diff --git a/.gitignore b/.gitignore index f85c6b1..ed683d3 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ -config.py \ No newline at end of file +config.py +project/config.py +project/bot.log + diff --git a/bot.log b/bot.log new file mode 100644 index 0000000..59023d6 --- /dev/null +++ b/bot.log @@ -0,0 +1,2 @@ +2024-08-26 16:15:10 - INFO - /start 451218808 +2024-08-26 16:15:10 - INFO - 451218808 diff --git a/bot.py b/bot.py deleted file mode 100644 index 6bccbce..0000000 --- a/bot.py +++ /dev/null @@ -1,114 +0,0 @@ -import telebot -from telebot import types - -# Укажите свой токен бота -API_TOKEN = '7092073070:AAGFOnZHUR86RdAjb7pgSN7plOiQe1_4Qow' -bot = telebot.TeleBot(API_TOKEN) - -# Словари для хранения данных пользователей -users = {} - -# Enum для ролей -class Role: - CURATOR = "Куратор" - FRESHMAN = "Первокурсник" - -# Стартовая команда -@bot.message_handler(commands=['start']) -def start(message): - markup = types.ReplyKeyboardMarkup(resize_keyboard=True) - item1 = types.KeyboardButton("Куратор") - item2 = types.KeyboardButton("Первокурсник") - markup.add(item1, item2) - - bot.send_message(message.chat.id, "Привет! Выберите, кем вы являетесь:", reply_markup=markup) - bot.register_next_step_handler(message, handle_role_selection) - -# Обработка выбора роли -def handle_role_selection(message): - if message.text == "Куратор": - role = Role.CURATOR - elif message.text == "Первокурсник": - role = Role.FRESHMAN - else: - bot.send_message(message.chat.id, "Некорректный выбор. Пожалуйста, выберите 'Куратор' или 'Первокурсник'.") - return - - # Сохраняем данные пользователя - user_id = message.from_user.id - users[user_id] = { - "role": role, - "name": "", - "group": "" - } - - bot.send_message(message.chat.id, "Введите ваше ФИО:") - bot.register_next_step_handler(message, enter_name) - -# Ввод ФИО -def enter_name(message): - user_id = message.from_user.id - users[user_id]["name"] = message.text - - bot.send_message(message.chat.id, "Введите вашу группу:") - bot.register_next_step_handler(message, enter_group) - -# Ввод группы -def enter_group(message): - user_id = message.from_user.id - users[user_id]["group"] = message.text - - role = users[user_id]["role"] - - markup = types.ReplyKeyboardMarkup(resize_keyboard=True) - if role == Role.CURATOR: - item1 = types.KeyboardButton("Отчитаться за мероприятие") - item2 = types.KeyboardButton("Добавить мероприятие") - markup.add(item1, item2) - bot.send_message(message.chat.id, "Вы куратор. Вы можете выбрать действие:", reply_markup=markup) - elif role == Role.FRESHMAN: - item1 = types.KeyboardButton("Задать вопрос куратору") - item2 = types.KeyboardButton("Поблагодарить куратора") - markup.add(item1, item2) - bot.send_message(message.chat.id, "Вы первокурсник. Вы можете выбрать действие:", reply_markup=markup) - -# Обработка инструкций для кураторов - -@bot.message_handler(func=lambda message: users.get(message.from_user.id, {}).get('role') == Role.CURATOR) -def handle_curator_actions(message): - if message.text == 'Отчитаться за мероприятие': - bot.send_message(message.chat.id, "Пожалуйста, пришлите фото мероприятия:") - bot.register_next_step_handler(message, upload_activity_photo) - elif message.text == 'Добавить мероприятие': - bot.send_message(message.chat.id, "Пожалуйста, опишите мероприятие:") - bot.register_next_step_handler(message, add_activity) - -def upload_activity_photo(message): - user_id = message.from_user.id - bot.send_message(message.chat.id, "Спасибо! Фото получено.") - -def add_activity(message): - description = message.text - bot.send_message(message.chat.id, f"Мероприятие добавлено: {description}") - -# Обработка инструкций для первокурсников -@bot.message_handler(func=lambda message: users.get(message.from_user.id, {}).get('role') == Role.FRESHMAN) -def handle_freshman_actions(message): - if message.text == 'Задать вопрос куратору': - bot.send_message(message.chat.id, "Пожалуйста, напишите свой вопрос:") - bot.register_next_step_handler(message, submit_question) - elif message.text == 'Поблагодарить куратора': - bot.send_message(message.chat.id, "Пожалуйста, пришлите фото с вашим куратором:") - bot.register_next_step_handler(message, upload_thank_you_photo) - -def submit_question(message): - question = message.text - bot.send_message(message.chat.id, f"Ваш вопрос отправлен: {question}") - -def upload_thank_you_photo(message): - user_id = message.from_user.id - bot.send_message(message.chat.id, "Спасибо! Фото получено.") - -# Запуск бота -if __name__ == '__main__': - bot.polling(none_stop=True) \ No newline at end of file diff --git a/env/Lib/site-packages/__pycache__/typing_extensions.cpython-311.pyc b/env/Lib/site-packages/__pycache__/typing_extensions.cpython-311.pyc new file mode 100644 index 0000000..0f399d7 Binary files /dev/null and b/env/Lib/site-packages/__pycache__/typing_extensions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles-23.2.1.dist-info/INSTALLER b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/aiofiles-23.2.1.dist-info/METADATA b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/METADATA new file mode 100644 index 0000000..61b6e3e --- /dev/null +++ b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/METADATA @@ -0,0 +1,291 @@ +Metadata-Version: 2.1 +Name: aiofiles +Version: 23.2.1 +Summary: File support for asyncio. +Project-URL: Changelog, https://github.com/Tinche/aiofiles#history +Project-URL: Bug Tracker, https://github.com/Tinche/aiofiles/issues +Project-URL: repository, https://github.com/Tinche/aiofiles +Author-email: Tin Tvrtkovic +License: Apache-2.0 +License-File: LICENSE +License-File: NOTICE +Classifier: Development Status :: 5 - Production/Stable +Classifier: Framework :: AsyncIO +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.7 +Description-Content-Type: text/markdown + +# aiofiles: file support for asyncio + +[![PyPI](https://img.shields.io/pypi/v/aiofiles.svg)](https://pypi.python.org/pypi/aiofiles) +[![Build](https://github.com/Tinche/aiofiles/workflows/CI/badge.svg)](https://github.com/Tinche/aiofiles/actions) +[![Coverage](https://img.shields.io/endpoint?url=https://gist.githubusercontent.com/Tinche/882f02e3df32136c847ba90d2688f06e/raw/covbadge.json)](https://github.com/Tinche/aiofiles/actions/workflows/main.yml) +[![Supported Python versions](https://img.shields.io/pypi/pyversions/aiofiles.svg)](https://github.com/Tinche/aiofiles) +[![Black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) + +**aiofiles** is an Apache2 licensed library, written in Python, for handling local +disk files in asyncio applications. + +Ordinary local file IO is blocking, and cannot easily and portably be made +asynchronous. This means doing file IO may interfere with asyncio applications, +which shouldn't block the executing thread. aiofiles helps with this by +introducing asynchronous versions of files that support delegating operations to +a separate thread pool. + +```python +async with aiofiles.open('filename', mode='r') as f: + contents = await f.read() +print(contents) +'My file contents' +``` + +Asynchronous iteration is also supported. + +```python +async with aiofiles.open('filename') as f: + async for line in f: + ... +``` + +Asynchronous interface to tempfile module. + +```python +async with aiofiles.tempfile.TemporaryFile('wb') as f: + await f.write(b'Hello, World!') +``` + +## Features + +- a file API very similar to Python's standard, blocking API +- support for buffered and unbuffered binary files, and buffered text files +- support for `async`/`await` ([PEP 492](https://peps.python.org/pep-0492/)) constructs +- async interface to tempfile module + +## Installation + +To install aiofiles, simply: + +```bash +$ pip install aiofiles +``` + +## Usage + +Files are opened using the `aiofiles.open()` coroutine, which in addition to +mirroring the builtin `open` accepts optional `loop` and `executor` +arguments. If `loop` is absent, the default loop will be used, as per the +set asyncio policy. If `executor` is not specified, the default event loop +executor will be used. + +In case of success, an asynchronous file object is returned with an +API identical to an ordinary file, except the following methods are coroutines +and delegate to an executor: + +- `close` +- `flush` +- `isatty` +- `read` +- `readall` +- `read1` +- `readinto` +- `readline` +- `readlines` +- `seek` +- `seekable` +- `tell` +- `truncate` +- `writable` +- `write` +- `writelines` + +In case of failure, one of the usual exceptions will be raised. + +`aiofiles.stdin`, `aiofiles.stdout`, `aiofiles.stderr`, +`aiofiles.stdin_bytes`, `aiofiles.stdout_bytes`, and +`aiofiles.stderr_bytes` provide async access to `sys.stdin`, +`sys.stdout`, `sys.stderr`, and their corresponding `.buffer` properties. + +The `aiofiles.os` module contains executor-enabled coroutine versions of +several useful `os` functions that deal with files: + +- `stat` +- `statvfs` +- `sendfile` +- `rename` +- `renames` +- `replace` +- `remove` +- `unlink` +- `mkdir` +- `makedirs` +- `rmdir` +- `removedirs` +- `link` +- `symlink` +- `readlink` +- `listdir` +- `scandir` +- `access` +- `path.exists` +- `path.isfile` +- `path.isdir` +- `path.islink` +- `path.ismount` +- `path.getsize` +- `path.getatime` +- `path.getctime` +- `path.samefile` +- `path.sameopenfile` + +### Tempfile + +**aiofiles.tempfile** implements the following interfaces: + +- TemporaryFile +- NamedTemporaryFile +- SpooledTemporaryFile +- TemporaryDirectory + +Results return wrapped with a context manager allowing use with async with and async for. + +```python +async with aiofiles.tempfile.NamedTemporaryFile('wb+') as f: + await f.write(b'Line1\n Line2') + await f.seek(0) + async for line in f: + print(line) + +async with aiofiles.tempfile.TemporaryDirectory() as d: + filename = os.path.join(d, "file.ext") +``` + +### Writing tests for aiofiles + +Real file IO can be mocked by patching `aiofiles.threadpool.sync_open` +as desired. The return type also needs to be registered with the +`aiofiles.threadpool.wrap` dispatcher: + +```python +aiofiles.threadpool.wrap.register(mock.MagicMock)( + lambda *args, **kwargs: threadpool.AsyncBufferedIOBase(*args, **kwargs)) + +async def test_stuff(): + data = 'data' + mock_file = mock.MagicMock() + + with mock.patch('aiofiles.threadpool.sync_open', return_value=mock_file) as mock_open: + async with aiofiles.open('filename', 'w') as f: + await f.write(data) + + mock_file.write.assert_called_once_with(data) +``` + +### History + +#### 23.2.1 (2023-08-09) + +- Import `os.statvfs` conditionally to fix importing on non-UNIX systems. + [#171](https://github.com/Tinche/aiofiles/issues/171) [#172](https://github.com/Tinche/aiofiles/pull/172) + +#### 23.2.0 (2023-08-09) + +- aiofiles is now tested on Python 3.12 too. + [#166](https://github.com/Tinche/aiofiles/issues/166) [#168](https://github.com/Tinche/aiofiles/pull/168) +- On Python 3.12, `aiofiles.tempfile.NamedTemporaryFile` now accepts a `delete_on_close` argument, just like the stdlib version. +- On Python 3.12, `aiofiles.tempfile.NamedTemporaryFile` no longer exposes a `delete` attribute, just like the stdlib version. +- Added `aiofiles.os.statvfs` and `aiofiles.os.path.ismount`. + [#162](https://github.com/Tinche/aiofiles/pull/162) +- Use [PDM](https://pdm.fming.dev/latest/) instead of Poetry. + [#169](https://github.com/Tinche/aiofiles/pull/169) + +#### 23.1.0 (2023-02-09) + +- Added `aiofiles.os.access`. + [#146](https://github.com/Tinche/aiofiles/pull/146) +- Removed `aiofiles.tempfile.temptypes.AsyncSpooledTemporaryFile.softspace`. + [#151](https://github.com/Tinche/aiofiles/pull/151) +- Added `aiofiles.stdin`, `aiofiles.stdin_bytes`, and other stdio streams. + [#154](https://github.com/Tinche/aiofiles/pull/154) +- Transition to `asyncio.get_running_loop` (vs `asyncio.get_event_loop`) internally. + +#### 22.1.0 (2022-09-04) + +- Added `aiofiles.os.path.islink`. + [#126](https://github.com/Tinche/aiofiles/pull/126) +- Added `aiofiles.os.readlink`. + [#125](https://github.com/Tinche/aiofiles/pull/125) +- Added `aiofiles.os.symlink`. + [#124](https://github.com/Tinche/aiofiles/pull/124) +- Added `aiofiles.os.unlink`. + [#123](https://github.com/Tinche/aiofiles/pull/123) +- Added `aiofiles.os.link`. + [#121](https://github.com/Tinche/aiofiles/pull/121) +- Added `aiofiles.os.renames`. + [#120](https://github.com/Tinche/aiofiles/pull/120) +- Added `aiofiles.os.{listdir, scandir}`. + [#143](https://github.com/Tinche/aiofiles/pull/143) +- Switched to CalVer. +- Dropped Python 3.6 support. If you require it, use version 0.8.0. +- aiofiles is now tested on Python 3.11. + +#### 0.8.0 (2021-11-27) + +- aiofiles is now tested on Python 3.10. +- Added `aiofiles.os.replace`. + [#107](https://github.com/Tinche/aiofiles/pull/107) +- Added `aiofiles.os.{makedirs, removedirs}`. +- Added `aiofiles.os.path.{exists, isfile, isdir, getsize, getatime, getctime, samefile, sameopenfile}`. + [#63](https://github.com/Tinche/aiofiles/pull/63) +- Added `suffix`, `prefix`, `dir` args to `aiofiles.tempfile.TemporaryDirectory`. + [#116](https://github.com/Tinche/aiofiles/pull/116) + +#### 0.7.0 (2021-05-17) + +- Added the `aiofiles.tempfile` module for async temporary files. + [#56](https://github.com/Tinche/aiofiles/pull/56) +- Switched to Poetry and GitHub actions. +- Dropped 3.5 support. + +#### 0.6.0 (2020-10-27) + +- `aiofiles` is now tested on ppc64le. +- Added `name` and `mode` properties to async file objects. + [#82](https://github.com/Tinche/aiofiles/pull/82) +- Fixed a DeprecationWarning internally. + [#75](https://github.com/Tinche/aiofiles/pull/75) +- Python 3.9 support and tests. + +#### 0.5.0 (2020-04-12) + +- Python 3.8 support. Code base modernization (using `async/await` instead of `asyncio.coroutine`/`yield from`). +- Added `aiofiles.os.remove`, `aiofiles.os.rename`, `aiofiles.os.mkdir`, `aiofiles.os.rmdir`. + [#62](https://github.com/Tinche/aiofiles/pull/62) + +#### 0.4.0 (2018-08-11) + +- Python 3.7 support. +- Removed Python 3.3/3.4 support. If you use these versions, stick to aiofiles 0.3.x. + +#### 0.3.2 (2017-09-23) + +- The LICENSE is now included in the sdist. + [#31](https://github.com/Tinche/aiofiles/pull/31) + +#### 0.3.1 (2017-03-10) + +- Introduced a changelog. +- `aiofiles.os.sendfile` will now work if the standard `os` module contains a `sendfile` function. + +### Contributing + +Contributions are very welcome. Tests can be run with `tox`, please ensure +the coverage at least stays the same before you submit a pull request. diff --git a/env/Lib/site-packages/aiofiles-23.2.1.dist-info/RECORD b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/RECORD new file mode 100644 index 0000000..9e403d8 --- /dev/null +++ b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/RECORD @@ -0,0 +1,26 @@ +aiofiles-23.2.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiofiles-23.2.1.dist-info/METADATA,sha256=cot28p_PNjdl_MK--l9Qu2e6QOv9OxdHrKbjLmYf9Uw,9673 +aiofiles-23.2.1.dist-info/RECORD,, +aiofiles-23.2.1.dist-info/WHEEL,sha256=KGYbc1zXlYddvwxnNty23BeaKzh7YuoSIvIMO4jEhvw,87 +aiofiles-23.2.1.dist-info/licenses/LICENSE,sha256=y16Ofl9KOYjhBjwULGDcLfdWBfTEZRXnduOspt-XbhQ,11325 +aiofiles-23.2.1.dist-info/licenses/NOTICE,sha256=EExY0dRQvWR0wJ2LZLwBgnM6YKw9jCU-M0zegpRSD_E,55 +aiofiles/__init__.py,sha256=1iAMJQyJtX3LGIS0AoFTJeO1aJ_RK2jpBSBhg0VoIrE,344 +aiofiles/__pycache__/__init__.cpython-311.pyc,, +aiofiles/__pycache__/base.cpython-311.pyc,, +aiofiles/__pycache__/os.cpython-311.pyc,, +aiofiles/__pycache__/ospath.cpython-311.pyc,, +aiofiles/base.py,sha256=rZwA151Ji8XlBkzvDmcF1CgDTY2iKNuJMfvNlM0s0E0,2684 +aiofiles/os.py,sha256=zuFGaIyGCGUuFb7trFFEm6SLdCRqTFsSV0mY6SO8z3M,970 +aiofiles/ospath.py,sha256=zqG2VFzRb6yYiIOWipqsdgvZmoMTFvZmBdkxkAl1FT4,764 +aiofiles/tempfile/__init__.py,sha256=hFSNTOjOUv371Ozdfy6FIxeln46Nm3xOVh4ZR3Q94V0,10244 +aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc,, +aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc,, +aiofiles/tempfile/temptypes.py,sha256=ddEvNjMLVlr7WUILCe6ypTqw77yREeIonTk16Uw_NVs,2093 +aiofiles/threadpool/__init__.py,sha256=c_aexl1t193iKdPZaolPEEbHDrQ0RrsH_HTAToMPQBo,3171 +aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc,, +aiofiles/threadpool/__pycache__/binary.cpython-311.pyc,, +aiofiles/threadpool/__pycache__/text.cpython-311.pyc,, +aiofiles/threadpool/__pycache__/utils.cpython-311.pyc,, +aiofiles/threadpool/binary.py,sha256=hp-km9VCRu0MLz_wAEUfbCz7OL7xtn9iGAawabpnp5U,2315 +aiofiles/threadpool/text.py,sha256=fNmpw2PEkj0BZSldipJXAgZqVGLxALcfOMiuDQ54Eas,1223 +aiofiles/threadpool/utils.py,sha256=B59dSZwO_WZs2dFFycKeA91iD2Xq2nNw1EFF8YMBI5k,1868 diff --git a/env/Lib/site-packages/aiofiles-23.2.1.dist-info/WHEEL b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/WHEEL new file mode 100644 index 0000000..9a7c9d3 --- /dev/null +++ b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.17.1 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/env/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/LICENSE b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/LICENSE new file mode 100644 index 0000000..e06d208 --- /dev/null +++ b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/env/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/NOTICE b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/NOTICE new file mode 100644 index 0000000..d134f28 --- /dev/null +++ b/env/Lib/site-packages/aiofiles-23.2.1.dist-info/licenses/NOTICE @@ -0,0 +1,2 @@ +Asyncio support for files +Copyright 2016 Tin Tvrtkovic diff --git a/env/Lib/site-packages/aiofiles/__init__.py b/env/Lib/site-packages/aiofiles/__init__.py new file mode 100644 index 0000000..9e75111 --- /dev/null +++ b/env/Lib/site-packages/aiofiles/__init__.py @@ -0,0 +1,22 @@ +"""Utilities for asyncio-friendly file handling.""" +from .threadpool import ( + open, + stdin, + stdout, + stderr, + stdin_bytes, + stdout_bytes, + stderr_bytes, +) +from . import tempfile + +__all__ = [ + "open", + "tempfile", + "stdin", + "stdout", + "stderr", + "stdin_bytes", + "stdout_bytes", + "stderr_bytes", +] diff --git a/env/Lib/site-packages/aiofiles/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiofiles/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..86986e8 Binary files /dev/null and b/env/Lib/site-packages/aiofiles/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiofiles/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..e5274f8 Binary files /dev/null and b/env/Lib/site-packages/aiofiles/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/__pycache__/os.cpython-311.pyc b/env/Lib/site-packages/aiofiles/__pycache__/os.cpython-311.pyc new file mode 100644 index 0000000..3581b05 Binary files /dev/null and b/env/Lib/site-packages/aiofiles/__pycache__/os.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/__pycache__/ospath.cpython-311.pyc b/env/Lib/site-packages/aiofiles/__pycache__/ospath.cpython-311.pyc new file mode 100644 index 0000000..5d2097c Binary files /dev/null and b/env/Lib/site-packages/aiofiles/__pycache__/ospath.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/base.py b/env/Lib/site-packages/aiofiles/base.py new file mode 100644 index 0000000..07f2c2e --- /dev/null +++ b/env/Lib/site-packages/aiofiles/base.py @@ -0,0 +1,113 @@ +"""Various base classes.""" +from types import coroutine +from collections.abc import Coroutine +from asyncio import get_running_loop + + +class AsyncBase: + def __init__(self, file, loop, executor): + self._file = file + self._executor = executor + self._ref_loop = loop + + @property + def _loop(self): + return self._ref_loop or get_running_loop() + + def __aiter__(self): + """We are our own iterator.""" + return self + + def __repr__(self): + return super().__repr__() + " wrapping " + repr(self._file) + + async def __anext__(self): + """Simulate normal file iteration.""" + line = await self.readline() + if line: + return line + else: + raise StopAsyncIteration + + +class AsyncIndirectBase(AsyncBase): + def __init__(self, name, loop, executor, indirect): + self._indirect = indirect + self._name = name + super().__init__(None, loop, executor) + + @property + def _file(self): + return self._indirect() + + @_file.setter + def _file(self, v): + pass # discard writes + + +class _ContextManager(Coroutine): + __slots__ = ("_coro", "_obj") + + def __init__(self, coro): + self._coro = coro + self._obj = None + + def send(self, value): + return self._coro.send(value) + + def throw(self, typ, val=None, tb=None): + if val is None: + return self._coro.throw(typ) + elif tb is None: + return self._coro.throw(typ, val) + else: + return self._coro.throw(typ, val, tb) + + def close(self): + return self._coro.close() + + @property + def gi_frame(self): + return self._coro.gi_frame + + @property + def gi_running(self): + return self._coro.gi_running + + @property + def gi_code(self): + return self._coro.gi_code + + def __next__(self): + return self.send(None) + + @coroutine + def __iter__(self): + resp = yield from self._coro + return resp + + def __await__(self): + resp = yield from self._coro + return resp + + async def __anext__(self): + resp = await self._coro + return resp + + async def __aenter__(self): + self._obj = await self._coro + return self._obj + + async def __aexit__(self, exc_type, exc, tb): + self._obj.close() + self._obj = None + + +class AiofilesContextManager(_ContextManager): + """An adjusted async context manager for aiofiles.""" + + async def __aexit__(self, exc_type, exc_val, exc_tb): + await get_running_loop().run_in_executor( + None, self._obj._file.__exit__, exc_type, exc_val, exc_tb + ) + self._obj = None diff --git a/env/Lib/site-packages/aiofiles/os.py b/env/Lib/site-packages/aiofiles/os.py new file mode 100644 index 0000000..29bc748 --- /dev/null +++ b/env/Lib/site-packages/aiofiles/os.py @@ -0,0 +1,51 @@ +"""Async executor versions of file functions from the os module.""" +import os + +from . import ospath as path +from .ospath import wrap + +__all__ = [ + "path", + "stat", + "statvfs", + "rename", + "renames", + "replace", + "remove", + "unlink", + "mkdir", + "makedirs", + "rmdir", + "removedirs", + "link", + "symlink", + "readlink", + "listdir", + "scandir", + "access", + "sendfile", + "wrap", +] + + +stat = wrap(os.stat) +rename = wrap(os.rename) +renames = wrap(os.renames) +replace = wrap(os.replace) +remove = wrap(os.remove) +unlink = wrap(os.unlink) +mkdir = wrap(os.mkdir) +makedirs = wrap(os.makedirs) +rmdir = wrap(os.rmdir) +removedirs = wrap(os.removedirs) +link = wrap(os.link) +symlink = wrap(os.symlink) +readlink = wrap(os.readlink) +listdir = wrap(os.listdir) +scandir = wrap(os.scandir) +access = wrap(os.access) + +if hasattr(os, "sendfile"): + sendfile = wrap(os.sendfile) +if hasattr(os, "statvfs"): + statvfs = wrap(os.statvfs) diff --git a/env/Lib/site-packages/aiofiles/ospath.py b/env/Lib/site-packages/aiofiles/ospath.py new file mode 100644 index 0000000..5f32a43 --- /dev/null +++ b/env/Lib/site-packages/aiofiles/ospath.py @@ -0,0 +1,28 @@ +"""Async executor versions of file functions from the os.path module.""" +import asyncio +from functools import partial, wraps +from os import path + + +def wrap(func): + @wraps(func) + async def run(*args, loop=None, executor=None, **kwargs): + if loop is None: + loop = asyncio.get_running_loop() + pfunc = partial(func, *args, **kwargs) + return await loop.run_in_executor(executor, pfunc) + + return run + + +exists = wrap(path.exists) +isfile = wrap(path.isfile) +isdir = wrap(path.isdir) +islink = wrap(path.islink) +ismount = wrap(path.ismount) +getsize = wrap(path.getsize) +getmtime = wrap(path.getmtime) +getatime = wrap(path.getatime) +getctime = wrap(path.getctime) +samefile = wrap(path.samefile) +sameopenfile = wrap(path.sameopenfile) diff --git a/env/Lib/site-packages/aiofiles/tempfile/__init__.py b/env/Lib/site-packages/aiofiles/tempfile/__init__.py new file mode 100644 index 0000000..75d10b6 --- /dev/null +++ b/env/Lib/site-packages/aiofiles/tempfile/__init__.py @@ -0,0 +1,357 @@ +import asyncio +from functools import partial, singledispatch +from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOBase +from tempfile import NamedTemporaryFile as syncNamedTemporaryFile +from tempfile import SpooledTemporaryFile as syncSpooledTemporaryFile +from tempfile import TemporaryDirectory as syncTemporaryDirectory +from tempfile import TemporaryFile as syncTemporaryFile +from tempfile import _TemporaryFileWrapper as syncTemporaryFileWrapper + +from ..base import AiofilesContextManager +from ..threadpool.binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO +from ..threadpool.text import AsyncTextIOWrapper +from .temptypes import AsyncSpooledTemporaryFile, AsyncTemporaryDirectory +import sys + +__all__ = [ + "NamedTemporaryFile", + "TemporaryFile", + "SpooledTemporaryFile", + "TemporaryDirectory", +] + + +# ================================================================ +# Public methods for async open and return of temp file/directory +# objects with async interface +# ================================================================ +if sys.version_info >= (3, 12): + + def NamedTemporaryFile( + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + delete=True, + delete_on_close=True, + loop=None, + executor=None, + ): + """Async open a named temporary file""" + return AiofilesContextManager( + _temporary_file( + named=True, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + delete_on_close=delete_on_close, + loop=loop, + executor=executor, + ) + ) + +else: + + def NamedTemporaryFile( + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + delete=True, + loop=None, + executor=None, + ): + """Async open a named temporary file""" + return AiofilesContextManager( + _temporary_file( + named=True, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + loop=loop, + executor=executor, + ) + ) + + +def TemporaryFile( + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + loop=None, + executor=None, +): + """Async open an unnamed temporary file""" + return AiofilesContextManager( + _temporary_file( + named=False, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + loop=loop, + executor=executor, + ) + ) + + +def SpooledTemporaryFile( + max_size=0, + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + loop=None, + executor=None, +): + """Async open a spooled temporary file""" + return AiofilesContextManager( + _spooled_temporary_file( + max_size=max_size, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + loop=loop, + executor=executor, + ) + ) + + +def TemporaryDirectory(suffix=None, prefix=None, dir=None, loop=None, executor=None): + """Async open a temporary directory""" + return AiofilesContextManagerTempDir( + _temporary_directory( + suffix=suffix, prefix=prefix, dir=dir, loop=loop, executor=executor + ) + ) + + +# ========================================================= +# Internal coroutines to open new temp files/directories +# ========================================================= +if sys.version_info >= (3, 12): + + async def _temporary_file( + named=True, + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + delete=True, + delete_on_close=True, + loop=None, + executor=None, + max_size=0, + ): + """Async method to open a temporary file with async interface""" + if loop is None: + loop = asyncio.get_running_loop() + + if named: + cb = partial( + syncNamedTemporaryFile, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + delete_on_close=delete_on_close, + ) + else: + cb = partial( + syncTemporaryFile, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + ) + + f = await loop.run_in_executor(executor, cb) + + # Wrap based on type of underlying IO object + if type(f) is syncTemporaryFileWrapper: + # _TemporaryFileWrapper was used (named files) + result = wrap(f.file, f, loop=loop, executor=executor) + result._closer = f._closer + return result + else: + # IO object was returned directly without wrapper + return wrap(f, f, loop=loop, executor=executor) + +else: + + async def _temporary_file( + named=True, + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + delete=True, + loop=None, + executor=None, + max_size=0, + ): + """Async method to open a temporary file with async interface""" + if loop is None: + loop = asyncio.get_running_loop() + + if named: + cb = partial( + syncNamedTemporaryFile, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + delete=delete, + ) + else: + cb = partial( + syncTemporaryFile, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + ) + + f = await loop.run_in_executor(executor, cb) + + # Wrap based on type of underlying IO object + if type(f) is syncTemporaryFileWrapper: + # _TemporaryFileWrapper was used (named files) + result = wrap(f.file, f, loop=loop, executor=executor) + # add delete property + result.delete = f.delete + return result + else: + # IO object was returned directly without wrapper + return wrap(f, f, loop=loop, executor=executor) + + +async def _spooled_temporary_file( + max_size=0, + mode="w+b", + buffering=-1, + encoding=None, + newline=None, + suffix=None, + prefix=None, + dir=None, + loop=None, + executor=None, +): + """Open a spooled temporary file with async interface""" + if loop is None: + loop = asyncio.get_running_loop() + + cb = partial( + syncSpooledTemporaryFile, + max_size=max_size, + mode=mode, + buffering=buffering, + encoding=encoding, + newline=newline, + suffix=suffix, + prefix=prefix, + dir=dir, + ) + + f = await loop.run_in_executor(executor, cb) + + # Single interface provided by SpooledTemporaryFile for all modes + return AsyncSpooledTemporaryFile(f, loop=loop, executor=executor) + + +async def _temporary_directory( + suffix=None, prefix=None, dir=None, loop=None, executor=None +): + """Async method to open a temporary directory with async interface""" + if loop is None: + loop = asyncio.get_running_loop() + + cb = partial(syncTemporaryDirectory, suffix, prefix, dir) + f = await loop.run_in_executor(executor, cb) + + return AsyncTemporaryDirectory(f, loop=loop, executor=executor) + + +class AiofilesContextManagerTempDir(AiofilesContextManager): + """With returns the directory location, not the object (matching sync lib)""" + + async def __aenter__(self): + self._obj = await self._coro + return self._obj.name + + +@singledispatch +def wrap(base_io_obj, file, *, loop=None, executor=None): + """Wrap the object with interface based on type of underlying IO""" + raise TypeError("Unsupported IO type: {}".format(base_io_obj)) + + +@wrap.register(TextIOBase) +def _(base_io_obj, file, *, loop=None, executor=None): + return AsyncTextIOWrapper(file, loop=loop, executor=executor) + + +@wrap.register(BufferedWriter) +def _(base_io_obj, file, *, loop=None, executor=None): + return AsyncBufferedIOBase(file, loop=loop, executor=executor) + + +@wrap.register(BufferedReader) +@wrap.register(BufferedRandom) +def _(base_io_obj, file, *, loop=None, executor=None): + return AsyncBufferedReader(file, loop=loop, executor=executor) + + +@wrap.register(FileIO) +def _(base_io_obj, file, *, loop=None, executor=None): + return AsyncFileIO(file, loop=loop, executor=executor) diff --git a/env/Lib/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..49a695b Binary files /dev/null and b/env/Lib/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc b/env/Lib/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc new file mode 100644 index 0000000..959020b Binary files /dev/null and b/env/Lib/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/tempfile/temptypes.py b/env/Lib/site-packages/aiofiles/tempfile/temptypes.py new file mode 100644 index 0000000..dccee6c --- /dev/null +++ b/env/Lib/site-packages/aiofiles/tempfile/temptypes.py @@ -0,0 +1,69 @@ +"""Async wrappers for spooled temp files and temp directory objects""" +from functools import partial + +from ..base import AsyncBase +from ..threadpool.utils import ( + cond_delegate_to_executor, + delegate_to_executor, + proxy_property_directly, +) + + +@delegate_to_executor("fileno", "rollover") +@cond_delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readline", + "readlines", + "seek", + "tell", + "truncate", +) +@proxy_property_directly("closed", "encoding", "mode", "name", "newlines") +class AsyncSpooledTemporaryFile(AsyncBase): + """Async wrapper for SpooledTemporaryFile class""" + + async def _check(self): + if self._file._rolled: + return + max_size = self._file._max_size + if max_size and self._file.tell() > max_size: + await self.rollover() + + async def write(self, s): + """Implementation to anticipate rollover""" + if self._file._rolled: + cb = partial(self._file.write, s) + return await self._loop.run_in_executor(self._executor, cb) + else: + file = self._file._file # reference underlying base IO object + rv = file.write(s) + await self._check() + return rv + + async def writelines(self, iterable): + """Implementation to anticipate rollover""" + if self._file._rolled: + cb = partial(self._file.writelines, iterable) + return await self._loop.run_in_executor(self._executor, cb) + else: + file = self._file._file # reference underlying base IO object + rv = file.writelines(iterable) + await self._check() + return rv + + +@delegate_to_executor("cleanup") +@proxy_property_directly("name") +class AsyncTemporaryDirectory: + """Async wrapper for TemporaryDirectory class""" + + def __init__(self, file, loop, executor): + self._file = file + self._loop = loop + self._executor = executor + + async def close(self): + await self.cleanup() diff --git a/env/Lib/site-packages/aiofiles/threadpool/__init__.py b/env/Lib/site-packages/aiofiles/threadpool/__init__.py new file mode 100644 index 0000000..a1cc673 --- /dev/null +++ b/env/Lib/site-packages/aiofiles/threadpool/__init__.py @@ -0,0 +1,141 @@ +"""Handle files using a thread pool executor.""" +import asyncio +import sys +from functools import partial, singledispatch +from io import ( + BufferedIOBase, + BufferedRandom, + BufferedReader, + BufferedWriter, + FileIO, + TextIOBase, +) +from types import coroutine + +from ..base import AiofilesContextManager +from .binary import ( + AsyncBufferedIOBase, + AsyncBufferedReader, + AsyncFileIO, + AsyncIndirectBufferedIOBase, +) +from .text import AsyncTextIndirectIOWrapper, AsyncTextIOWrapper + +sync_open = open + +__all__ = ( + "open", + "stdin", + "stdout", + "stderr", + "stdin_bytes", + "stdout_bytes", + "stderr_bytes", +) + + +def open( + file, + mode="r", + buffering=-1, + encoding=None, + errors=None, + newline=None, + closefd=True, + opener=None, + *, + loop=None, + executor=None, +): + return AiofilesContextManager( + _open( + file, + mode=mode, + buffering=buffering, + encoding=encoding, + errors=errors, + newline=newline, + closefd=closefd, + opener=opener, + loop=loop, + executor=executor, + ) + ) + + +@coroutine +def _open( + file, + mode="r", + buffering=-1, + encoding=None, + errors=None, + newline=None, + closefd=True, + opener=None, + *, + loop=None, + executor=None, +): + """Open an asyncio file.""" + if loop is None: + loop = asyncio.get_running_loop() + cb = partial( + sync_open, + file, + mode=mode, + buffering=buffering, + encoding=encoding, + errors=errors, + newline=newline, + closefd=closefd, + opener=opener, + ) + f = yield from loop.run_in_executor(executor, cb) + + return wrap(f, loop=loop, executor=executor) + + +@singledispatch +def wrap(file, *, loop=None, executor=None): + raise TypeError("Unsupported io type: {}.".format(file)) + + +@wrap.register(TextIOBase) +def _(file, *, loop=None, executor=None): + return AsyncTextIOWrapper(file, loop=loop, executor=executor) + + +@wrap.register(BufferedWriter) +@wrap.register(BufferedIOBase) +def _(file, *, loop=None, executor=None): + return AsyncBufferedIOBase(file, loop=loop, executor=executor) + + +@wrap.register(BufferedReader) +@wrap.register(BufferedRandom) +def _(file, *, loop=None, executor=None): + return AsyncBufferedReader(file, loop=loop, executor=executor) + + +@wrap.register(FileIO) +def _(file, *, loop=None, executor=None): + return AsyncFileIO(file, loop=loop, executor=executor) + + +stdin = AsyncTextIndirectIOWrapper("sys.stdin", None, None, indirect=lambda: sys.stdin) +stdout = AsyncTextIndirectIOWrapper( + "sys.stdout", None, None, indirect=lambda: sys.stdout +) +stderr = AsyncTextIndirectIOWrapper( + "sys.stderr", None, None, indirect=lambda: sys.stderr +) +stdin_bytes = AsyncIndirectBufferedIOBase( + "sys.stdin.buffer", None, None, indirect=lambda: sys.stdin.buffer +) +stdout_bytes = AsyncIndirectBufferedIOBase( + "sys.stdout.buffer", None, None, indirect=lambda: sys.stdout.buffer +) +stderr_bytes = AsyncIndirectBufferedIOBase( + "sys.stderr.buffer", None, None, indirect=lambda: sys.stderr.buffer +) diff --git a/env/Lib/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..ea5209d Binary files /dev/null and b/env/Lib/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-311.pyc b/env/Lib/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-311.pyc new file mode 100644 index 0000000..30133f7 Binary files /dev/null and b/env/Lib/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/threadpool/__pycache__/text.cpython-311.pyc b/env/Lib/site-packages/aiofiles/threadpool/__pycache__/text.cpython-311.pyc new file mode 100644 index 0000000..aa84cc4 Binary files /dev/null and b/env/Lib/site-packages/aiofiles/threadpool/__pycache__/text.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-311.pyc b/env/Lib/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000..f942125 Binary files /dev/null and b/env/Lib/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiofiles/threadpool/binary.py b/env/Lib/site-packages/aiofiles/threadpool/binary.py new file mode 100644 index 0000000..63fcaff --- /dev/null +++ b/env/Lib/site-packages/aiofiles/threadpool/binary.py @@ -0,0 +1,104 @@ +from ..base import AsyncBase, AsyncIndirectBase +from .utils import delegate_to_executor, proxy_method_directly, proxy_property_directly + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "read1", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly("closed", "raw", "name", "mode") +class AsyncBufferedIOBase(AsyncBase): + """The asyncio executor version of io.BufferedWriter and BufferedIOBase.""" + + +@delegate_to_executor("peek") +class AsyncBufferedReader(AsyncBufferedIOBase): + """The asyncio executor version of io.BufferedReader and Random.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readall", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("fileno", "readable") +@proxy_property_directly("closed", "name", "mode") +class AsyncFileIO(AsyncBase): + """The asyncio executor version of io.FileIO.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "read1", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly("closed", "raw", "name", "mode") +class AsyncIndirectBufferedIOBase(AsyncIndirectBase): + """The indirect asyncio executor version of io.BufferedWriter and BufferedIOBase.""" + + +@delegate_to_executor("peek") +class AsyncIndirectBufferedReader(AsyncIndirectBufferedIOBase): + """The indirect asyncio executor version of io.BufferedReader and Random.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readall", + "readinto", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "writable", + "write", + "writelines", +) +@proxy_method_directly("fileno", "readable") +@proxy_property_directly("closed", "name", "mode") +class AsyncIndirectFileIO(AsyncIndirectBase): + """The indirect asyncio executor version of io.FileIO.""" diff --git a/env/Lib/site-packages/aiofiles/threadpool/text.py b/env/Lib/site-packages/aiofiles/threadpool/text.py new file mode 100644 index 0000000..0e62590 --- /dev/null +++ b/env/Lib/site-packages/aiofiles/threadpool/text.py @@ -0,0 +1,64 @@ +from ..base import AsyncBase, AsyncIndirectBase +from .utils import delegate_to_executor, proxy_method_directly, proxy_property_directly + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readable", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "write", + "writable", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly( + "buffer", + "closed", + "encoding", + "errors", + "line_buffering", + "newlines", + "name", + "mode", +) +class AsyncTextIOWrapper(AsyncBase): + """The asyncio executor version of io.TextIOWrapper.""" + + +@delegate_to_executor( + "close", + "flush", + "isatty", + "read", + "readable", + "readline", + "readlines", + "seek", + "seekable", + "tell", + "truncate", + "write", + "writable", + "writelines", +) +@proxy_method_directly("detach", "fileno", "readable") +@proxy_property_directly( + "buffer", + "closed", + "encoding", + "errors", + "line_buffering", + "newlines", + "name", + "mode", +) +class AsyncTextIndirectIOWrapper(AsyncIndirectBase): + """The indirect asyncio executor version of io.TextIOWrapper.""" diff --git a/env/Lib/site-packages/aiofiles/threadpool/utils.py b/env/Lib/site-packages/aiofiles/threadpool/utils.py new file mode 100644 index 0000000..5fd3bb9 --- /dev/null +++ b/env/Lib/site-packages/aiofiles/threadpool/utils.py @@ -0,0 +1,72 @@ +import functools + + +def delegate_to_executor(*attrs): + def cls_builder(cls): + for attr_name in attrs: + setattr(cls, attr_name, _make_delegate_method(attr_name)) + return cls + + return cls_builder + + +def proxy_method_directly(*attrs): + def cls_builder(cls): + for attr_name in attrs: + setattr(cls, attr_name, _make_proxy_method(attr_name)) + return cls + + return cls_builder + + +def proxy_property_directly(*attrs): + def cls_builder(cls): + for attr_name in attrs: + setattr(cls, attr_name, _make_proxy_property(attr_name)) + return cls + + return cls_builder + + +def cond_delegate_to_executor(*attrs): + def cls_builder(cls): + for attr_name in attrs: + setattr(cls, attr_name, _make_cond_delegate_method(attr_name)) + return cls + + return cls_builder + + +def _make_delegate_method(attr_name): + async def method(self, *args, **kwargs): + cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs) + return await self._loop.run_in_executor(self._executor, cb) + + return method + + +def _make_proxy_method(attr_name): + def method(self, *args, **kwargs): + return getattr(self._file, attr_name)(*args, **kwargs) + + return method + + +def _make_proxy_property(attr_name): + def proxy_property(self): + return getattr(self._file, attr_name) + + return property(proxy_property) + + +def _make_cond_delegate_method(attr_name): + """For spooled temp files, delegate only if rolled to file object""" + + async def method(self, *args, **kwargs): + if self._file._rolled: + cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs) + return await self._loop.run_in_executor(self._executor, cb) + else: + return getattr(self._file, attr_name)(*args, **kwargs) + + return method diff --git a/env/Lib/site-packages/aiogram-3.12.0.dist-info/INSTALLER b/env/Lib/site-packages/aiogram-3.12.0.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/aiogram-3.12.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/aiogram-3.12.0.dist-info/METADATA b/env/Lib/site-packages/aiogram-3.12.0.dist-info/METADATA new file mode 100644 index 0000000..e0470f1 --- /dev/null +++ b/env/Lib/site-packages/aiogram-3.12.0.dist-info/METADATA @@ -0,0 +1,163 @@ +Metadata-Version: 2.3 +Name: aiogram +Version: 3.12.0 +Summary: Modern and fully asynchronous framework for Telegram Bot API +Project-URL: Homepage, https://aiogram.dev/ +Project-URL: Documentation, https://docs.aiogram.dev/ +Project-URL: Repository, https://github.com/aiogram/aiogram/ +Author-email: Alex Root Junior +Maintainer-email: Alex Root Junior +License-Expression: MIT +License-File: LICENSE +Keywords: api,asyncio,bot,framework,telegram,wrapper +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Framework :: AsyncIO +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: System Administrators +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Communications :: Chat +Classifier: Topic :: Software Development :: Libraries :: Application Frameworks +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Requires-Python: >=3.8 +Requires-Dist: aiofiles~=23.2.1 +Requires-Dist: aiohttp<3.11,>=3.9.0 +Requires-Dist: certifi>=2023.7.22 +Requires-Dist: magic-filter<1.1,>=1.0.12 +Requires-Dist: pydantic<2.9,>=2.4.1 +Requires-Dist: typing-extensions<=5.0,>=4.7.0 +Provides-Extra: cli +Requires-Dist: aiogram-cli~=1.0.3; extra == 'cli' +Provides-Extra: dev +Requires-Dist: black~=24.4.2; extra == 'dev' +Requires-Dist: isort~=5.13.2; extra == 'dev' +Requires-Dist: motor-types~=1.0.0b4; extra == 'dev' +Requires-Dist: mypy~=1.10.0; extra == 'dev' +Requires-Dist: packaging~=24.1; extra == 'dev' +Requires-Dist: pre-commit~=3.5; extra == 'dev' +Requires-Dist: ruff~=0.5.1; extra == 'dev' +Requires-Dist: toml~=0.10.2; extra == 'dev' +Provides-Extra: docs +Requires-Dist: furo~=2023.9.10; extra == 'docs' +Requires-Dist: markdown-include~=0.8.1; extra == 'docs' +Requires-Dist: pygments~=2.16.1; extra == 'docs' +Requires-Dist: pymdown-extensions~=10.3; extra == 'docs' +Requires-Dist: sphinx-autobuild~=2021.3.14; extra == 'docs' +Requires-Dist: sphinx-copybutton~=0.5.2; extra == 'docs' +Requires-Dist: sphinx-intl~=2.1.0; extra == 'docs' +Requires-Dist: sphinx-substitution-extensions~=2022.2.16; extra == 'docs' +Requires-Dist: sphinxcontrib-towncrier~=0.4.0a0; extra == 'docs' +Requires-Dist: sphinx~=7.2.6; extra == 'docs' +Requires-Dist: towncrier~=24.7.1; extra == 'docs' +Provides-Extra: fast +Requires-Dist: aiodns>=3.0.0; extra == 'fast' +Requires-Dist: uvloop>=0.17.0; ((sys_platform == 'darwin' or sys_platform == 'linux') and platform_python_implementation != 'PyPy') and extra == 'fast' +Provides-Extra: i18n +Requires-Dist: babel~=2.13.0; extra == 'i18n' +Provides-Extra: mongo +Requires-Dist: motor~=3.3.2; extra == 'mongo' +Provides-Extra: proxy +Requires-Dist: aiohttp-socks~=0.8.3; extra == 'proxy' +Provides-Extra: redis +Requires-Dist: redis[hiredis]~=5.0.1; extra == 'redis' +Provides-Extra: test +Requires-Dist: aresponses~=2.1.6; extra == 'test' +Requires-Dist: pycryptodomex~=3.19.0; extra == 'test' +Requires-Dist: pytest-aiohttp~=1.0.5; extra == 'test' +Requires-Dist: pytest-asyncio~=0.21.1; extra == 'test' +Requires-Dist: pytest-cov~=4.1.0; extra == 'test' +Requires-Dist: pytest-html~=4.0.2; extra == 'test' +Requires-Dist: pytest-lazy-fixture~=0.6.3; extra == 'test' +Requires-Dist: pytest-mock~=3.12.0; extra == 'test' +Requires-Dist: pytest-mypy~=0.10.3; extra == 'test' +Requires-Dist: pytest~=7.4.2; extra == 'test' +Requires-Dist: pytz~=2023.3; extra == 'test' +Description-Content-Type: text/x-rst + +####### +aiogram +####### + +.. image:: https://img.shields.io/pypi/l/aiogram.svg?style=flat-square + :target: https://opensource.org/licenses/MIT + :alt: MIT License + +.. image:: https://img.shields.io/pypi/status/aiogram.svg?style=flat-square + :target: https://pypi.python.org/pypi/aiogram + :alt: PyPi status + +.. image:: https://img.shields.io/pypi/v/aiogram.svg?style=flat-square + :target: https://pypi.python.org/pypi/aiogram + :alt: PyPi Package Version + +.. image:: https://img.shields.io/pypi/dm/aiogram.svg?style=flat-square + :target: https://pypi.python.org/pypi/aiogram + :alt: Downloads + +.. image:: https://img.shields.io/pypi/pyversions/aiogram.svg?style=flat-square + :target: https://pypi.python.org/pypi/aiogram + :alt: Supported python versions + +.. image:: https://img.shields.io/badge/dynamic/json?color=blue&logo=telegram&label=Telegram%20Bot%20API&query=%24.api.version&url=https%3A%2F%2Fraw.githubusercontent.com%2Faiogram%2Faiogram%2Fdev-3.x%2F.butcher%2Fschema%2Fschema.json&style=flat-square + :target: https://core.telegram.org/bots/api + :alt: Telegram Bot API + +.. image:: https://img.shields.io/github/actions/workflow/status/aiogram/aiogram/tests.yml?branch=dev-3.x&style=flat-square + :target: https://github.com/aiogram/aiogram/actions + :alt: Tests + +.. image:: https://img.shields.io/codecov/c/github/aiogram/aiogram?style=flat-square + :target: https://app.codecov.io/gh/aiogram/aiogram + :alt: Codecov + +**aiogram** is a modern and fully asynchronous framework for +`Telegram Bot API `_ written in Python 3.8+ using +`asyncio `_ and +`aiohttp `_. + +Make your bots faster and more powerful! + +Documentation: + - 🇺🇸 `English `_ + - 🇺🇦 `Ukrainian `_ + + +Features +======== + +- Asynchronous (`asyncio docs `_, :pep:`492`) +- Has type hints (:pep:`484`) and can be used with `mypy `_ +- Supports `PyPy `_ +- Supports `Telegram Bot API 7.9 `_ and gets fast updates to the latest versions of the Bot API +- Telegram Bot API integration code was `autogenerated `_ and can be easily re-generated when API gets updated +- Updates router (Blueprints) +- Has Finite State Machine +- Uses powerful `magic filters `_ +- Middlewares (incoming updates and API calls) +- Provides `Replies into Webhook `_ +- Integrated I18n/L10n support with GNU Gettext (or Fluent) + + +.. warning:: + + It is strongly advised that you have prior experience working + with `asyncio `_ + before beginning to use **aiogram**. + + If you have any questions, you can visit our community chats on Telegram: + + - 🇺🇸 `@aiogram `_ + - 🇺🇦 `@aiogramua `_ + - 🇺🇿 `@aiogram_uz `_ + - 🇰🇿 `@aiogram_kz `_ + - 🇷🇺 `@aiogram_ru `_ + - 🇮🇷 `@aiogram_fa `_ + - 🇮🇹 `@aiogram_it `_ + - 🇧🇷 `@aiogram_br `_ diff --git a/env/Lib/site-packages/aiogram-3.12.0.dist-info/RECORD b/env/Lib/site-packages/aiogram-3.12.0.dist-info/RECORD new file mode 100644 index 0000000..4bcde9a --- /dev/null +++ b/env/Lib/site-packages/aiogram-3.12.0.dist-info/RECORD @@ -0,0 +1,961 @@ +aiogram-3.12.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiogram-3.12.0.dist-info/METADATA,sha256=xLpro6MzAiOqnI3s9iwMQa4utDb-lP5628N1tsZdgN4,7344 +aiogram-3.12.0.dist-info/RECORD,, +aiogram-3.12.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram-3.12.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87 +aiogram-3.12.0.dist-info/licenses/LICENSE,sha256=kTEqDVZ6fYSuFKAER9NvxX60epaWBKI_h-xGsoiU6Iw,1070 +aiogram/__init__.py,sha256=hzEKX_gFXmp5n4GXZEU80SJep1_FAH9owAnFTqd9nK0,948 +aiogram/__meta__.py,sha256=55lJQIAoSsYeR0jyyKdVygUQrmEXQxbAvKlsKTLaShU,47 +aiogram/__pycache__/__init__.cpython-311.pyc,, +aiogram/__pycache__/__meta__.cpython-311.pyc,, +aiogram/__pycache__/exceptions.cpython-311.pyc,, +aiogram/__pycache__/loggers.cpython-311.pyc,, +aiogram/client/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/client/__pycache__/__init__.cpython-311.pyc,, +aiogram/client/__pycache__/bot.cpython-311.pyc,, +aiogram/client/__pycache__/context_controller.cpython-311.pyc,, +aiogram/client/__pycache__/default.cpython-311.pyc,, +aiogram/client/__pycache__/telegram.cpython-311.pyc,, +aiogram/client/bot.py,sha256=gYy_a9F6Hass5YwsobSFeOu15mDrnR1u6N1x0YohQnA,262513 +aiogram/client/context_controller.py,sha256=rAminUBsB3K5FDyj-WQopkD1e94c7GrGVXNyaqPbXZ0,761 +aiogram/client/default.py,sha256=sqctTqHKsc69UBGh4sJeFbihGH5feDudb685CbMtdDU,2750 +aiogram/client/session/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/client/session/__pycache__/__init__.cpython-311.pyc,, +aiogram/client/session/__pycache__/aiohttp.cpython-311.pyc,, +aiogram/client/session/__pycache__/base.cpython-311.pyc,, +aiogram/client/session/aiohttp.py,sha256=q2OZLVEdz3LghDlEC5KfDEJJLtwYEbfJMXEmsVNnRcQ,7197 +aiogram/client/session/base.py,sha256=e3n5NrwL6L-pFhLetTgBg76uLJDxDP6jQqyxPgjtI_0,8335 +aiogram/client/session/middlewares/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/client/session/middlewares/__pycache__/__init__.cpython-311.pyc,, +aiogram/client/session/middlewares/__pycache__/base.cpython-311.pyc,, +aiogram/client/session/middlewares/__pycache__/manager.cpython-311.pyc,, +aiogram/client/session/middlewares/__pycache__/request_logging.cpython-311.pyc,, +aiogram/client/session/middlewares/base.py,sha256=ck8-iOnaYO2FHb3Yjq6E_TZwiPMg8w8THOXqyHDLjro,1394 +aiogram/client/session/middlewares/manager.py,sha256=c1CS6S_UvxYVAfCq6MZ4Laet6sxReEmQ915XltTJR5o,1903 +aiogram/client/session/middlewares/request_logging.py,sha256=_nUsciMnQeTZ-_nJw3A3NNBlGWzGqKMqYw2oJqJw3s8,1183 +aiogram/client/telegram.py,sha256=cu0HUZqwPzvZp-tMI3yewmnNZ78aTpFfEF0ZZVf0qAw,3080 +aiogram/dispatcher/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/dispatcher/__pycache__/__init__.cpython-311.pyc,, +aiogram/dispatcher/__pycache__/dispatcher.cpython-311.pyc,, +aiogram/dispatcher/__pycache__/flags.cpython-311.pyc,, +aiogram/dispatcher/__pycache__/router.cpython-311.pyc,, +aiogram/dispatcher/dispatcher.py,sha256=j3V5oi-nBUT1CBSBAs8lbCRQNIveZ9sVOJmUHnuJEqE,23205 +aiogram/dispatcher/event/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/dispatcher/event/__pycache__/__init__.cpython-311.pyc,, +aiogram/dispatcher/event/__pycache__/bases.cpython-311.pyc,, +aiogram/dispatcher/event/__pycache__/event.cpython-311.pyc,, +aiogram/dispatcher/event/__pycache__/handler.cpython-311.pyc,, +aiogram/dispatcher/event/__pycache__/telegram.cpython-311.pyc,, +aiogram/dispatcher/event/bases.py,sha256=Piod0CEyGvBOwEuE7e70JMQal4XFilFD3NMinR2bEyE,871 +aiogram/dispatcher/event/event.py,sha256=YXOroGX5Mj-5w6Jgl9oPf-muIp6ijeWjNJ3hEr2mA68,1352 +aiogram/dispatcher/event/handler.py,sha256=rgV8j1x2a8qpmWCue1-uQ3fRzrc8qDdhKNJBkBnFSYo,3631 +aiogram/dispatcher/event/telegram.py,sha256=BjptMwTbDVdpiIkngGyy8zY2b3i5__gwnuyA7uw9HoY,4767 +aiogram/dispatcher/flags.py,sha256=vEevCfweZKDCEW2tA5E3UbqMH-TjDBI0ujf7ktzsx9o,3479 +aiogram/dispatcher/middlewares/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/dispatcher/middlewares/__pycache__/__init__.cpython-311.pyc,, +aiogram/dispatcher/middlewares/__pycache__/base.cpython-311.pyc,, +aiogram/dispatcher/middlewares/__pycache__/error.cpython-311.pyc,, +aiogram/dispatcher/middlewares/__pycache__/manager.cpython-311.pyc,, +aiogram/dispatcher/middlewares/__pycache__/user_context.cpython-311.pyc,, +aiogram/dispatcher/middlewares/base.py,sha256=czbD9IDLoHb6pf6HisRGyG8pAQMLbC4R5k-iuTIWSNU,784 +aiogram/dispatcher/middlewares/error.py,sha256=xDfQxTo9PT1qXvE35OGesDi7WydeQeB4zgT07eXM5G4,1119 +aiogram/dispatcher/middlewares/manager.py,sha256=-ivUdff-Addpd_s_AlDA4RaVsMJmzgWwvt2DIqITnBw,2166 +aiogram/dispatcher/middlewares/user_context.py,sha256=kc2ONIgh_b4MlItGxH-7RkxZ6zCevY2sfplJl1keyVU,7115 +aiogram/dispatcher/router.py,sha256=vnAvQQANQ85JXE84s7JXkVo60uKUvyqg0bcIFGJ8we8,10512 +aiogram/enums/__init__.py,sha256=oQH8dIPtHKcgQwX6k6-EIda0PLM_HWyyPy5Oft1BSoY,2014 +aiogram/enums/__pycache__/__init__.cpython-311.pyc,, +aiogram/enums/__pycache__/bot_command_scope_type.cpython-311.pyc,, +aiogram/enums/__pycache__/chat_action.cpython-311.pyc,, +aiogram/enums/__pycache__/chat_boost_source_type.cpython-311.pyc,, +aiogram/enums/__pycache__/chat_member_status.cpython-311.pyc,, +aiogram/enums/__pycache__/chat_type.cpython-311.pyc,, +aiogram/enums/__pycache__/content_type.cpython-311.pyc,, +aiogram/enums/__pycache__/currency.cpython-311.pyc,, +aiogram/enums/__pycache__/dice_emoji.cpython-311.pyc,, +aiogram/enums/__pycache__/encrypted_passport_element.cpython-311.pyc,, +aiogram/enums/__pycache__/inline_query_result_type.cpython-311.pyc,, +aiogram/enums/__pycache__/input_media_type.cpython-311.pyc,, +aiogram/enums/__pycache__/input_paid_media_type.cpython-311.pyc,, +aiogram/enums/__pycache__/keyboard_button_poll_type_type.cpython-311.pyc,, +aiogram/enums/__pycache__/mask_position_point.cpython-311.pyc,, +aiogram/enums/__pycache__/menu_button_type.cpython-311.pyc,, +aiogram/enums/__pycache__/message_entity_type.cpython-311.pyc,, +aiogram/enums/__pycache__/message_origin_type.cpython-311.pyc,, +aiogram/enums/__pycache__/paid_media_type.cpython-311.pyc,, +aiogram/enums/__pycache__/parse_mode.cpython-311.pyc,, +aiogram/enums/__pycache__/passport_element_error_type.cpython-311.pyc,, +aiogram/enums/__pycache__/poll_type.cpython-311.pyc,, +aiogram/enums/__pycache__/reaction_type_type.cpython-311.pyc,, +aiogram/enums/__pycache__/revenue_withdrawal_state_type.cpython-311.pyc,, +aiogram/enums/__pycache__/sticker_format.cpython-311.pyc,, +aiogram/enums/__pycache__/sticker_type.cpython-311.pyc,, +aiogram/enums/__pycache__/topic_icon_color.cpython-311.pyc,, +aiogram/enums/__pycache__/transaction_partner_type.cpython-311.pyc,, +aiogram/enums/__pycache__/update_type.cpython-311.pyc,, +aiogram/enums/bot_command_scope_type.py,sha256=aPn5UKE6AN5BpK9kTH1ffJzG3qUOWFu5lyZOifMu5so,477 +aiogram/enums/chat_action.py,sha256=KKItRU_RQuNzFMrAtc67Pn0aT4rZuuynpH6-yXfBhRY,972 +aiogram/enums/chat_boost_source_type.py,sha256=80MfT0G_9-uv-7MsTs0lZjtJiA7EaUmqYd5b3vH6JtU,277 +aiogram/enums/chat_member_status.py,sha256=OLr5ZfkZocicy1t5i30g7ufR8kujBPHENzR5UHnsDpc,334 +aiogram/enums/chat_type.py,sha256=1Oi1TYITumT8jZritu1fgHNKDvK9otlAhPm4soyBKQQ,280 +aiogram/enums/content_type.py,sha256=sSTHtq4LqeYB4J3zFug1HkhVuORSdcT7g91ZQTjOZrE,2311 +aiogram/enums/currency.py,sha256=P5S_e7Y3wYmODiaK_8Fz0MHVwJXkt1P9Y3gd2SGo1iU,1563 +aiogram/enums/dice_emoji.py,sha256=9KlOPTQlgt-6d3myDEWWUTB9H8BrE_LRaOZvBM2ceWs,303 +aiogram/enums/encrypted_passport_element.py,sha256=m0-tAF9myf6FwPbsuJgj4AYvywzLMzzltUgrqWgGVws,704 +aiogram/enums/inline_query_result_type.py,sha256=HGNN5aOg_jZbE4NNfHs21M-xK5cj2rBar4-C77T73YI,465 +aiogram/enums/input_media_type.py,sha256=BfCDkzFOjrzJSo2syY2lq3E3JP8AdlGemp7qMnAupw0,291 +aiogram/enums/input_paid_media_type.py,sha256=KoqJo7AelAiY8pmS1mRBuQLz97hedWFImEEVFnEoMmY,247 +aiogram/enums/keyboard_button_poll_type_type.py,sha256=vPjequaOO5zySi7hiQjyVIfQl-jhtpgCGHYMR7DOYWY,324 +aiogram/enums/mask_position_point.py,sha256=lhlx8U-9gtGn_LPiSOHWBe1u8YTLZCERs5x8DRmUubM,290 +aiogram/enums/menu_button_type.py,sha256=4FDz7HKaVtfBlvXObCOVAUmyQQvRsyPi0Vu_Kc-HbDs,264 +aiogram/enums/message_entity_type.py,sha256=00ioN4bPLNUYvCL_nJzp7rNUPhIqNOqoWY3PjiC4ob8,703 +aiogram/enums/message_origin_type.py,sha256=qWHgXPzpuhsTcLx-huqNS1l36JSwqbsCY70_d20nreM,279 +aiogram/enums/paid_media_type.py,sha256=FrGQyXq9bimIb8_b0hpuqYG4mWVruoBYkSC6drd7hw4,261 +aiogram/enums/parse_mode.py,sha256=t5F3LaNLsUOaNQuYlQseWt36suA-oRgr_uScGEU8TKU,234 +aiogram/enums/passport_element_error_type.py,sha256=HCcvvc8DDUNRD-mdFgFqMEFlr_4pa5Us5_U6pO2wXsc,471 +aiogram/enums/poll_type.py,sha256=DluT-wQcOGqBgQimYLlO6OlTIIYnnbtHOmY9pjqVToo,200 +aiogram/enums/reaction_type_type.py,sha256=HfSXXZFcMXjIoD0Q8B_lZju6mPuB4jNIBbRyIfLYnEI,233 +aiogram/enums/revenue_withdrawal_state_type.py,sha256=ZVw59f9-RYG00TJdSHnZo_LTbdR_J8RmkhDCV4C8AFg,290 +aiogram/enums/sticker_format.py,sha256=UmbwulTvkG7TFwS2twsblqiBj89jeEWY-y7P7Ah2qgo,235 +aiogram/enums/sticker_type.py,sha256=XonGtnasf3tXwoD2DVRx5E16rHCE5VqgAFSfcFMIAGU,278 +aiogram/enums/topic_icon_color.py,sha256=q-DilvJsgVmz5VafMOxj1BKJcMoHzpRrbatTPE4inxk,399 +aiogram/enums/transaction_partner_type.py,sha256=VSLiUN_53Ggi9_YrrxoF8OeltgiLY2jJGkAYQJcaHWI,305 +aiogram/enums/update_type.py,sha256=WAXTSDLbOXyzjLanGn_22HsALq96OVdd5q8HunubdG8,1086 +aiogram/exceptions.py,sha256=Y6wDVG2fyoczPn15U5epm_nnTx8eTC3CgX19SzyiqOE,5153 +aiogram/filters/__init__.py,sha256=w7mWuJOIpLDZyUt1eznzMeF-o1UrstHQ-OYbBHHG6ek,1031 +aiogram/filters/__pycache__/__init__.cpython-311.pyc,, +aiogram/filters/__pycache__/base.cpython-311.pyc,, +aiogram/filters/__pycache__/callback_data.cpython-311.pyc,, +aiogram/filters/__pycache__/chat_member_updated.cpython-311.pyc,, +aiogram/filters/__pycache__/command.cpython-311.pyc,, +aiogram/filters/__pycache__/exception.cpython-311.pyc,, +aiogram/filters/__pycache__/logic.cpython-311.pyc,, +aiogram/filters/__pycache__/magic_data.cpython-311.pyc,, +aiogram/filters/__pycache__/state.cpython-311.pyc,, +aiogram/filters/base.py,sha256=6mCB2nSjqskDDl9mKCZ3SghhwQ1jryaSTd5PvWii3bM,2005 +aiogram/filters/callback_data.py,sha256=nxRCCPXX4iuk1bnVpg3MdLOCeGlmJFKIcS6yjPkM2V8,6225 +aiogram/filters/chat_member_updated.py,sha256=3VsiMYLK6L7AfLS7RQRWwjXThWGN7gj4NAYnR0Wdr8I,7484 +aiogram/filters/command.py,sha256=IXb54dwKHLz-Jaq2_HHn2si7r5iAr9pYW3sSxD8szCk,9957 +aiogram/filters/exception.py,sha256=HbJIOVrXHh0_LkID6b-yn8Xow-llmLqKYmK0_tqB4YA,1488 +aiogram/filters/logic.py,sha256=2M-fYY8m1ybX00wFn_8toRHj5alTfy4T6zkIkYrQZbM,2174 +aiogram/filters/magic_data.py,sha256=Y07K9NLDXpXV0EuFR7GR7Yq4SzCYaD3XJsvDH-6JFkQ,718 +aiogram/filters/state.py,sha256=A4GuSAo5KPdSZMetCC9crrfbJ-yghLunJUVYkOdBPTI,1448 +aiogram/fsm/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/fsm/__pycache__/__init__.cpython-311.pyc,, +aiogram/fsm/__pycache__/context.cpython-311.pyc,, +aiogram/fsm/__pycache__/middleware.cpython-311.pyc,, +aiogram/fsm/__pycache__/scene.cpython-311.pyc,, +aiogram/fsm/__pycache__/state.cpython-311.pyc,, +aiogram/fsm/__pycache__/strategy.cpython-311.pyc,, +aiogram/fsm/context.py,sha256=o0cKPtB43Z2S8DgSD9be5moF8FqOboBca8Wyd6qvUgU,1072 +aiogram/fsm/middleware.py,sha256=4MsKWzr93tzLTmv3dph3pKhznuX9EGsrhBhCb6mhzPo,3755 +aiogram/fsm/scene.py,sha256=7a5zMRvfE2vHQ-3zSCHiBDa93QedmOr6kgLs1svjHAg,31903 +aiogram/fsm/state.py,sha256=T0sPq1_JV5Jq1jVKu67bUQ0-y9Kqsk3hGpj7PgjpacQ,5640 +aiogram/fsm/storage/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/fsm/storage/__pycache__/__init__.cpython-311.pyc,, +aiogram/fsm/storage/__pycache__/base.cpython-311.pyc,, +aiogram/fsm/storage/__pycache__/memory.cpython-311.pyc,, +aiogram/fsm/storage/__pycache__/mongo.cpython-311.pyc,, +aiogram/fsm/storage/__pycache__/redis.cpython-311.pyc,, +aiogram/fsm/storage/base.py,sha256=5SVkAFfcCLN8uZkE1EX7DFFcGJ89p4fp3wB9R8FU2no,5023 +aiogram/fsm/storage/memory.py,sha256=xG3507DVY01GTntkGSG1-2fPlWkcDL48QUTIE5WFowQ,2133 +aiogram/fsm/storage/mongo.py,sha256=xGvz9rLr6ji8BhumZb1FTvQ5RvmlGquhLAPe1-vi9ms,4880 +aiogram/fsm/storage/redis.py,sha256=7ZyaB-AMNEITjdYVn24Bha28_MIFRPX41mn5_0sEtiY,5322 +aiogram/fsm/strategy.py,sha256=RUDc6kMae9ZFbyC1bdbAIRz6GoeaIHFzXCXRu8p3Kn0,1147 +aiogram/handlers/__init__.py,sha256=XVErtJHhSmg4ytiDTP9J5pQY0RwBN1TsjT5v-Ls7RE4,800 +aiogram/handlers/__pycache__/__init__.cpython-311.pyc,, +aiogram/handlers/__pycache__/base.cpython-311.pyc,, +aiogram/handlers/__pycache__/callback_query.cpython-311.pyc,, +aiogram/handlers/__pycache__/chat_member.cpython-311.pyc,, +aiogram/handlers/__pycache__/chosen_inline_result.cpython-311.pyc,, +aiogram/handlers/__pycache__/error.cpython-311.pyc,, +aiogram/handlers/__pycache__/inline_query.cpython-311.pyc,, +aiogram/handlers/__pycache__/message.cpython-311.pyc,, +aiogram/handlers/__pycache__/poll.cpython-311.pyc,, +aiogram/handlers/__pycache__/pre_checkout_query.cpython-311.pyc,, +aiogram/handlers/__pycache__/shipping_query.cpython-311.pyc,, +aiogram/handlers/base.py,sha256=SKLNknDSxAItRHwPMJanOPFztWakJQCun4myH9TBNik,1097 +aiogram/handlers/callback_query.py,sha256=XWGgkmyt2Bgnh1B_3ivIZ_jMRJIQUEXPeKSUO4VW_zg,1036 +aiogram/handlers/chat_member.py,sha256=TCr1m47duHFUpL92W56ok0hF1k0NN3Yk88-1zzEsYmw,322 +aiogram/handlers/chosen_inline_result.py,sha256=NjAPc5EgBb8V4p3WVpcPNPd8b1OApymvBN-I75EYMQo,410 +aiogram/handlers/error.py,sha256=86pedHPBgYxXYwrW00s0cadf_lRP6TeHEG0goJ6zNJk,352 +aiogram/handlers/inline_query.py,sha256=sOkT3uMuvamMnSTxct-cdQFng6GBqaOlSNV4aHUbVPQ,381 +aiogram/handlers/message.py,sha256=I6R4TJ8V6bbGVppmxmGSxIkCzeN9JMn1CDojywWrt50,721 +aiogram/handlers/poll.py,sha256=Bn075JIux1lNPjKWH3woV_OzMcvPgPvtkgp4W22mUX8,396 +aiogram/handlers/pre_checkout_query.py,sha256=ZO0iZFVwRz4CtBWIVLds8JoHhMPqCahz6lwOfR4dEkg,321 +aiogram/handlers/shipping_query.py,sha256=ku14YRYvddTbHeKoIwb2oDpfrpsetFC1m2BwIsNwoAs,314 +aiogram/loggers.py,sha256=3MCGSmwgXXsWbgtSaTc6bPSwVOIe8FkQZglc0QLVvsY,257 +aiogram/methods/__init__.py,sha256=v4-H0SB9W9Z7rY4Y_uF5Z86dUZje0aI0cafAxDbL2W0,9575 +aiogram/methods/__pycache__/__init__.cpython-311.pyc,, +aiogram/methods/__pycache__/add_sticker_to_set.cpython-311.pyc,, +aiogram/methods/__pycache__/answer_callback_query.cpython-311.pyc,, +aiogram/methods/__pycache__/answer_inline_query.cpython-311.pyc,, +aiogram/methods/__pycache__/answer_pre_checkout_query.cpython-311.pyc,, +aiogram/methods/__pycache__/answer_shipping_query.cpython-311.pyc,, +aiogram/methods/__pycache__/answer_web_app_query.cpython-311.pyc,, +aiogram/methods/__pycache__/approve_chat_join_request.cpython-311.pyc,, +aiogram/methods/__pycache__/ban_chat_member.cpython-311.pyc,, +aiogram/methods/__pycache__/ban_chat_sender_chat.cpython-311.pyc,, +aiogram/methods/__pycache__/base.cpython-311.pyc,, +aiogram/methods/__pycache__/close.cpython-311.pyc,, +aiogram/methods/__pycache__/close_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/close_general_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/copy_message.cpython-311.pyc,, +aiogram/methods/__pycache__/copy_messages.cpython-311.pyc,, +aiogram/methods/__pycache__/create_chat_invite_link.cpython-311.pyc,, +aiogram/methods/__pycache__/create_chat_subscription_invite_link.cpython-311.pyc,, +aiogram/methods/__pycache__/create_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/create_invoice_link.cpython-311.pyc,, +aiogram/methods/__pycache__/create_new_sticker_set.cpython-311.pyc,, +aiogram/methods/__pycache__/decline_chat_join_request.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_chat_photo.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_chat_sticker_set.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_message.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_messages.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_my_commands.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_sticker_from_set.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_sticker_set.cpython-311.pyc,, +aiogram/methods/__pycache__/delete_webhook.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_chat_invite_link.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_chat_subscription_invite_link.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_general_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_message_caption.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_message_live_location.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_message_media.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_message_reply_markup.cpython-311.pyc,, +aiogram/methods/__pycache__/edit_message_text.cpython-311.pyc,, +aiogram/methods/__pycache__/export_chat_invite_link.cpython-311.pyc,, +aiogram/methods/__pycache__/forward_message.cpython-311.pyc,, +aiogram/methods/__pycache__/forward_messages.cpython-311.pyc,, +aiogram/methods/__pycache__/get_business_connection.cpython-311.pyc,, +aiogram/methods/__pycache__/get_chat.cpython-311.pyc,, +aiogram/methods/__pycache__/get_chat_administrators.cpython-311.pyc,, +aiogram/methods/__pycache__/get_chat_member.cpython-311.pyc,, +aiogram/methods/__pycache__/get_chat_member_count.cpython-311.pyc,, +aiogram/methods/__pycache__/get_chat_menu_button.cpython-311.pyc,, +aiogram/methods/__pycache__/get_custom_emoji_stickers.cpython-311.pyc,, +aiogram/methods/__pycache__/get_file.cpython-311.pyc,, +aiogram/methods/__pycache__/get_forum_topic_icon_stickers.cpython-311.pyc,, +aiogram/methods/__pycache__/get_game_high_scores.cpython-311.pyc,, +aiogram/methods/__pycache__/get_me.cpython-311.pyc,, +aiogram/methods/__pycache__/get_my_commands.cpython-311.pyc,, +aiogram/methods/__pycache__/get_my_default_administrator_rights.cpython-311.pyc,, +aiogram/methods/__pycache__/get_my_description.cpython-311.pyc,, +aiogram/methods/__pycache__/get_my_name.cpython-311.pyc,, +aiogram/methods/__pycache__/get_my_short_description.cpython-311.pyc,, +aiogram/methods/__pycache__/get_star_transactions.cpython-311.pyc,, +aiogram/methods/__pycache__/get_sticker_set.cpython-311.pyc,, +aiogram/methods/__pycache__/get_updates.cpython-311.pyc,, +aiogram/methods/__pycache__/get_user_chat_boosts.cpython-311.pyc,, +aiogram/methods/__pycache__/get_user_profile_photos.cpython-311.pyc,, +aiogram/methods/__pycache__/get_webhook_info.cpython-311.pyc,, +aiogram/methods/__pycache__/hide_general_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/leave_chat.cpython-311.pyc,, +aiogram/methods/__pycache__/log_out.cpython-311.pyc,, +aiogram/methods/__pycache__/pin_chat_message.cpython-311.pyc,, +aiogram/methods/__pycache__/promote_chat_member.cpython-311.pyc,, +aiogram/methods/__pycache__/refund_star_payment.cpython-311.pyc,, +aiogram/methods/__pycache__/reopen_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/reopen_general_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/replace_sticker_in_set.cpython-311.pyc,, +aiogram/methods/__pycache__/restrict_chat_member.cpython-311.pyc,, +aiogram/methods/__pycache__/revoke_chat_invite_link.cpython-311.pyc,, +aiogram/methods/__pycache__/send_animation.cpython-311.pyc,, +aiogram/methods/__pycache__/send_audio.cpython-311.pyc,, +aiogram/methods/__pycache__/send_chat_action.cpython-311.pyc,, +aiogram/methods/__pycache__/send_contact.cpython-311.pyc,, +aiogram/methods/__pycache__/send_dice.cpython-311.pyc,, +aiogram/methods/__pycache__/send_document.cpython-311.pyc,, +aiogram/methods/__pycache__/send_game.cpython-311.pyc,, +aiogram/methods/__pycache__/send_invoice.cpython-311.pyc,, +aiogram/methods/__pycache__/send_location.cpython-311.pyc,, +aiogram/methods/__pycache__/send_media_group.cpython-311.pyc,, +aiogram/methods/__pycache__/send_message.cpython-311.pyc,, +aiogram/methods/__pycache__/send_paid_media.cpython-311.pyc,, +aiogram/methods/__pycache__/send_photo.cpython-311.pyc,, +aiogram/methods/__pycache__/send_poll.cpython-311.pyc,, +aiogram/methods/__pycache__/send_sticker.cpython-311.pyc,, +aiogram/methods/__pycache__/send_venue.cpython-311.pyc,, +aiogram/methods/__pycache__/send_video.cpython-311.pyc,, +aiogram/methods/__pycache__/send_video_note.cpython-311.pyc,, +aiogram/methods/__pycache__/send_voice.cpython-311.pyc,, +aiogram/methods/__pycache__/set_chat_administrator_custom_title.cpython-311.pyc,, +aiogram/methods/__pycache__/set_chat_description.cpython-311.pyc,, +aiogram/methods/__pycache__/set_chat_menu_button.cpython-311.pyc,, +aiogram/methods/__pycache__/set_chat_permissions.cpython-311.pyc,, +aiogram/methods/__pycache__/set_chat_photo.cpython-311.pyc,, +aiogram/methods/__pycache__/set_chat_sticker_set.cpython-311.pyc,, +aiogram/methods/__pycache__/set_chat_title.cpython-311.pyc,, +aiogram/methods/__pycache__/set_custom_emoji_sticker_set_thumbnail.cpython-311.pyc,, +aiogram/methods/__pycache__/set_game_score.cpython-311.pyc,, +aiogram/methods/__pycache__/set_message_reaction.cpython-311.pyc,, +aiogram/methods/__pycache__/set_my_commands.cpython-311.pyc,, +aiogram/methods/__pycache__/set_my_default_administrator_rights.cpython-311.pyc,, +aiogram/methods/__pycache__/set_my_description.cpython-311.pyc,, +aiogram/methods/__pycache__/set_my_name.cpython-311.pyc,, +aiogram/methods/__pycache__/set_my_short_description.cpython-311.pyc,, +aiogram/methods/__pycache__/set_passport_data_errors.cpython-311.pyc,, +aiogram/methods/__pycache__/set_sticker_emoji_list.cpython-311.pyc,, +aiogram/methods/__pycache__/set_sticker_keywords.cpython-311.pyc,, +aiogram/methods/__pycache__/set_sticker_mask_position.cpython-311.pyc,, +aiogram/methods/__pycache__/set_sticker_position_in_set.cpython-311.pyc,, +aiogram/methods/__pycache__/set_sticker_set_thumbnail.cpython-311.pyc,, +aiogram/methods/__pycache__/set_sticker_set_title.cpython-311.pyc,, +aiogram/methods/__pycache__/set_webhook.cpython-311.pyc,, +aiogram/methods/__pycache__/stop_message_live_location.cpython-311.pyc,, +aiogram/methods/__pycache__/stop_poll.cpython-311.pyc,, +aiogram/methods/__pycache__/unban_chat_member.cpython-311.pyc,, +aiogram/methods/__pycache__/unban_chat_sender_chat.cpython-311.pyc,, +aiogram/methods/__pycache__/unhide_general_forum_topic.cpython-311.pyc,, +aiogram/methods/__pycache__/unpin_all_chat_messages.cpython-311.pyc,, +aiogram/methods/__pycache__/unpin_all_forum_topic_messages.cpython-311.pyc,, +aiogram/methods/__pycache__/unpin_all_general_forum_topic_messages.cpython-311.pyc,, +aiogram/methods/__pycache__/unpin_chat_message.cpython-311.pyc,, +aiogram/methods/__pycache__/upload_sticker_file.cpython-311.pyc,, +aiogram/methods/add_sticker_to_set.py,sha256=PR2B-SDNNYLaH70oevadRNAoiUjFQXLffGSIhQ7uah4,1443 +aiogram/methods/answer_callback_query.py,sha256=YVozC3bMDE8YoH6x5TipzWiXCwdWLAU96GWOJTxf1AE,2903 +aiogram/methods/answer_inline_query.py,sha256=039jip6Ty3cdvEuYbfougTO-DZIzi1f5hisl6yRg8qw,6017 +aiogram/methods/answer_pre_checkout_query.py,sha256=5peOULN2DO0VoK3nEAnsN-E9RWAH5ab64UUc-4apRHk,2172 +aiogram/methods/answer_shipping_query.py,sha256=oiq-B_Go-J_sRalwvgyFjUUZDEF1MX5IGNKV6khU0N8,2254 +aiogram/methods/answer_web_app_query.py,sha256=AXM-hDf_xIarwburmGT27ZoKFoGsbcVbPNM_EHUHKVo,3676 +aiogram/methods/approve_chat_join_request.py,sha256=KUetMV7jHSB9_v702JlSI-CVlJMHUCNstvjUC0GU3i4,1281 +aiogram/methods/ban_chat_member.py,sha256=hfHkT_Ucg-26oVtvRQwGvijDMn7uaV84agEY7vIEp-E,2481 +aiogram/methods/ban_chat_sender_chat.py,sha256=rr77ixJufnD9bWevxTaSHCcJVh3lIf19JGLEctMMm7A,1569 +aiogram/methods/base.py,sha256=VH-3rKUGvNYoiQ9Tw78FujrzlJLs9smBhmI8ejx3-2Y,2734 +aiogram/methods/close.py,sha256=Bnzle__tO6tCMMLHkN1E00ypkrdQ0RjhkBNxhjDOq3k,593 +aiogram/methods/close_forum_topic.py,sha256=njPMjFb7CkLYbjEuNWPrSDh2HSpqlmO76B9Xs_Xahco,1475 +aiogram/methods/close_general_forum_topic.py,sha256=lLWx-ZgE4eV15D2yLXg1wWVECfcN7_1y2XA5vqr1d84,1223 +aiogram/methods/copy_message.py,sha256=jvPiwstYa8Lt0XNeI15_HyrwAvnPdgmi0KJZI3GuXOs,6109 +aiogram/methods/copy_messages.py,sha256=PbxTovACFr7NM8Te3iN2tq7VLLKvxGDzr_Gp8hrjukA,3293 +aiogram/methods/create_chat_invite_link.py,sha256=Snalw6e_zk5g5FI2wKB4Pr0qbGS1PbjIcq7567RC5YE,2545 +aiogram/methods/create_chat_subscription_invite_link.py,sha256=ulylrmNJXJa7hipKx7j_2wOeZSVgufPaW2h5JFO2OIw,2508 +aiogram/methods/create_forum_topic.py,sha256=FuJ8R-jkpfk7hPKe6pffiUQE21Hhh22G7cFMCFe5kok,2188 +aiogram/methods/create_invoice_link.py,sha256=PsgrJvP9W55DuTBmGut1puRNYQOuE6xvRHmblwv64lM,6655 +aiogram/methods/create_new_sticker_set.py,sha256=0LwiOVBGTo-sJLOd76Au3_G2-d6YtqFHfju6TU0A2vw,2928 +aiogram/methods/decline_chat_join_request.py,sha256=19Sj8OHe6erv3_E4p-Sw_y8XygNYOWrPI5S23CU5P1w,1281 +aiogram/methods/delete_chat_photo.py,sha256=0nrFbxWyO7R0pVMAWook7VRXAIU-AeEr_wpiFvyLssQ,1194 +aiogram/methods/delete_chat_sticker_set.py,sha256=KaRyvzLt1ystCbkptimtxqUM_4_RzpI7Sl91heSVlKc,1348 +aiogram/methods/delete_forum_topic.py,sha256=LrncMipGRW2Be4bYFzSYMjydvRijmPU5Owtmb61e374,1470 +aiogram/methods/delete_message.py,sha256=wCMd8oHwYETY1Nk2vP4DYhu-sdrm-LqhQBKPAgQQhSY,1956 +aiogram/methods/delete_messages.py,sha256=Hp9tfOVK4T9y3SuAAlfLo58_58CP83JWfpLnN3jkbiM,1401 +aiogram/methods/delete_my_commands.py,sha256=LiYVWXeqBxs_hUbq6pQ1h3zSKUyzw7ahdaXb1esAH8Q,2608 +aiogram/methods/delete_sticker_from_set.py,sha256=J2PsBRRTBks5TDlp4mlmubem7MSWKh8jzJMmLJQV9CI,944 +aiogram/methods/delete_sticker_set.py,sha256=csUT6RkdqmOy0K7vT2QXXR_YJfpQ78S31WYttFqEPY8,908 +aiogram/methods/delete_webhook.py,sha256=7kfmOOSlujfXV5JZEozbuQQzNrX5YV0f6nMvUo5aw_k,1155 +aiogram/methods/edit_chat_invite_link.py,sha256=N2RqH2DHbRK-zF97jtHlhMV2YykBgHgpqw_iDz8KQRw,2564 +aiogram/methods/edit_chat_subscription_invite_link.py,sha256=AvDlMClqa00KJnf4sXZkdOYGBErGtuwLMeHEM0AND5E,1610 +aiogram/methods/edit_forum_topic.py,sha256=hELFkBuB_6I3_y2xencOolPXPUjEK3xXCgfzC4lAuCA,2195 +aiogram/methods/edit_general_forum_topic.py,sha256=PK37qgJRVISQWhYAWlg3LNGmgneVdQxpJCa1dMiq_uY,1306 +aiogram/methods/edit_message_caption.py,sha256=wv-USNcfyHIjskv6PaSQAABE9yDK8lr9lgDS5yBfiVM,3995 +aiogram/methods/edit_message_live_location.py,sha256=akOy16TytMIR1ONYR8lu8W48HplUl9ugqW-tttrn2Zk,4205 +aiogram/methods/edit_message_media.py,sha256=fjDjBVQ6jbHoSDsxX3_19Q_TF-WzACaItS4gfdKtGuw,3529 +aiogram/methods/edit_message_reply_markup.py,sha256=H5elelToPCzLoOsGDDfOa7nXRQ10AMhxP13quMGRt1k,2658 +aiogram/methods/edit_message_text.py,sha256=IQPTgqWDn-xK5L7hjJ3FOhJqe8DJC9uRnnVWE-gmWcs,4345 +aiogram/methods/export_chat_invite_link.py,sha256=oC00_UAsmJ7icNtjmnCbQ9sYyJLoOujNJsLIRMyx9qg,1792 +aiogram/methods/forward_message.py,sha256=KM6v9CrqMnwC0YLgiIEVxTFBUmb5GhFfAMycrxY0IJ4,2655 +aiogram/methods/forward_messages.py,sha256=BIUEDoLp8jD5YglFN2pbHp6FtuhMFMB1VCSzMPhtOPs,2774 +aiogram/methods/get_business_connection.py,sha256=wJhKMcBoLcOXTxK1_xG8SR2h85e1sW1C4sWD6L6bTTM,1200 +aiogram/methods/get_chat.py,sha256=yOPjLV12HVZOk6ch2bUOfyrZBPIhyAXhhHEhiZKEdro,1145 +aiogram/methods/get_chat_administrators.py,sha256=uxzQWmNc0EJRJ-c0ecJmjLPWDOwlMD1KWDiOAnqofxs,1815 +aiogram/methods/get_chat_member.py,sha256=pltcJQL_aSljObA_XAVa9chzyC5saahC-jCA85U0Z_E,1857 +aiogram/methods/get_chat_member_count.py,sha256=phZ05LJUn3EAXBuH_7HqMFOuTg99nyVNjNEVWry1sto,1067 +aiogram/methods/get_chat_menu_button.py,sha256=Ko5U5PMvTP08x8SkCUddFASaGr-LbtP_4GhvbM-TP7c,1362 +aiogram/methods/get_custom_emoji_stickers.py,sha256=ob0rvnUFtuDlZ6GmNHlFZH2hNZNITf2k0mjBBvmeNY0,1201 +aiogram/methods/get_file.py,sha256=FutkpYaOz_xjdU_1FwGY75ZYZ-uqBCZapZBiE5K9sC0,1571 +aiogram/methods/get_forum_topic_icon_stickers.py,sha256=TUAX41OPjlluu3zxI-_lYCzBHzX-Wa_Fgde727H4llg,557 +aiogram/methods/get_game_high_scores.py,sha256=IhEZ81rRGOh_pkq54qGys0RGoywhTG7I5UdYikoVS8A,2156 +aiogram/methods/get_me.py,sha256=gA4vD-v3WYPpZaSTy6mpGZmsV5WXdSHv06EymV9ZQnU,439 +aiogram/methods/get_my_commands.py,sha256=67G3OlYrwZAnQZM8D2nQwNwEhPB1siDqOvMkc9saSgo,2464 +aiogram/methods/get_my_default_administrator_rights.py,sha256=dw1MnQACVfVsQeYs5ikZG1jThB15HR8Trv1xHg_oSLY,1359 +aiogram/methods/get_my_description.py,sha256=UzgJhr6sl4i4RD9LIYxvTx4z4V3cZMGQavCFucWwv1I,1156 +aiogram/methods/get_my_name.py,sha256=GGY2ZnZ_uXL5GqRKHJ2uXs5v_LUBqg6yx0NdrBLZoy8,1057 +aiogram/methods/get_my_short_description.py,sha256=yRQ0ertSdcbEy32FC07FAo12q7eyLEN04h0gkxzpmGE,1203 +aiogram/methods/get_star_transactions.py,sha256=kCp-vAuYCbogKN6PQ4_ulx4ByBatWbMwuXUTsMib22M,1374 +aiogram/methods/get_sticker_set.py,sha256=oh9jEInEgKDfOhAu58ex4rUYRCJCk-BTsOAvNa7GPMg,965 +aiogram/methods/get_updates.py,sha256=dMl44T18fGWKDG2ZK-GQ2OJu7PIYe3GJ93IzX26LXqs,3024 +aiogram/methods/get_user_chat_boosts.py,sha256=2HYUsuZMxrP-YdZO7S4rX0QItzjUN8H01mmwvm2SSkc,1255 +aiogram/methods/get_user_profile_photos.py,sha256=URseFqr69kRj4-gqNkSl4TsiEaAK78iAyjYrTv4tCpA,1507 +aiogram/methods/get_webhook_info.py,sha256=8h38GW1au2fAZau2qmXuOnmu-H6kIjXQEms3VKLJf5c,576 +aiogram/methods/hide_general_forum_topic.py,sha256=dKPkMB4okbduRG9K-Mah5hf6OsKzGg8NrtnTQdcVu78,1270 +aiogram/methods/leave_chat.py,sha256=m3F4mKwOmJaxk958rbBZqGIRcM7007JMce1S2zpEvPY,1063 +aiogram/methods/log_out.py,sha256=yBkCbabI7CRBkTHwhJ61KmqazMxiUuGRMhxlzl7BWB4,660 +aiogram/methods/pin_chat_message.py,sha256=njAbF_yEAZobt9b-0CqxblQpJ2M-jAgZHDpKdw_THAI,2143 +aiogram/methods/promote_chat_member.py,sha256=BDT9L1MIVTwWrmph-HUe0Rh7kKMPQt4bkMkICPiDfgE,5568 +aiogram/methods/refund_star_payment.py,sha256=s-eELWhpYoE8ubWNvlYc0dmPGCcBiATS0fU50IXXZ5g,1264 +aiogram/methods/reopen_forum_topic.py,sha256=TfJtX4zGVNYjjhivHRwBFV9sbWINhr8k_q5lXoLtITw,1480 +aiogram/methods/reopen_general_forum_topic.py,sha256=kxJtoOauJNWYxqesoT6qeDvXAJujUZvK-3QO5lnFEw8,1287 +aiogram/methods/replace_sticker_in_set.py,sha256=df80oQuwZsYrbmUixIPxtQ75iUqIMZXsiIyoMZHious,1858 +aiogram/methods/restrict_chat_member.py,sha256=KFAtkHVDqA4Ny4quy1jCnqH1mxf_5kSo8kDlA_ben4Q,2751 +aiogram/methods/revoke_chat_invite_link.py,sha256=RrIN4jcxTHaoThF0Dru3d4z7RGEQk0u0cTkNx13Do-s,1526 +aiogram/methods/send_animation.py,sha256=axQu7PxIUqpMtxCJH-7-5aUxzTl1UnUexDMkXXzRK3c,7678 +aiogram/methods/send_audio.py,sha256=6SrnsKd4smXuDLR3PfpgV9gf2TXBb42GtBxJGt6jeBY,7134 +aiogram/methods/send_chat_action.py,sha256=sOrGWv2bA9Przot-gPT1ksZ8UEhPpJeEsd7tPd-06gg,3187 +aiogram/methods/send_contact.py,sha256=zyup2lC1OQ94IXs1yW0Or4j8SaAqUe_a_AVTIE1rlJs,5053 +aiogram/methods/send_dice.py,sha256=v4j0-lETnu_rjj8oD3KdvOwMUh_IkXXcnWJW7jZmg-E,4823 +aiogram/methods/send_document.py,sha256=-ANAOHscFJhk3Y0LfmvAO_1_u3BUhEdBQ3YYafc5u64,6886 +aiogram/methods/send_game.py,sha256=gtcKxuwixa1N3JXOY8bLqCuvQ30QYrhi89VChwRTDmU,4243 +aiogram/methods/send_invoice.py,sha256=grSq2uQhWGWI4VLTCVBsuzbkrnrOkLAlBALUb8NLmbE,10135 +aiogram/methods/send_location.py,sha256=52UX5uvJBNfA80CEdmSEPTAmymurXXkYeEPXNitaY38,5851 +aiogram/methods/send_media_group.py,sha256=C67CTZUPPgqrDLGwP1mxzREridLXhBMpVKyfzL2wS-c,4430 +aiogram/methods/send_message.py,sha256=pMW81tP9p21i6iMo_KWYBhgy_uM2k_oa1_7kLQ81HN4,6112 +aiogram/methods/send_paid_media.py,sha256=Wf66l54kgMqWGTfMioVe0xdS-P3x2NQ4MpZkcHfson0,4658 +aiogram/methods/send_photo.py,sha256=2mN1S3ppYKaTzs6omllqGEZiRbd7Hx3XD5V1fxiOdwo,6492 +aiogram/methods/send_poll.py,sha256=_ATWrR7o6OeI8bllk83HRsG24-8w7TQzif3qpxFxYrs,8387 +aiogram/methods/send_sticker.py,sha256=mfqQAqLimwwNMhWwqokA7SQoNV17z1_cO-SiBBZFHAU,5284 +aiogram/methods/send_venue.py,sha256=rYIxNQbd_fZJybWLcFS4OmbE2EYvKrReqQyegMpNoxo,5820 +aiogram/methods/send_video.py,sha256=LfebSy4ucxxQi-euGGfTpXfLjWfn_AcCN7NkUh76tbk,7894 +aiogram/methods/send_video_note.py,sha256=dAXiWtv1hngrGQONybstfrC_Q29po0BpKHuVzGKx9I4,6038 +aiogram/methods/send_voice.py,sha256=Dk-oqbTfs_ZAHLpAyFgDlKd2sU0IVc8-8JAitlVNKRA,6282 +aiogram/methods/set_chat_administrator_custom_title.py,sha256=lOizk5Z8-tUh6EOiZ2hRyVSUrP2qQzDHlcKIbJCKgSg,1490 +aiogram/methods/set_chat_description.py,sha256=AvzTU_XRaTuI9s9iKX_hihCLpsH4F8du3dBQ-wrNZnU,1407 +aiogram/methods/set_chat_menu_button.py,sha256=5y8sOvgs6cH4sWBa_NuBnsRH7sE8ch0_s4YygG1PbZY,1622 +aiogram/methods/set_chat_permissions.py,sha256=x42Gmf910ycY0Nf5lCnM1Xe6z5bhjNqUMHA673X1J_A,2159 +aiogram/methods/set_chat_photo.py,sha256=kHjTl8U-i5B03KaFIEKxQnT8Sgl8CAa_F9kQeFUW_9M,1394 +aiogram/methods/set_chat_sticker_set.py,sha256=RFNtIcj8Lq8It6L6qoJLCk247RYVgGROdJM5UoF0HSQ,1571 +aiogram/methods/set_chat_title.py,sha256=X21F3pX37t3z13-4o6WJfQHKVfLPr8c_HGO-vNqI3k0,1275 +aiogram/methods/set_custom_emoji_sticker_set_thumbnail.py,sha256=E8zURRFNnJnjzxVnYchBta807eCrarjMzpKWp0R5Ypg,1309 +aiogram/methods/set_game_score.py,sha256=RDiYH61W1aN6WZoRLKI_vDQJz8-7V1I8tP__UbZLw1s,2626 +aiogram/methods/set_message_reaction.py,sha256=bEK822WDw3OqvO99WU3IV543yYI7tWpA-mIJVgv2rGg,2457 +aiogram/methods/set_my_commands.py,sha256=sjd1da-uPfDIH0OGTpuyZzBl8ARwbWPiMoAHenQc530,2803 +aiogram/methods/set_my_default_administrator_rights.py,sha256=DKX3KXLXbfv-heE5uJfPbcFXQRvNG6ps3ih1bQNa5RY,1750 +aiogram/methods/set_my_description.py,sha256=ww9IAjtC4X6Ti9cFlnE3dleZ_FKE6byjblGUYn2EqwI,1489 +aiogram/methods/set_my_name.py,sha256=xqSgEYS3Rgr2ETQlvBuD_VopBsuDX_DZY_MnbsOoJgs,1274 +aiogram/methods/set_my_short_description.py,sha256=ONiD6HfZxxnHRjPstEmuBqedjQVjZ-lSJPY14sTRPyc,1639 +aiogram/methods/set_passport_data_errors.py,sha256=Z4SjM_CHHzXw_SQ5TsIFXvsrI5GTrgx0xO0kKrtnE7c,2922 +aiogram/methods/set_sticker_emoji_list.py,sha256=rgUpD35X_QHAJmIbdgRBsXtF4p-wQcuRFFYmNBjDPpo,1201 +aiogram/methods/set_sticker_keywords.py,sha256=usS8uLY4YghFWwNyJnpG9C5X9eRQ1PzGWfIxSKhPTOg,1320 +aiogram/methods/set_sticker_mask_position.py,sha256=eoT5D9VmWuRNsUqyzrHlYWd_bVaK583o3hP_KsoevaI,1450 +aiogram/methods/set_sticker_position_in_set.py,sha256=QJI3x-tobyjpFoEThjcqGQLjXWdCZTd59ei49Gi2Mcg,1100 +aiogram/methods/set_sticker_set_thumbnail.py,sha256=l6hozWYpPQI-Y-QI2YxyXopG8ZXzGme-q2vdl4SUJvk,2891 +aiogram/methods/set_sticker_set_title.py,sha256=kf1H5K3capHR5wlu91DXmP6Q1G_TG_AEJeivppuM-58,1011 +aiogram/methods/set_webhook.py,sha256=5mPLVBDfSDbw2BEsSThw6wfErFTta_55UtyisYA4o1k,4476 +aiogram/methods/stop_message_live_location.py,sha256=ZvsRZ_qADXt3Oxxk8-6nvOAHT5b-yL2v4isAxNChE7M,2539 +aiogram/methods/stop_poll.py,sha256=xs5Bhzdwrny9CueVr1qfe6lOWjPqKoS8te9PYvpTZs4,1933 +aiogram/methods/unban_chat_member.py,sha256=kCOiIN03O3RZG4esxneAnt87-iC24TKqW4FeAOcBPCY,1919 +aiogram/methods/unban_chat_sender_chat.py,sha256=JwiCTYpl797vXH1iKEmHdvngNgmN3N5MzTM6Bd5QI3o,1376 +aiogram/methods/unhide_general_forum_topic.py,sha256=vDxVKNhnBifPmhBxDtIgEGq9DLw5U0E-HUPoIVOEL_I,1223 +aiogram/methods/unpin_all_chat_messages.py,sha256=1eYhMh4IsLV4x94XEC7oJkkFeiwe1LSpr_sj2ywyvUY,1303 +aiogram/methods/unpin_all_forum_topic_messages.py,sha256=RDUz0D8kSuayzY0DU0DVo6ez2dUH8VdqBmTSthCECCc,1489 +aiogram/methods/unpin_all_general_forum_topic_messages.py,sha256=O_PhZuwarHW9I2iFIHggOqgc7QfXtF1GEqZYweOH5PA,1248 +aiogram/methods/unpin_chat_message.py,sha256=9iiJcGt8sU1vYKKeMGpk7KgMvTXnLysywExpsjWckgs,1978 +aiogram/methods/upload_sticker_file.py,sha256=TgGArcP8fVpAOM7GRmpbk7GO3sKn2PfBEV--WOo0NKo,1951 +aiogram/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/types/__init__.py,sha256=YUQNYA592qPfHdhV_Lv90St1aCXLaMYyzOm-QQhLcNw,18420 +aiogram/types/__pycache__/__init__.cpython-311.pyc,, +aiogram/types/__pycache__/animation.cpython-311.pyc,, +aiogram/types/__pycache__/audio.cpython-311.pyc,, +aiogram/types/__pycache__/background_fill.cpython-311.pyc,, +aiogram/types/__pycache__/background_fill_freeform_gradient.cpython-311.pyc,, +aiogram/types/__pycache__/background_fill_gradient.cpython-311.pyc,, +aiogram/types/__pycache__/background_fill_solid.cpython-311.pyc,, +aiogram/types/__pycache__/background_type.cpython-311.pyc,, +aiogram/types/__pycache__/background_type_chat_theme.cpython-311.pyc,, +aiogram/types/__pycache__/background_type_fill.cpython-311.pyc,, +aiogram/types/__pycache__/background_type_pattern.cpython-311.pyc,, +aiogram/types/__pycache__/background_type_wallpaper.cpython-311.pyc,, +aiogram/types/__pycache__/base.cpython-311.pyc,, +aiogram/types/__pycache__/birthdate.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command_scope.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command_scope_all_chat_administrators.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command_scope_all_group_chats.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command_scope_all_private_chats.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command_scope_chat.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command_scope_chat_administrators.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command_scope_chat_member.cpython-311.pyc,, +aiogram/types/__pycache__/bot_command_scope_default.cpython-311.pyc,, +aiogram/types/__pycache__/bot_description.cpython-311.pyc,, +aiogram/types/__pycache__/bot_name.cpython-311.pyc,, +aiogram/types/__pycache__/bot_short_description.cpython-311.pyc,, +aiogram/types/__pycache__/business_connection.cpython-311.pyc,, +aiogram/types/__pycache__/business_intro.cpython-311.pyc,, +aiogram/types/__pycache__/business_location.cpython-311.pyc,, +aiogram/types/__pycache__/business_messages_deleted.cpython-311.pyc,, +aiogram/types/__pycache__/business_opening_hours.cpython-311.pyc,, +aiogram/types/__pycache__/business_opening_hours_interval.cpython-311.pyc,, +aiogram/types/__pycache__/callback_game.cpython-311.pyc,, +aiogram/types/__pycache__/callback_query.cpython-311.pyc,, +aiogram/types/__pycache__/chat.cpython-311.pyc,, +aiogram/types/__pycache__/chat_administrator_rights.cpython-311.pyc,, +aiogram/types/__pycache__/chat_background.cpython-311.pyc,, +aiogram/types/__pycache__/chat_boost.cpython-311.pyc,, +aiogram/types/__pycache__/chat_boost_added.cpython-311.pyc,, +aiogram/types/__pycache__/chat_boost_removed.cpython-311.pyc,, +aiogram/types/__pycache__/chat_boost_source.cpython-311.pyc,, +aiogram/types/__pycache__/chat_boost_source_gift_code.cpython-311.pyc,, +aiogram/types/__pycache__/chat_boost_source_giveaway.cpython-311.pyc,, +aiogram/types/__pycache__/chat_boost_source_premium.cpython-311.pyc,, +aiogram/types/__pycache__/chat_boost_updated.cpython-311.pyc,, +aiogram/types/__pycache__/chat_full_info.cpython-311.pyc,, +aiogram/types/__pycache__/chat_invite_link.cpython-311.pyc,, +aiogram/types/__pycache__/chat_join_request.cpython-311.pyc,, +aiogram/types/__pycache__/chat_location.cpython-311.pyc,, +aiogram/types/__pycache__/chat_member.cpython-311.pyc,, +aiogram/types/__pycache__/chat_member_administrator.cpython-311.pyc,, +aiogram/types/__pycache__/chat_member_banned.cpython-311.pyc,, +aiogram/types/__pycache__/chat_member_left.cpython-311.pyc,, +aiogram/types/__pycache__/chat_member_member.cpython-311.pyc,, +aiogram/types/__pycache__/chat_member_owner.cpython-311.pyc,, +aiogram/types/__pycache__/chat_member_restricted.cpython-311.pyc,, +aiogram/types/__pycache__/chat_member_updated.cpython-311.pyc,, +aiogram/types/__pycache__/chat_permissions.cpython-311.pyc,, +aiogram/types/__pycache__/chat_photo.cpython-311.pyc,, +aiogram/types/__pycache__/chat_shared.cpython-311.pyc,, +aiogram/types/__pycache__/chosen_inline_result.cpython-311.pyc,, +aiogram/types/__pycache__/contact.cpython-311.pyc,, +aiogram/types/__pycache__/custom.cpython-311.pyc,, +aiogram/types/__pycache__/dice.cpython-311.pyc,, +aiogram/types/__pycache__/document.cpython-311.pyc,, +aiogram/types/__pycache__/downloadable.cpython-311.pyc,, +aiogram/types/__pycache__/encrypted_credentials.cpython-311.pyc,, +aiogram/types/__pycache__/encrypted_passport_element.cpython-311.pyc,, +aiogram/types/__pycache__/error_event.cpython-311.pyc,, +aiogram/types/__pycache__/external_reply_info.cpython-311.pyc,, +aiogram/types/__pycache__/file.cpython-311.pyc,, +aiogram/types/__pycache__/force_reply.cpython-311.pyc,, +aiogram/types/__pycache__/forum_topic.cpython-311.pyc,, +aiogram/types/__pycache__/forum_topic_closed.cpython-311.pyc,, +aiogram/types/__pycache__/forum_topic_created.cpython-311.pyc,, +aiogram/types/__pycache__/forum_topic_edited.cpython-311.pyc,, +aiogram/types/__pycache__/forum_topic_reopened.cpython-311.pyc,, +aiogram/types/__pycache__/game.cpython-311.pyc,, +aiogram/types/__pycache__/game_high_score.cpython-311.pyc,, +aiogram/types/__pycache__/general_forum_topic_hidden.cpython-311.pyc,, +aiogram/types/__pycache__/general_forum_topic_unhidden.cpython-311.pyc,, +aiogram/types/__pycache__/giveaway.cpython-311.pyc,, +aiogram/types/__pycache__/giveaway_completed.cpython-311.pyc,, +aiogram/types/__pycache__/giveaway_created.cpython-311.pyc,, +aiogram/types/__pycache__/giveaway_winners.cpython-311.pyc,, +aiogram/types/__pycache__/inaccessible_message.cpython-311.pyc,, +aiogram/types/__pycache__/inline_keyboard_button.cpython-311.pyc,, +aiogram/types/__pycache__/inline_keyboard_markup.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_article.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_audio.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_cached_audio.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_cached_document.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_cached_gif.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_cached_mpeg4_gif.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_cached_photo.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_cached_sticker.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_cached_video.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_cached_voice.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_contact.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_document.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_game.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_gif.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_location.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_mpeg4_gif.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_photo.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_venue.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_video.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_result_voice.cpython-311.pyc,, +aiogram/types/__pycache__/inline_query_results_button.cpython-311.pyc,, +aiogram/types/__pycache__/input_contact_message_content.cpython-311.pyc,, +aiogram/types/__pycache__/input_file.cpython-311.pyc,, +aiogram/types/__pycache__/input_invoice_message_content.cpython-311.pyc,, +aiogram/types/__pycache__/input_location_message_content.cpython-311.pyc,, +aiogram/types/__pycache__/input_media.cpython-311.pyc,, +aiogram/types/__pycache__/input_media_animation.cpython-311.pyc,, +aiogram/types/__pycache__/input_media_audio.cpython-311.pyc,, +aiogram/types/__pycache__/input_media_document.cpython-311.pyc,, +aiogram/types/__pycache__/input_media_photo.cpython-311.pyc,, +aiogram/types/__pycache__/input_media_video.cpython-311.pyc,, +aiogram/types/__pycache__/input_message_content.cpython-311.pyc,, +aiogram/types/__pycache__/input_paid_media.cpython-311.pyc,, +aiogram/types/__pycache__/input_paid_media_photo.cpython-311.pyc,, +aiogram/types/__pycache__/input_paid_media_video.cpython-311.pyc,, +aiogram/types/__pycache__/input_poll_option.cpython-311.pyc,, +aiogram/types/__pycache__/input_sticker.cpython-311.pyc,, +aiogram/types/__pycache__/input_text_message_content.cpython-311.pyc,, +aiogram/types/__pycache__/input_venue_message_content.cpython-311.pyc,, +aiogram/types/__pycache__/invoice.cpython-311.pyc,, +aiogram/types/__pycache__/keyboard_button.cpython-311.pyc,, +aiogram/types/__pycache__/keyboard_button_poll_type.cpython-311.pyc,, +aiogram/types/__pycache__/keyboard_button_request_chat.cpython-311.pyc,, +aiogram/types/__pycache__/keyboard_button_request_user.cpython-311.pyc,, +aiogram/types/__pycache__/keyboard_button_request_users.cpython-311.pyc,, +aiogram/types/__pycache__/labeled_price.cpython-311.pyc,, +aiogram/types/__pycache__/link_preview_options.cpython-311.pyc,, +aiogram/types/__pycache__/location.cpython-311.pyc,, +aiogram/types/__pycache__/login_url.cpython-311.pyc,, +aiogram/types/__pycache__/mask_position.cpython-311.pyc,, +aiogram/types/__pycache__/maybe_inaccessible_message.cpython-311.pyc,, +aiogram/types/__pycache__/menu_button.cpython-311.pyc,, +aiogram/types/__pycache__/menu_button_commands.cpython-311.pyc,, +aiogram/types/__pycache__/menu_button_default.cpython-311.pyc,, +aiogram/types/__pycache__/menu_button_web_app.cpython-311.pyc,, +aiogram/types/__pycache__/message.cpython-311.pyc,, +aiogram/types/__pycache__/message_auto_delete_timer_changed.cpython-311.pyc,, +aiogram/types/__pycache__/message_entity.cpython-311.pyc,, +aiogram/types/__pycache__/message_id.cpython-311.pyc,, +aiogram/types/__pycache__/message_origin.cpython-311.pyc,, +aiogram/types/__pycache__/message_origin_channel.cpython-311.pyc,, +aiogram/types/__pycache__/message_origin_chat.cpython-311.pyc,, +aiogram/types/__pycache__/message_origin_hidden_user.cpython-311.pyc,, +aiogram/types/__pycache__/message_origin_user.cpython-311.pyc,, +aiogram/types/__pycache__/message_reaction_count_updated.cpython-311.pyc,, +aiogram/types/__pycache__/message_reaction_updated.cpython-311.pyc,, +aiogram/types/__pycache__/order_info.cpython-311.pyc,, +aiogram/types/__pycache__/paid_media.cpython-311.pyc,, +aiogram/types/__pycache__/paid_media_info.cpython-311.pyc,, +aiogram/types/__pycache__/paid_media_photo.cpython-311.pyc,, +aiogram/types/__pycache__/paid_media_preview.cpython-311.pyc,, +aiogram/types/__pycache__/paid_media_video.cpython-311.pyc,, +aiogram/types/__pycache__/passport_data.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_data_field.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_file.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_files.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_front_side.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_reverse_side.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_selfie.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_translation_file.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_translation_files.cpython-311.pyc,, +aiogram/types/__pycache__/passport_element_error_unspecified.cpython-311.pyc,, +aiogram/types/__pycache__/passport_file.cpython-311.pyc,, +aiogram/types/__pycache__/photo_size.cpython-311.pyc,, +aiogram/types/__pycache__/poll.cpython-311.pyc,, +aiogram/types/__pycache__/poll_answer.cpython-311.pyc,, +aiogram/types/__pycache__/poll_option.cpython-311.pyc,, +aiogram/types/__pycache__/pre_checkout_query.cpython-311.pyc,, +aiogram/types/__pycache__/proximity_alert_triggered.cpython-311.pyc,, +aiogram/types/__pycache__/reaction_count.cpython-311.pyc,, +aiogram/types/__pycache__/reaction_type.cpython-311.pyc,, +aiogram/types/__pycache__/reaction_type_custom_emoji.cpython-311.pyc,, +aiogram/types/__pycache__/reaction_type_emoji.cpython-311.pyc,, +aiogram/types/__pycache__/reaction_type_paid.cpython-311.pyc,, +aiogram/types/__pycache__/refunded_payment.cpython-311.pyc,, +aiogram/types/__pycache__/reply_keyboard_markup.cpython-311.pyc,, +aiogram/types/__pycache__/reply_keyboard_remove.cpython-311.pyc,, +aiogram/types/__pycache__/reply_parameters.cpython-311.pyc,, +aiogram/types/__pycache__/response_parameters.cpython-311.pyc,, +aiogram/types/__pycache__/revenue_withdrawal_state.cpython-311.pyc,, +aiogram/types/__pycache__/revenue_withdrawal_state_failed.cpython-311.pyc,, +aiogram/types/__pycache__/revenue_withdrawal_state_pending.cpython-311.pyc,, +aiogram/types/__pycache__/revenue_withdrawal_state_succeeded.cpython-311.pyc,, +aiogram/types/__pycache__/sent_web_app_message.cpython-311.pyc,, +aiogram/types/__pycache__/shared_user.cpython-311.pyc,, +aiogram/types/__pycache__/shipping_address.cpython-311.pyc,, +aiogram/types/__pycache__/shipping_option.cpython-311.pyc,, +aiogram/types/__pycache__/shipping_query.cpython-311.pyc,, +aiogram/types/__pycache__/star_transaction.cpython-311.pyc,, +aiogram/types/__pycache__/star_transactions.cpython-311.pyc,, +aiogram/types/__pycache__/sticker.cpython-311.pyc,, +aiogram/types/__pycache__/sticker_set.cpython-311.pyc,, +aiogram/types/__pycache__/story.cpython-311.pyc,, +aiogram/types/__pycache__/successful_payment.cpython-311.pyc,, +aiogram/types/__pycache__/switch_inline_query_chosen_chat.cpython-311.pyc,, +aiogram/types/__pycache__/text_quote.cpython-311.pyc,, +aiogram/types/__pycache__/transaction_partner.cpython-311.pyc,, +aiogram/types/__pycache__/transaction_partner_fragment.cpython-311.pyc,, +aiogram/types/__pycache__/transaction_partner_other.cpython-311.pyc,, +aiogram/types/__pycache__/transaction_partner_telegram_ads.cpython-311.pyc,, +aiogram/types/__pycache__/transaction_partner_user.cpython-311.pyc,, +aiogram/types/__pycache__/update.cpython-311.pyc,, +aiogram/types/__pycache__/user.cpython-311.pyc,, +aiogram/types/__pycache__/user_chat_boosts.cpython-311.pyc,, +aiogram/types/__pycache__/user_profile_photos.cpython-311.pyc,, +aiogram/types/__pycache__/user_shared.cpython-311.pyc,, +aiogram/types/__pycache__/users_shared.cpython-311.pyc,, +aiogram/types/__pycache__/venue.cpython-311.pyc,, +aiogram/types/__pycache__/video.cpython-311.pyc,, +aiogram/types/__pycache__/video_chat_ended.cpython-311.pyc,, +aiogram/types/__pycache__/video_chat_participants_invited.cpython-311.pyc,, +aiogram/types/__pycache__/video_chat_scheduled.cpython-311.pyc,, +aiogram/types/__pycache__/video_chat_started.cpython-311.pyc,, +aiogram/types/__pycache__/video_note.cpython-311.pyc,, +aiogram/types/__pycache__/voice.cpython-311.pyc,, +aiogram/types/__pycache__/web_app_data.cpython-311.pyc,, +aiogram/types/__pycache__/web_app_info.cpython-311.pyc,, +aiogram/types/__pycache__/webhook_info.cpython-311.pyc,, +aiogram/types/__pycache__/write_access_allowed.cpython-311.pyc,, +aiogram/types/animation.py,sha256=W9LGC1-JeWGolCU3OI1a3dXjtD5pCnaOd_J7ulWhau8,2673 +aiogram/types/audio.py,sha256=2WPtZmAQfW6ewCb6ozlcfXXZACQEX7c1MYTEVMAy9Lw,2823 +aiogram/types/background_fill.py,sha256=sJj85JGxTXOJVd_dq0jpgH5TbBPlvRKFNjk2CNoM5Bw,513 +aiogram/types/background_fill_freeform_gradient.py,sha256=R74cAjirD-pqisj3KiMKuQj5uALD7ZY5DagTNYZ18Xk,1207 +aiogram/types/background_fill_gradient.py,sha256=bSkNQPDrdWCrSIoCSBE3iFI3NaOAk2cktmLOFUbX2qA,1434 +aiogram/types/background_fill_solid.py,sha256=cL3N_tRhRdpM3rGYjHqh1c05Ys1_w5Sn5RVFX4Kzrhc,1022 +aiogram/types/background_type.py,sha256=_UKdw_LQfpR4z7W8wdtEmKV38EUlsSCheh0l4O0d90Y,540 +aiogram/types/background_type_chat_theme.py,sha256=1mylq_KCHfLYikVuv2FVNHTK-FivuOc3fIN16ThxGX0,1077 +aiogram/types/background_type_fill.py,sha256=P3mjIBc_oZspRCYLZvep1Tjx2F2r3Gz8QnK3ZhBRXr0,1656 +aiogram/types/background_type_pattern.py,sha256=7y5N7vxg4EauwCLqAf_7VjfYGcdDLWt5P2wieNZl9i4,2514 +aiogram/types/background_type_wallpaper.py,sha256=6uYeiZ4xQBTmJY0jCTeUFAj65Q872NZL7D2-WMeSLac,1868 +aiogram/types/base.py,sha256=ZAKfSk-DVyoBoYdyyZUTkoIKzuaj0kJS0ophsohsdI4,1762 +aiogram/types/birthdate.py,sha256=ev957uyU2tG4cRqQ838h8LHW0uIPFUu0TdC1YfL0mnY,1056 +aiogram/types/bot_command.py,sha256=rJuwZroECtHDZxhyv92K2vyTUlXdieXdCEhewEsIPk0,1017 +aiogram/types/bot_command_scope.py,sha256=rs7YoyRACVLm4tMMEQ01LM6ckWbF7o81edYEAnWXoyY,951 +aiogram/types/bot_command_scope_all_chat_administrators.py,sha256=3wvcWAh_yZADVbqPQD09kd1hyjmDL_KuoYR8us7A0jI,1311 +aiogram/types/bot_command_scope_all_group_chats.py,sha256=BElN12t3RwjYAFgo__K4PSUA5Mf0Vgzx6lzrhO1_kOY,1225 +aiogram/types/bot_command_scope_all_private_chats.py,sha256=1Ww3HUSSJINy4qNSqF5lybQJwWHpflhMM2So6EMplyg,1226 +aiogram/types/bot_command_scope_chat.py,sha256=chjf7klLRhCM8AB1xwkfkPfUXcw-_vnQekRVkiIB1Rs,1327 +aiogram/types/bot_command_scope_chat_administrators.py,sha256=ezkiv48UyMIlKyZXvmlmsLi9cop5pk6cZW6FLgFJr-E,1518 +aiogram/types/bot_command_scope_chat_member.py,sha256=IvFP2cemuZtMFdIn7T7hfo4o4-35_1ZBTOHV5pARCQI,1513 +aiogram/types/bot_command_scope_default.py,sha256=Aqa5eiFS2_2rd8S19i7qfBPIk8TNPVdOEOMR1oSPMuI,1270 +aiogram/types/bot_description.py,sha256=daKHDJ4d2c9j7wCTKwDLgbXy1HNrjbYkZkwC9D7FiPQ,781 +aiogram/types/bot_name.py,sha256=ut3sf9j5LYd2xki-_pZ1lnVvN7HOUr6v37llIi75j6w,717 +aiogram/types/bot_short_description.py,sha256=UdHLoRvp1hdhEg-W1XYUoDwPeCxvuU2H430JrNDiY4U,849 +aiogram/types/business_connection.py,sha256=B3LuYw0bZwli2E2d6L9CGE_Rm1IvnzpD0RyCmZWxljU,2056 +aiogram/types/business_intro.py,sha256=TTTNSlPX-bvzbDqKd-YzwXaUjgznpZxnBDGtAKpmSBc,1303 +aiogram/types/business_location.py,sha256=OHFm2V3jLoRWJdXS3ubflMjFGd2Wo6sMhMhvsHbJUUY,1103 +aiogram/types/business_messages_deleted.py,sha256=AZvMF6tTIcq1pRoY2lHE8VPNJ26l5lgaeXLZ0rwZEq0,1478 +aiogram/types/business_opening_hours.py,sha256=R0il4hXIel_WWaB0DZUR3lgd816IDxXZFwmEi04glSE,1282 +aiogram/types/business_opening_hours_interval.py,sha256=NFi-_QWLEN_0D1fPpqqp2TlrdWBJ71Rz7c4P-lSWj9Y,1329 +aiogram/types/callback_game.py,sha256=AF-WqkqFcC6nG_tKoNX1sRjRiKEstbEFJfLy4NPKtRQ,298 +aiogram/types/callback_query.py,sha256=JBnbrz0j0C6zK1eMeCgQ7l28ytKVxxkExVbwDsc2u4Y,6017 +aiogram/types/chat.py,sha256=LnnFHYcYdWkXZ3KNIedhnXpqbt_d_jDoan2fQdATNpA,64452 +aiogram/types/chat_administrator_rights.py,sha256=xwIgM6y2daN5FSYNJagmhBtgEy88S9GTSQk_OWgrykU,4578 +aiogram/types/chat_background.py,sha256=tGylRgxxa5pMDsuQFkG2XrY7mKQCsA9lc-BsaArwXEE,1400 +aiogram/types/chat_boost.py,sha256=iAbDstYKPATDpf9C0UTaeeipi1kcFedXhiTC6INxEuQ,1879 +aiogram/types/chat_boost_added.py,sha256=4WPPng6cqzhb0qpepGeu4mAoga2ieA2vmqIxWQR5n-A,811 +aiogram/types/chat_boost_removed.py,sha256=phu1WXsR6noLlEuiwyF1S0HzlwDmFsk2vwc9TRJ00K0,1768 +aiogram/types/chat_boost_source.py,sha256=-s9Um1lFg4ab2MiQpb1SpJlKM2hJHZkpM43TQE6GEMo,476 +aiogram/types/chat_boost_source_gift_code.py,sha256=VkPQktCIZdyI7wvhR-c7hgDs8lI2XySv_tCX1IJoFDc,1378 +aiogram/types/chat_boost_source_giveaway.py,sha256=ncM8YI0ra6Jb_cDeOFFfm1l0sDwaZT4TNVGbFbas6Zo,1976 +aiogram/types/chat_boost_source_premium.py,sha256=nN3o9Kvt5JHXcp1RpYq1WDX8Szzn9so1-FgGR1Olf38,1278 +aiogram/types/chat_boost_updated.py,sha256=L0LKL6jutsHYPbCDQoXHaZVjIS5y7uIDXlacKNIFvE0,1002 +aiogram/types/chat_full_info.py,sha256=gYA2B-STpK5Iz3sGxlKYBdJ1tDJNNC_LgJbJGI47dlY,13713 +aiogram/types/chat_invite_link.py,sha256=BBsofu3IJb7dpZvZHnZNStaaVWYhb8Bn9AhMq6jc_d4,2638 +aiogram/types/chat_join_request.py,sha256=IeM2JRKIMVyVBXA1309TLoNuBo-ExjIbkNJL53YUYeU,171076 +aiogram/types/chat_location.py,sha256=qZUA9NnQBDCHRLvKDP1Oo0wDX5T5tw-j14-NX8tlXSM,1062 +aiogram/types/chat_member.py,sha256=sq0RhcwghiW4Gy9XJTskFA3dHxaol5EA5Oify1QJfz4,722 +aiogram/types/chat_member_administrator.py,sha256=d7se9Lm1AWDuZRNYGbK3ZLC2NkZVkSzegziJ0Lx66Qc,5453 +aiogram/types/chat_member_banned.py,sha256=bvvMSTPn4iNy6N5nGoPYoxR3pjqDZhFFqvGC_Jb1T3M,1500 +aiogram/types/chat_member_left.py,sha256=YhW1LjLUG5TDTARmj44DaJ0OyX2Gm8CW9-K6EA7LYgI,1254 +aiogram/types/chat_member_member.py,sha256=2AtZsJz3aICbn2eqCmG1p0UsBYSqlNLmN-wnqnC6uks,1482 +aiogram/types/chat_member_owner.py,sha256=2gV3f1ubns_eORZjJocWSuwH8IW_cv2j2I0MuHbVa68,1676 +aiogram/types/chat_member_restricted.py,sha256=7F40ERHf29ihfrB4tTc9JWL5w5xRBjqVLGoMWMgyWlg,4545 +aiogram/types/chat_member_updated.py,sha256=AS5_q6EXSBL2Wuy6lQXzn7gaXUPGZJWOWgGK1GCvx2c,87547 +aiogram/types/chat_permissions.py,sha256=A6I6DuCQGRWBqhQuVe8xMnRkd9i0iD7gOZm6Qg7m0LY,4382 +aiogram/types/chat_photo.py,sha256=BouKO-6NIn5d17fB9acX9iAbv_gjYzbeKuTqN3BcFD4,1872 +aiogram/types/chat_shared.py,sha256=O6taLjKlBX-z15XYZ6Hcp9SsUCYhBa9Sz7hKzAvi2as,2260 +aiogram/types/chosen_inline_result.py,sha256=VFMo9FklvYjWrPbwrxeIyHrDwLlRvnFObUV5EhaannU,2399 +aiogram/types/contact.py,sha256=jWvv9gc-4LyFyBLeAeucyr7A8yjBk7-sJQH10NKoydU,1848 +aiogram/types/custom.py,sha256=3Xqsx2Llx47Hu1v4hGEFOjbMzkgkdQ9lmKW87Atulp4,819 +aiogram/types/dice.py,sha256=QOFOqUx3jqVtqU_nwuWhhSthy5CBR_mNTMuIpwiD2KY,1165 +aiogram/types/document.py,sha256=6tKzYSPyON6BoWLn3F3tiXHUxaQNG1YNl6kC6bO-0ZE,2425 +aiogram/types/downloadable.py,sha256=FbRdIM3Cpw3tcDzZvwy__u98aSKqMMJn2kKh9mK62B0,77 +aiogram/types/encrypted_credentials.py,sha256=1ZC-Q3c84mEVZGEK_cXTkqzX4FzBujn0_necxJ1uSPc,1521 +aiogram/types/encrypted_passport_element.py,sha256=9RmD1xbkrWw-DFb8QCUCWENswXBKklGqy0G3SX_TB78,4733 +aiogram/types/error_event.py,sha256=m0QrLksRJ0-x0q5xpb6iyI4rqPfiz3XJom_Gh75CJ-8,714 +aiogram/types/external_reply_info.py,sha256=aYYuCYyyz5DL3zhDgdECSkdvf6HyiiHSTN61dyVMGmU,7185 +aiogram/types/file.py,sha256=52bE-c7RjZmTdXk8ij8PJ5fsx2-1IfgedM763PmzGnQ,2166 +aiogram/types/force_reply.py,sha256=YkTteaPMOUH544hl9h6VDypMxyiLIKFd9KXryouTmVM,3024 +aiogram/types/forum_topic.py,sha256=CchPMME1NgB8WT9FWLgQ5mYZ7uXFG2yuTmDMaDZ6kcU,1422 +aiogram/types/forum_topic_closed.py,sha256=aw1K6fIadwJtSTZnyTQq3xtEf7920vodFjK5lHeKVgs,309 +aiogram/types/forum_topic_created.py,sha256=OPYpne_Zz5tdOpzjYOXGplCxLhF1aeKnHFzpn3qXIRg,1321 +aiogram/types/forum_topic_edited.py,sha256=Fq8QDirNBsymOKbAxBYnFqhmXL52XuqKAQrLxePRyA8,1230 +aiogram/types/forum_topic_reopened.py,sha256=MloV3nhDpHSLe5VoVgmC99u7ch3IYahIHH2EokGCWgY,315 +aiogram/types/game.py,sha256=AUnwPfixbvWpzxfoHziedT7WJtoF02vxBNz791j0fro,2365 +aiogram/types/game_high_score.py,sha256=rwCyO24y4BkcTJSmoLPA7pGEsgfA6-_3i40uvCgxp6k,1203 +aiogram/types/general_forum_topic_hidden.py,sha256=QC3u0Qpt3nptdhl3dxqgNXVrptwSAdnEzI-OWP8QMMw,301 +aiogram/types/general_forum_topic_unhidden.py,sha256=W8HRGyB81eyooaucgD0ojeAzywD8AjnMnUf2hf7r5Nk,307 +aiogram/types/giveaway.py,sha256=N5k2AXEdBRKRaHfDbYl_YuRGARaIAiOP1S49cAkGgc4,3042 +aiogram/types/giveaway_completed.py,sha256=m6QrBVrfT5s2W4mt-LoJwvHodkV7eIc112HOHLf9Z3k,1515 +aiogram/types/giveaway_created.py,sha256=6HYs2dBo4V6OBZpfoOAB7CxlMZQB_jPb01rEAw3RLe8,275 +aiogram/types/giveaway_winners.py,sha256=t2b4tX6twU0wlOEJLvrTbD_PB2pAcL3LDSycXhvQNw0,3321 +aiogram/types/inaccessible_message.py,sha256=Wn3WocufH3a8g0BE0S0TIK1pUQrt3NQBPAm-_9HhjSs,1288 +aiogram/types/inline_keyboard_button.py,sha256=1AwstgKnWwqrt0dI57_bMZNQWXAuEP74gxpYtHKN024,4769 +aiogram/types/inline_keyboard_markup.py,sha256=b6dxsxzM93LZyG41mXHPX4JKyKlPr3bqc-8s4zuUCpk,1273 +aiogram/types/inline_query.py,sha256=XCXCRESvVpbepiIYiJLcF48rc35K8sKrmeFw8iciLf4,7410 +aiogram/types/inline_query_result.py,sha256=8Ve8Fe1Yf6O7NHWCYdTVIgnbawI6hIo5B0l2cV5ZN20,2189 +aiogram/types/inline_query_result_article.py,sha256=Keq9BuANquPGxWDw9D8Yra7_vNDSvYSRfqK5Ml9e9yE,3759 +aiogram/types/inline_query_result_audio.py,sha256=6r3mHQQ4tA0kouOznWvE4izEJ9NarZBP-40-BOdn0Mo,4367 +aiogram/types/inline_query_result_cached_audio.py,sha256=7oYplK6rrWZrDAcXQqZvpnKOW_Kuj1vQ1oa3sqj-VcQ,4018 +aiogram/types/inline_query_result_cached_document.py,sha256=qvNPpMWQfJ-i_SCLDIHWDvuuRqFqYLuxqdLuaVq0_Nk,4360 +aiogram/types/inline_query_result_cached_gif.py,sha256=Mawa0gyeGd4-MSjVAJ1Pm62pBSakp9SpvOsGXOhpQ7Q,4601 +aiogram/types/inline_query_result_cached_mpeg4_gif.py,sha256=UtOhg-YOQPO3H3JkJZeZcUloxXgDmoaHHOBOg6x-GO0,4699 +aiogram/types/inline_query_result_cached_photo.py,sha256=LQPdR2UW9hvnz68YOziipLaajVqCPzVzK8yhjHJZSxc,4769 +aiogram/types/inline_query_result_cached_sticker.py,sha256=hqZ8ZvEv0jA0rf7WDVa4SVkaX5khDncpdSPoH5LWEcU,3100 +aiogram/types/inline_query_result_cached_video.py,sha256=Uyr7rlAZO4djHXnhfyoEItN_Mu30W8NkooZICLN8LKk,4739 +aiogram/types/inline_query_result_cached_voice.py,sha256=kvsqjskDe_Aor7WZvrijUsfZnJdum-krGxMwYl4GEGQ,4144 +aiogram/types/inline_query_result_contact.py,sha256=vAmYCE49k7pWHNA-1-L0p7pD2TljNdzitFgsE_hrYDI,4111 +aiogram/types/inline_query_result_document.py,sha256=yYEqSbiWqW3zDl2xX7WNcf2oraOu8zp7hr1BIqLrUeo,5047 +aiogram/types/inline_query_result_game.py,sha256=9t2HzFgVgHjPW_pQZ4YBTeGptSbn9KOHcGsbEPpUwzQ,1758 +aiogram/types/inline_query_result_gif.py,sha256=MNmFu5R4Jz1MbiDoznpsI7GBdy7-BB83QhVnF16HyhM,5577 +aiogram/types/inline_query_result_location.py,sha256=FX_eYlVfcRkcTTxubrTu1m3jGFWbgLEyg0R0TFp3ybY,4961 +aiogram/types/inline_query_result_mpeg4_gif.py,sha256=uL9AGdWYTaUJf3mM1v4iR-An8ZtWt-8XVpZY03vmZRI,5645 +aiogram/types/inline_query_result_photo.py,sha256=zWHeeIKMYQWHYzdIg9li93ziZ8acH9m-MSDmOLAiJA4,5245 +aiogram/types/inline_query_result_venue.py,sha256=pln1TVUl5cLvgxTxR1PEYLA7K69L9ZGAGxR_YQ0eQyY,4904 +aiogram/types/inline_query_result_video.py,sha256=9u6L-4nZVtUspl4nomPe3d0AuQHDv7EA3H1CmZQaJs8,5842 +aiogram/types/inline_query_result_voice.py,sha256=LUGfZZgL66NH6wppO9kpVnBoiCbC_zV6SBV3PBIBQJQ,4310 +aiogram/types/inline_query_results_button.py,sha256=mcDUu9wvU35tBvH1BhICorSlJ25XUVbpJlh9BWE3HNQ,1878 +aiogram/types/input_contact_message_content.py,sha256=GR2RDpizrX7rlxjf05CKzRT3zmLEO1yJSpqbmxCLwQA,1599 +aiogram/types/input_file.py,sha256=oCElYrCtJgfP5_ck0MQxvGppVZyXW5BnsHcmSg1Ds1o,4672 +aiogram/types/input_invoice_message_content.py,sha256=L4QePd9Bw7Mqy9L6vFTLL6iRsyJDB-YfOGfKNfVs24k,6899 +aiogram/types/input_location_message_content.py,sha256=UmmTHtSm-0MbIp2pISbl6FoPo9rjKeBK0pKzKg66GvE,2374 +aiogram/types/input_media.py,sha256=2nTD1Wg9VX8x74KTAf2d6OjjGTwPTUXaQL5Ty5TxvYQ,619 +aiogram/types/input_media_animation.py,sha256=BLpBBGSBzSRKpG-K7mQwguiof4cR58ElSNPwH9PdefQ,4373 +aiogram/types/input_media_audio.py,sha256=615pBywXCgGPIoeiqGep4D8SiMwTa83kmhasp0qqgHE,3706 +aiogram/types/input_media_document.py,sha256=2Z89Foqhnh3LviuiMcaU9rWg2kCVPQdNMvL_KrGckFM,3628 +aiogram/types/input_media_photo.py,sha256=QGqJC6qCGyEzbBLHsX8vw6pbnsk3l7eYA8AKmKA6WY4,3127 +aiogram/types/input_media_video.py,sha256=Yugn-j1NmMjMFP7ztI8XQMJVDZ_2KV_xJYdOCFSBk2I,4509 +aiogram/types/input_message_content.py,sha256=wj0C4RyiLpVP4yz0LmmO4qMNNIwRMihjnoMrjBSxjDE,793 +aiogram/types/input_paid_media.py,sha256=z-STAz_0G590-eFlOYNTv_HP1LOWbACXM0XMYbEBXrg,380 +aiogram/types/input_paid_media_photo.py,sha256=AHnkA6yvhhxdt_ffpCplgOxtqeh0YiDZ0WjVYj0boSA,1498 +aiogram/types/input_paid_media_video.py,sha256=nKQwP5BtYARot0LjkAr-EOa7UfbL8DwtFqexwoTNIY4,2977 +aiogram/types/input_poll_option.py,sha256=ky4L3A9Z2PuNTJL-WxMJ3o2zysphXaV2OukDdhXrLM4,1791 +aiogram/types/input_sticker.py,sha256=8smkhrtpZraqVrA_v87UuO4uNqzK_9bvPPVvDRrmCuY,2438 +aiogram/types/input_text_message_content.py,sha256=Er1EsUzQKV_p-spafMGNKL1saWlvvOmu4IBqFk03BaA,2720 +aiogram/types/input_venue_message_content.py,sha256=CZsCPYQrFdP_BrYBzNJ_Ik39PlJ1VLOsvI5q9vRS0Ns,2411 +aiogram/types/invoice.py,sha256=gOiw5G9yXJ8ZkAVupt2ww-mcooYanTix6t7KarSni9Y,1932 +aiogram/types/keyboard_button.py,sha256=L0cHsJEsKQziqK3zJN6laQL9drC36AhbhMOG20vhzcE,4352 +aiogram/types/keyboard_button_poll_type.py,sha256=tPGlW_jRXaDxZML1_vK080sp6BO86DO5cbBP-TEOf4Q,1153 +aiogram/types/keyboard_button_request_chat.py,sha256=N8UBPPlrQ07OSCO-33mfP5lKJ744sugaS86dYWpxMRQ,4448 +aiogram/types/keyboard_button_request_user.py,sha256=89efkQPnTYrtpBozhTvXp00YE8uKqgJInVUafJV7nkI,1990 +aiogram/types/keyboard_button_request_users.py,sha256=bhj4_scIdCcKxWeuC8f8guU_tcWTvwrbISe_PycG-XE,2747 +aiogram/types/labeled_price.py,sha256=7kRZPTy8HgJG4FYrix21xGfhgT_u93fROUBOj1wB4Rk,1330 +aiogram/types/link_preview_options.py,sha256=xv8Z-qE_NBfojELQHSlgegmsXso661AL8562z8i0dls,2747 +aiogram/types/location.py,sha256=0X9SBlANNn_ODEByFE0oDiJxpKtGEQ6OI6fDXB_1loA,2115 +aiogram/types/login_url.py,sha256=VxZTVG1LbmKeon_spDg17HJiPh1l1buOI5eFBNLu1Rk,2771 +aiogram/types/mask_position.py,sha256=ZH0pNJ8u4Xlos2MwCtsnSzMNfhgGvacCGdJ42qFp9no,1627 +aiogram/types/maybe_inaccessible_message.py,sha256=TbxUHEoW88w4nWer6zhQhWaAjTqr2Xi3H9-ZJRfvA9Q,388 +aiogram/types/menu_button.py,sha256=4Q2I_AlbnRe2fQ0f1a-LNl0toGOHI73ehjhMQmLngV4,2103 +aiogram/types/menu_button_commands.py,sha256=NMmH1S0jcEivjXmzRfMTLJAO4UBKVhFuo8wS4ONgZwc,1038 +aiogram/types/menu_button_default.py,sha256=FnjUz1-aXR3-0oHPv0pNU5yi1M86wnzwCbNnzEMu094,1027 +aiogram/types/menu_button_web_app.py,sha256=G-yWLPg91mgaMP672VRj6xmB8_UqDpMeH2iePvY0rw0,1715 +aiogram/types/message.py,sha256=AlHRfaN9KyEJjT887Jv6P52WLaMZvOKx_SgBEMcP7eM,240867 +aiogram/types/message_auto_delete_timer_changed.py,sha256=D9GoK5tOtxWTksB_yaIKthfiHWJhOI6SUBWWpW_PRTY,1020 +aiogram/types/message_entity.py,sha256=q_dWKJhMNVg8zGzIUy40b0viRNnBaZSPT_7ySANbwDw,3287 +aiogram/types/message_id.py,sha256=4I7m_laQsIwLiTOVG3B59BJLvlzGTkf0gai9aazqs0I,805 +aiogram/types/message_origin.py,sha256=uSs6n9q5JhIzaV42ldMJJL_8nAx_aCQ3xNqrRVMJsWg,518 +aiogram/types/message_origin_channel.py,sha256=tgCfiuS81A0oWD9EY90F0P3B9s-Avsm0FJlw5ra8umA,1795 +aiogram/types/message_origin_chat.py,sha256=_EE8lVR8Kp745dHTlT1zHYXEDImbGhq_nuZgteu9lbc,1725 +aiogram/types/message_origin_hidden_user.py,sha256=N8WXMNcBlWSuDMRYUxsUiZubnOxsDFOr7GyYQKRrij4,1377 +aiogram/types/message_origin_user.py,sha256=FTu0wnkg8AElOQtMjy2Ee-ApL2eX57a5qMrudWMWf90,1349 +aiogram/types/message_reaction_count_updated.py,sha256=TKCPGGl2hKGFg4hizjdclB8hMzLjDsVP_48-uk_pKmI,1521 +aiogram/types/message_reaction_updated.py,sha256=_-QSyiZFNlEy9s-aZp61AFq8yRUT3Kp_T1x7SDbKv34,2616 +aiogram/types/order_info.py,sha256=ECWERhAIl3kkclMOwnNN9NHGQLUtW0B6oElkLubPPr4,1516 +aiogram/types/paid_media.py,sha256=gw3vvGNuZugsvlWpqxuZs1Q81ALL9MTZ6RVP5EFMbmk,399 +aiogram/types/paid_media_info.py,sha256=vCXLSVj5f9BHeI5t60EWllCMZykOtWFaVOglXZQKzC0,1327 +aiogram/types/paid_media_photo.py,sha256=uRakDZNVUOHpvLoxMPxI0eKdfp1_x-hs1KEMvDriSEc,1130 +aiogram/types/paid_media_preview.py,sha256=9ZIG6wR-De8VPU2y5Rn77czZFOdLcW_JxKXQeYsiycw,1522 +aiogram/types/paid_media_video.py,sha256=afHhTgBEXuyms9V1FaGqJutjveZeHjESmYvav3D3_ck,1095 +aiogram/types/passport_data.py,sha256=PT4TKdMo9drK6LeK_FgGS98wE8c-kCwHkB7HcjthguQ,1318 +aiogram/types/passport_element_error.py,sha256=0MooyVK2Yoz-6MTnBDqbyiR9o-cYM5GoM6HC-p6X9jQ,1214 +aiogram/types/passport_element_error_data_field.py,sha256=NQXIJOOjXP56vbMTgKl2z9QqTs7FyHlxURO2xSOMQI0,1850 +aiogram/types/passport_element_error_file.py,sha256=tlUpJBAJFPUzHnCgd07gIS1c_HvFXFTpQWlB6Kipo_w,1619 +aiogram/types/passport_element_error_files.py,sha256=UKY3feWaWnV7E0gVs2nTys43bbYmB-C3flQ2j0DbAdg,1734 +aiogram/types/passport_element_error_front_side.py,sha256=669dn7UWwY4GnNnmaUBipHj8U22PahkJFmzLVerAGXk,1721 +aiogram/types/passport_element_error_reverse_side.py,sha256=ZVfTzKDmrZqzwcOBNuzsSwfEUip8hHCzeRk2jyiWDak,1704 +aiogram/types/passport_element_error_selfie.py,sha256=KR-TG1DguG1w9Kv1rIJRf7qkI_L7euSwr9h5IC8DAJU,1623 +aiogram/types/passport_element_error_translation_file.py,sha256=Zm4DzT7yQoHHdANCgq0uW6kmskULr56hwjv0GFPWTGI,1843 +aiogram/types/passport_element_error_translation_files.py,sha256=I_i-u15lAHxpCzhzj7Iiu8aTdbwyhQJfGeYp9p3woIs,1952 +aiogram/types/passport_element_error_unspecified.py,sha256=KqvSPstDlkcEJRDA-JkFX5JK97uO9R4Nqx_Sbp5iW4Q,1651 +aiogram/types/passport_file.py,sha256=tN7IbA6M4Zk6WH4CpVeI0exfi_UKoKOUiz1iT1e1epo,1599 +aiogram/types/photo_size.py,sha256=J1rOX1QxScCjA0LPm4KgdLZBpsAQfscAaDfuocE4cC0,1664 +aiogram/types/poll.py,sha256=dgCODf8MlNQKh74LfWuwfdOXli-N55kqwRWS3wl1pcg,3737 +aiogram/types/poll_answer.py,sha256=HZoZQ4SiytyywLPa3ACX617QJ4zy3REXG_puRmtJdww,1614 +aiogram/types/poll_option.py,sha256=KhsgOD64wZu2RCD6F6gsuT9z-5RKnOWMOFs-Cjwdnh4,1445 +aiogram/types/pre_checkout_query.py,sha256=CaYsF1zvPb1k5cgka1GC12VMS3eZc3RWVba7VmRr6L4,4410 +aiogram/types/proximity_alert_triggered.py,sha256=b2zF9r0sjf-cp6Gj-pyTIJq9x5a_JBjdp-DseDGpM_0,1253 +aiogram/types/reaction_count.py,sha256=wmMH5iR_tOJ3ieSezjBzRCPQyt7RhH3Lbw8emodaxqE,1332 +aiogram/types/reaction_type.py,sha256=EBHvWnPblOe2T6ey0_V9m6vReAX8VcHX4wuzKLVMR0w,442 +aiogram/types/reaction_type_custom_emoji.py,sha256=dzZSLhEtBke35GtTgfSxrijMu9jQzob6drdFkYReR7w,1150 +aiogram/types/reaction_type_emoji.py,sha256=F5WoRrUm9tOV3YJVNh8quD4D2OfsU53Y-mbqggbnm-w,1682 +aiogram/types/reaction_type_paid.py,sha256=zXzhLH6g8HeyIOO1dhsZwG4_Mh52Yw5sC5mucpffnTY,854 +aiogram/types/refunded_payment.py,sha256=yaj69LD-j7ffwtTk69ozl0MXz3r2kUlBTgOuWEqvxto,2180 +aiogram/types/reply_keyboard_markup.py,sha256=Ey04kT-CDRoFk4Ofqe-U6-SUi_SYaXtYQ72NqzNwgq4,3373 +aiogram/types/reply_keyboard_remove.py,sha256=vt2LTPCyoNO1SzO7JLJAUTLxfcyVh5eVKTkFmjQVvag,2093 +aiogram/types/reply_parameters.py,sha256=2DWrO4V2Vxdc42OnEuHjfLS60PaNO01rtcvlt-H4aCY,3502 +aiogram/types/response_parameters.py,sha256=qPu3C079bJZRdUIQwr-r9WIcW6yYW7rdWJlraZQbw-M,1550 +aiogram/types/revenue_withdrawal_state.py,sha256=rUzcoQ2Nbmm-2EwkoD-g_xWUp9o3mIsthyE2ZWrg0ZY,585 +aiogram/types/revenue_withdrawal_state_failed.py,sha256=uhCBqAV8SpbCkL364ygkvGg7TzarISQ6NniBeHvn3HE,1133 +aiogram/types/revenue_withdrawal_state_pending.py,sha256=rVieabsj2ayXpzN7yW8uGN-8p6Qy_lQyrKYFSKH5qmw,1115 +aiogram/types/revenue_withdrawal_state_succeeded.py,sha256=d2cBJbxXEPhtSLWb-TzyDy-iumMWkG7G6LWNRBmH7oI,1409 +aiogram/types/sent_web_app_message.py,sha256=1p2Xr_3czwPbZd8PpylTSo31ZgeAEBLnlnlRcBY31xc,1168 +aiogram/types/shared_user.py,sha256=L_PyLNJ0I75E9OykdQA5Nk5j56QjmwEgD8jPIYxFGYA,2340 +aiogram/types/shipping_address.py,sha256=9JTEnZoNaPa-T1p_YolL1ErIGWJol8lAU4F8ycsQ8ZY,1550 +aiogram/types/shipping_option.py,sha256=5jI1LADtNbe2oZC0a2G3f7Fh6J8CZ0wfCBqVFOUlqIw,1098 +aiogram/types/shipping_query.py,sha256=22pK3KfuxTTkZm-GFxrgphBmldqT4iIifVY-6vmF-qk,3458 +aiogram/types/star_transaction.py,sha256=zGrNLgJeDuv4AWfr8tiCWLHM_KgNO-d9rYiiaiUe8A8,3087 +aiogram/types/star_transactions.py,sha256=n4NDZK71RgvVbuiCAzdjKBc5p6PyezzYQFjJkiewunw,954 +aiogram/types/sticker.py,sha256=Tcz8iqKzCbfvP7MdV3NVwUEt9u27EmB7_R-N_BxSd6M,5902 +aiogram/types/sticker_set.py,sha256=OGKkpMzsQxRcuAGLt9ZJOaLwv9IKndmTaaKl5fyiNLo,2388 +aiogram/types/story.py,sha256=2Bm9ZHpfr4_yeBPWFgwnqTs-y4xFgKqW8NLRVWzMdqM,884 +aiogram/types/successful_payment.py,sha256=nNUteKAYhz_PI3EuoDkd8zX1dDal_NLMSy08fnwjC98,2574 +aiogram/types/switch_inline_query_chosen_chat.py,sha256=KH9p_x5aY6XxQn71LRa92cVQMl8glZKdc2m2935i_Yo,2002 +aiogram/types/text_quote.py,sha256=2bmMetBcRCIUu5GPlGUC8IpRLqPEAOmirvpsmzOPrrA,1863 +aiogram/types/transaction_partner.py,sha256=WtOmiGbZhHF_1vidNsULzjypaypxdHfif3nGcOwNIjg,625 +aiogram/types/transaction_partner_fragment.py,sha256=sHfiApYXz8E4Jr40pb0szs4b94aAp0UTE6UGQ1xFFdo,1962 +aiogram/types/transaction_partner_other.py,sha256=iHViDYZ62dQS3z6k1YkMOqFELyBM4wpAkGzRlif-_xw,1104 +aiogram/types/transaction_partner_telegram_ads.py,sha256=QmVjyRZUGNTpxRIFZF4F_pAPj9i4224E1PsnA9GS8YU,1185 +aiogram/types/transaction_partner_user.py,sha256=rslWGfJ7C-ptPRXACLyB3vxrbDyu1yd9LJX0pTNiLV8,1979 +aiogram/types/update.py,sha256=5FVm6IcFT8INyU3GPNVBxL0s3-g7cJpeO3vUUogzoo4,11481 +aiogram/types/user.py,sha256=DW0Xg1Lld2oB5wwOZtBIJggt-WiNLKOY-4HHSpU_t1k,6001 +aiogram/types/user_chat_boosts.py,sha256=Qpvrxc-BGYuyKbC8kLIrmQqNpfYi3jXXYY_234NWb0M,946 +aiogram/types/user_profile_photos.py,sha256=VKpZMznwuIUQ4sWxjDgNv3tSr6AW2fwG4AIwgztwL-w,1124 +aiogram/types/user_shared.py,sha256=1yGKAO67fshHSOCtVl3dO_oD1-VOyzPBC4Ak-hflMOQ,1534 +aiogram/types/users_shared.py,sha256=Fdjww27YYlWMVzYOhpBp54RL_N_Zh7_meWgpqBxfkjQ,1986 +aiogram/types/venue.py,sha256=wEmGfGAiqdhDhTskRoxOKiNVliUaPpPOxBmohfDlL5I,2147 +aiogram/types/video.py,sha256=e-uI5iQSKAdhPK-vVz5kiQCIV22kaxmylzN8gzmtwnk,2575 +aiogram/types/video_chat_ended.py,sha256=eL3ZSR0WfVcHEEpXrdLm1mvuogXS7RAoxLwX2AwMdeg,839 +aiogram/types/video_chat_participants_invited.py,sha256=zV4sR4Mi_BmHeS60I4C-KzrAhOAh2weIFuEE8CmhmZI,943 +aiogram/types/video_chat_scheduled.py,sha256=G-a24czeK7NVzJ88SKFNutPd_SGnRgTBLy85rHozNLo,990 +aiogram/types/video_chat_started.py,sha256=FYHVcH-a5knoXIYMmCQThFt8hjjPwAiZ8QvGLNVWgl4,309 +aiogram/types/video_note.py,sha256=Hwa8uTCnyb9yT9eGikFwyVfk6X779md3DNAPbav6VrM,2059 +aiogram/types/voice.py,sha256=AMyEJovxyDl2TRVpEfpHLMSmsXNjXIrNDH73HxQUxqg,1932 +aiogram/types/web_app_data.py,sha256=CzkuU2VwVYQ7WBkFA6Zh8BL-qUKQeB__mcmhmVZnT2A,1107 +aiogram/types/web_app_info.py,sha256=aPH4uLFFLKNLEF3RUm3uYCkg9Hk545kMoUvrkg4TUds,931 +aiogram/types/webhook_info.py,sha256=TAfcO66tpfH5XolOI90pg_sHowUkV4hHjzp3tWhpj_w,2992 +aiogram/types/write_access_allowed.py,sha256=3GiPknn_fKHAJ53FROE4AK4MtpwluNlAuZvFuOP6diA,1912 +aiogram/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/utils/__pycache__/__init__.cpython-311.pyc,, +aiogram/utils/__pycache__/auth_widget.cpython-311.pyc,, +aiogram/utils/__pycache__/backoff.cpython-311.pyc,, +aiogram/utils/__pycache__/callback_answer.cpython-311.pyc,, +aiogram/utils/__pycache__/chat_action.cpython-311.pyc,, +aiogram/utils/__pycache__/chat_member.cpython-311.pyc,, +aiogram/utils/__pycache__/deep_linking.cpython-311.pyc,, +aiogram/utils/__pycache__/formatting.cpython-311.pyc,, +aiogram/utils/__pycache__/keyboard.cpython-311.pyc,, +aiogram/utils/__pycache__/link.cpython-311.pyc,, +aiogram/utils/__pycache__/magic_filter.cpython-311.pyc,, +aiogram/utils/__pycache__/markdown.cpython-311.pyc,, +aiogram/utils/__pycache__/media_group.cpython-311.pyc,, +aiogram/utils/__pycache__/mixins.cpython-311.pyc,, +aiogram/utils/__pycache__/mypy_hacks.cpython-311.pyc,, +aiogram/utils/__pycache__/payload.cpython-311.pyc,, +aiogram/utils/__pycache__/serialization.cpython-311.pyc,, +aiogram/utils/__pycache__/text_decorations.cpython-311.pyc,, +aiogram/utils/__pycache__/token.cpython-311.pyc,, +aiogram/utils/__pycache__/warnings.cpython-311.pyc,, +aiogram/utils/__pycache__/web_app.cpython-311.pyc,, +aiogram/utils/auth_widget.py,sha256=kcNMXu7hA4kWHw_PeZsGFaeC0m0Sbtbd2-8Q9rWfkHg,981 +aiogram/utils/backoff.py,sha256=D_d7z94PyR5USzeoIednnCgW07qQgwQNgVdPGkgrmJM,2123 +aiogram/utils/callback_answer.py,sha256=_NHsLMjfZBKOXtyCSHBh4s9V3go-U8Wsk5JqpMh-O4c,6573 +aiogram/utils/chat_action.py,sha256=3GW2mDqQQ5fv6LMpeqB0j-J1d1blml2aF4q7vqlnMBQ,12201 +aiogram/utils/chat_member.py,sha256=WwMEi__6DYeF55TFuLxPS-OQaDdTa0I2f-yJkt3Dio0,942 +aiogram/utils/deep_linking.py,sha256=D89nv29pnL63_N_E_ZfLjiarTQZhg0oq6RnRdWRDSTE,2980 +aiogram/utils/formatting.py,sha256=7je7KplskUsRgo4DFVWwnN0g4C8JMBYC4tTVxw-3zr4,16902 +aiogram/utils/i18n/__init__.py,sha256=mwTwSL1cuXYi3a3LBICqoH66y4kHVML24YNPbGlZ55M,440 +aiogram/utils/i18n/__pycache__/__init__.cpython-311.pyc,, +aiogram/utils/i18n/__pycache__/context.cpython-311.pyc,, +aiogram/utils/i18n/__pycache__/core.cpython-311.pyc,, +aiogram/utils/i18n/__pycache__/lazy_proxy.cpython-311.pyc,, +aiogram/utils/i18n/__pycache__/middleware.cpython-311.pyc,, +aiogram/utils/i18n/context.py,sha256=fhLzDZvxqRMvPu2-lEUrH7n09oHl-H0qo2mLFyKzCJk,549 +aiogram/utils/i18n/core.py,sha256=XX_iuwylDTfrfCrafnqiFq28LDr-bvoO4Qnkhy81d_M,3542 +aiogram/utils/i18n/lazy_proxy.py,sha256=0yHtyrejG9wG4yzLl1cDEsFomww2nyR7KFSbFyp7_NA,472 +aiogram/utils/i18n/middleware.py,sha256=lqeui9-x7ztMQPI0IeQeRawe6orMjpsg2EtvXTzAQj4,5874 +aiogram/utils/keyboard.py,sha256=zxXdpmRr5x-4kaczAGWvlElMoWzRKF5PvDyxSJ9_4HY,13234 +aiogram/utils/link.py,sha256=z7Zp5uk5z3iNO26-wZrhoCDNLt1N0KjbPYhthOq-50o,2261 +aiogram/utils/magic_filter.py,sha256=WGHOC9k2acxrcpkFF-ViQv3LbzRAKtJj5MRv7IEi75c,666 +aiogram/utils/markdown.py,sha256=3T1UVSzaAwnYnTNNq6pklq-TTs6Y6zINp-LIWgwrAyU,4481 +aiogram/utils/media_group.py,sha256=E28oJhPoTQ4iKXr0QUx5W1nd7VPHAJf0PQz0MeqG46E,14804 +aiogram/utils/mixins.py,sha256=ox0Q6BlxcyTfAtzLVMEY9eUfXXhnXtkkLBQlUQ6uL4o,2923 +aiogram/utils/mypy_hacks.py,sha256=cm5_tBzfrkG5OOIs2m5U4JfQKohj1KkmCRXNLTJFDy0,433 +aiogram/utils/payload.py,sha256=mGJdQryRHL07VbSjdzGbN1NbYzd_mN2MGY1RiY3_KX4,2942 +aiogram/utils/serialization.py,sha256=SMiqv2TQed_GOhvhWoaABFM65jjIiXqBJTRRdMQ9nXY,2765 +aiogram/utils/text_decorations.py,sha256=tJwFV-zefED_z70wQsGWXIhD85m8Ee12mk3VrWN8Koo,8248 +aiogram/utils/token.py,sha256=iFfmK-pHGyPsF4ekWWcOlfH4OR9xGNAyCIavND8Ykrc,936 +aiogram/utils/warnings.py,sha256=xGsQcxrMXtdZfLOGRCqKRIJbw80DA39COcctikBfYAE,89 +aiogram/utils/web_app.py,sha256=pYFAohjk8OW3qRQkJebMtKaFJ7vOL4OJivUEh171kkI,7105 +aiogram/webhook/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiogram/webhook/__pycache__/__init__.cpython-311.pyc,, +aiogram/webhook/__pycache__/aiohttp_server.cpython-311.pyc,, +aiogram/webhook/__pycache__/security.cpython-311.pyc,, +aiogram/webhook/aiohttp_server.py,sha256=3uto1_vwf6h73SXFNSoDxGt49gFHFYDI1wf4uRcxWUg,10454 +aiogram/webhook/security.py,sha256=ifd2TrPSOlXfutYyAmRh0LT3hJkB4o79XmEV1lo6fv0,1350 diff --git a/env/Lib/site-packages/aiogram-3.12.0.dist-info/REQUESTED b/env/Lib/site-packages/aiogram-3.12.0.dist-info/REQUESTED new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram-3.12.0.dist-info/WHEEL b/env/Lib/site-packages/aiogram-3.12.0.dist-info/WHEEL new file mode 100644 index 0000000..cdd68a4 --- /dev/null +++ b/env/Lib/site-packages/aiogram-3.12.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.25.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/env/Lib/site-packages/aiogram-3.12.0.dist-info/licenses/LICENSE b/env/Lib/site-packages/aiogram-3.12.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000..caa060c --- /dev/null +++ b/env/Lib/site-packages/aiogram-3.12.0.dist-info/licenses/LICENSE @@ -0,0 +1,18 @@ +Copyright (c) 2017 - present Alex Root Junior + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/env/Lib/site-packages/aiogram/__init__.py b/env/Lib/site-packages/aiogram/__init__.py new file mode 100644 index 0000000..1fbee0e --- /dev/null +++ b/env/Lib/site-packages/aiogram/__init__.py @@ -0,0 +1,41 @@ +import asyncio as _asyncio +from contextlib import suppress + +from aiogram.dispatcher.flags import FlagGenerator + +from . import enums, methods, types +from .__meta__ import __api_version__, __version__ +from .client import session +from .client.bot import Bot +from .dispatcher.dispatcher import Dispatcher +from .dispatcher.middlewares.base import BaseMiddleware +from .dispatcher.router import Router +from .utils.magic_filter import MagicFilter +from .utils.text_decorations import html_decoration as html +from .utils.text_decorations import markdown_decoration as md + +with suppress(ImportError): + import uvloop as _uvloop + + _asyncio.set_event_loop_policy(_uvloop.EventLoopPolicy()) + + +F = MagicFilter() +flags = FlagGenerator() + +__all__ = ( + "__api_version__", + "__version__", + "types", + "methods", + "enums", + "Bot", + "session", + "Dispatcher", + "Router", + "BaseMiddleware", + "F", + "html", + "md", + "flags", +) diff --git a/env/Lib/site-packages/aiogram/__meta__.py b/env/Lib/site-packages/aiogram/__meta__.py new file mode 100644 index 0000000..c36e738 --- /dev/null +++ b/env/Lib/site-packages/aiogram/__meta__.py @@ -0,0 +1,2 @@ +__version__ = "3.12.0" +__api_version__ = "7.9" diff --git a/env/Lib/site-packages/aiogram/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..84bce6d Binary files /dev/null and b/env/Lib/site-packages/aiogram/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/__pycache__/__meta__.cpython-311.pyc b/env/Lib/site-packages/aiogram/__pycache__/__meta__.cpython-311.pyc new file mode 100644 index 0000000..d1b1a9c Binary files /dev/null and b/env/Lib/site-packages/aiogram/__pycache__/__meta__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/__pycache__/exceptions.cpython-311.pyc b/env/Lib/site-packages/aiogram/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000..328a5d3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/__pycache__/exceptions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/__pycache__/loggers.cpython-311.pyc b/env/Lib/site-packages/aiogram/__pycache__/loggers.cpython-311.pyc new file mode 100644 index 0000000..ba3d0c1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/__pycache__/loggers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/__init__.py b/env/Lib/site-packages/aiogram/client/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/client/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..0f57daf Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/__pycache__/bot.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/__pycache__/bot.cpython-311.pyc new file mode 100644 index 0000000..4ee2c62 Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/__pycache__/bot.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/__pycache__/context_controller.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/__pycache__/context_controller.cpython-311.pyc new file mode 100644 index 0000000..d74dc5d Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/__pycache__/context_controller.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/__pycache__/default.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/__pycache__/default.cpython-311.pyc new file mode 100644 index 0000000..685d80f Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/__pycache__/default.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/__pycache__/telegram.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/__pycache__/telegram.cpython-311.pyc new file mode 100644 index 0000000..8f13551 Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/__pycache__/telegram.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/bot.py b/env/Lib/site-packages/aiogram/client/bot.py new file mode 100644 index 0000000..397e1a1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/bot.py @@ -0,0 +1,4761 @@ +from __future__ import annotations + +import datetime +import io +import pathlib +from contextlib import asynccontextmanager +from types import TracebackType +from typing import ( + Any, + AsyncGenerator, + AsyncIterator, + BinaryIO, + List, + Optional, + Type, + TypeVar, + Union, + cast, +) + +import aiofiles + +from aiogram.utils.token import extract_bot_id, validate_token + +from ..methods import ( + AddStickerToSet, + AnswerCallbackQuery, + AnswerInlineQuery, + AnswerPreCheckoutQuery, + AnswerShippingQuery, + AnswerWebAppQuery, + ApproveChatJoinRequest, + BanChatMember, + BanChatSenderChat, + Close, + CloseForumTopic, + CloseGeneralForumTopic, + CopyMessage, + CopyMessages, + CreateChatInviteLink, + CreateChatSubscriptionInviteLink, + CreateForumTopic, + CreateInvoiceLink, + CreateNewStickerSet, + DeclineChatJoinRequest, + DeleteChatPhoto, + DeleteChatStickerSet, + DeleteForumTopic, + DeleteMessage, + DeleteMessages, + DeleteMyCommands, + DeleteStickerFromSet, + DeleteStickerSet, + DeleteWebhook, + EditChatInviteLink, + EditChatSubscriptionInviteLink, + EditForumTopic, + EditGeneralForumTopic, + EditMessageCaption, + EditMessageLiveLocation, + EditMessageMedia, + EditMessageReplyMarkup, + EditMessageText, + ExportChatInviteLink, + ForwardMessage, + ForwardMessages, + GetBusinessConnection, + GetChat, + GetChatAdministrators, + GetChatMember, + GetChatMemberCount, + GetChatMenuButton, + GetCustomEmojiStickers, + GetFile, + GetForumTopicIconStickers, + GetGameHighScores, + GetMe, + GetMyCommands, + GetMyDefaultAdministratorRights, + GetMyDescription, + GetMyName, + GetMyShortDescription, + GetStarTransactions, + GetStickerSet, + GetUpdates, + GetUserChatBoosts, + GetUserProfilePhotos, + GetWebhookInfo, + HideGeneralForumTopic, + LeaveChat, + LogOut, + PinChatMessage, + PromoteChatMember, + RefundStarPayment, + ReopenForumTopic, + ReopenGeneralForumTopic, + ReplaceStickerInSet, + RestrictChatMember, + RevokeChatInviteLink, + SendAnimation, + SendAudio, + SendChatAction, + SendContact, + SendDice, + SendDocument, + SendGame, + SendInvoice, + SendLocation, + SendMediaGroup, + SendMessage, + SendPaidMedia, + SendPhoto, + SendPoll, + SendSticker, + SendVenue, + SendVideo, + SendVideoNote, + SendVoice, + SetChatAdministratorCustomTitle, + SetChatDescription, + SetChatMenuButton, + SetChatPermissions, + SetChatPhoto, + SetChatStickerSet, + SetChatTitle, + SetCustomEmojiStickerSetThumbnail, + SetGameScore, + SetMessageReaction, + SetMyCommands, + SetMyDefaultAdministratorRights, + SetMyDescription, + SetMyName, + SetMyShortDescription, + SetPassportDataErrors, + SetStickerEmojiList, + SetStickerKeywords, + SetStickerMaskPosition, + SetStickerPositionInSet, + SetStickerSetThumbnail, + SetStickerSetTitle, + SetWebhook, + StopMessageLiveLocation, + StopPoll, + TelegramMethod, + UnbanChatMember, + UnbanChatSenderChat, + UnhideGeneralForumTopic, + UnpinAllChatMessages, + UnpinAllForumTopicMessages, + UnpinAllGeneralForumTopicMessages, + UnpinChatMessage, + UploadStickerFile, +) +from ..types import ( + BotCommand, + BotCommandScopeAllChatAdministrators, + BotCommandScopeAllGroupChats, + BotCommandScopeAllPrivateChats, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + BotCommandScopeDefault, + BotDescription, + BotName, + BotShortDescription, + BusinessConnection, + ChatAdministratorRights, + ChatFullInfo, + ChatInviteLink, + ChatMemberAdministrator, + ChatMemberBanned, + ChatMemberLeft, + ChatMemberMember, + ChatMemberOwner, + ChatMemberRestricted, + ChatPermissions, + Downloadable, + File, + ForceReply, + ForumTopic, + GameHighScore, + InlineKeyboardMarkup, + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultContact, + InlineQueryResultDocument, + InlineQueryResultGame, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultsButton, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + InputFile, + InputMediaAnimation, + InputMediaAudio, + InputMediaDocument, + InputMediaPhoto, + InputMediaVideo, + InputPaidMediaPhoto, + InputPaidMediaVideo, + InputPollOption, + InputSticker, + LabeledPrice, + LinkPreviewOptions, + MaskPosition, + MenuButtonCommands, + MenuButtonDefault, + MenuButtonWebApp, + Message, + MessageEntity, + MessageId, + PassportElementErrorDataField, + PassportElementErrorFile, + PassportElementErrorFiles, + PassportElementErrorFrontSide, + PassportElementErrorReverseSide, + PassportElementErrorSelfie, + PassportElementErrorTranslationFile, + PassportElementErrorTranslationFiles, + PassportElementErrorUnspecified, + Poll, + ReactionTypeCustomEmoji, + ReactionTypeEmoji, + ReactionTypePaid, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, + SentWebAppMessage, + ShippingOption, + StarTransactions, + Sticker, + StickerSet, + Update, + User, + UserChatBoosts, + UserProfilePhotos, + WebhookInfo, +) +from .default import Default, DefaultBotProperties +from .session.aiohttp import AiohttpSession +from .session.base import BaseSession + +T = TypeVar("T") + + +class Bot: + def __init__( + self, + token: str, + session: Optional[BaseSession] = None, + default: Optional[DefaultBotProperties] = None, + **kwargs: Any, + ) -> None: + """ + Bot class + + :param token: Telegram Bot token `Obtained from @BotFather `_ + :param session: HTTP Client session (For example AiohttpSession). + If not specified it will be automatically created. + :param default: Default bot properties. + If specified it will be propagated into the API methods at runtime. + :raise TokenValidationError: When token has invalid format this exception will be raised + """ + + validate_token(token) + + if session is None: + session = AiohttpSession() + if default is None: + default = DefaultBotProperties() + + self.session = session + + # Few arguments are completely removed in 3.7.0 version + # Temporary solution to raise an error if user passed these arguments + # with explanation how to fix it + parse_mode = kwargs.get("parse_mode", None) + link_preview_is_disabled = kwargs.get("disable_web_page_preview", None) + protect_content = kwargs.get("protect_content", None) + if ( + parse_mode is not None + or link_preview_is_disabled is not None + or protect_content is not None + ): + example_kwargs = { + "parse_mode": parse_mode, + "link_preview_is_disabled": link_preview_is_disabled, + "protect_content": protect_content, + } + replacement_spec = ", ".join( + f"{k}={v!r}" for k, v in example_kwargs.items() if v is not None + ) + raise TypeError( + "Passing `parse_mode`, `disable_web_page_preview` or `protect_content` " + "to Bot initializer is not supported anymore. These arguments have been removed " + f"in 3.7.0 version. Use `default=DefaultBotProperties({replacement_spec})` argument instead." + ) + + self.default = default + + self.__token = token + self._me: Optional[User] = None + + async def __aenter__(self) -> "Bot": + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + await self.session.close() + + @property + def token(self) -> str: + return self.__token + + @property + def id(self) -> int: + """ + Get bot ID from token + + :return: + """ + return extract_bot_id(self.__token) + + @asynccontextmanager + async def context(self, auto_close: bool = True) -> AsyncIterator[Bot]: + """ + Generate bot context + + :param auto_close: close session on exit + :return: + """ + try: + yield self + finally: + if auto_close: + await self.session.close() + + async def me(self) -> User: + """ + Cached alias for getMe method + + :return: + """ + if self._me is None: # pragma: no cover + self._me = await self.get_me() + return self._me + + @classmethod + async def __download_file_binary_io( + cls, destination: BinaryIO, seek: bool, stream: AsyncGenerator[bytes, None] + ) -> BinaryIO: + async for chunk in stream: + destination.write(chunk) + destination.flush() + if seek is True: + destination.seek(0) + return destination + + @classmethod + async def __download_file( + cls, destination: Union[str, pathlib.Path], stream: AsyncGenerator[bytes, None] + ) -> None: + async with aiofiles.open(destination, "wb") as f: + async for chunk in stream: + await f.write(chunk) + + @classmethod + async def __aiofiles_reader( + cls, file: str, chunk_size: int = 65536 + ) -> AsyncGenerator[bytes, None]: + async with aiofiles.open(file, "rb") as f: + while chunk := await f.read(chunk_size): + yield chunk + + async def download_file( + self, + file_path: str, + destination: Optional[Union[BinaryIO, pathlib.Path, str]] = None, + timeout: int = 30, + chunk_size: int = 65536, + seek: bool = True, + ) -> Optional[BinaryIO]: + """ + Download file by file_path to destination. + + If you want to automatically create destination (:class:`io.BytesIO`) use default + value of destination and handle result of this method. + + :param file_path: File path on Telegram server (You can get it from :obj:`aiogram.types.File`) + :param destination: Filename, file path or instance of :class:`io.IOBase`. For e.g. :class:`io.BytesIO`, defaults to None + :param timeout: Total timeout in seconds, defaults to 30 + :param chunk_size: File chunks size, defaults to 64 kb + :param seek: Go to start of file when downloading is finished. Used only for destination with :class:`typing.BinaryIO` type, defaults to True + """ + if destination is None: + destination = io.BytesIO() + + close_stream = False + if self.session.api.is_local: + stream = self.__aiofiles_reader( + str(self.session.api.wrap_local_file.to_local(file_path)), chunk_size=chunk_size + ) + close_stream = True + else: + url = self.session.api.file_url(self.__token, file_path) + stream = self.session.stream_content( + url=url, + timeout=timeout, + chunk_size=chunk_size, + raise_for_status=True, + ) + + try: + if isinstance(destination, (str, pathlib.Path)): + await self.__download_file(destination=destination, stream=stream) + return None + return await self.__download_file_binary_io( + destination=destination, seek=seek, stream=stream + ) + finally: + if close_stream: + await stream.aclose() + + async def download( + self, + file: Union[str, Downloadable], + destination: Optional[Union[BinaryIO, pathlib.Path, str]] = None, + timeout: int = 30, + chunk_size: int = 65536, + seek: bool = True, + ) -> Optional[BinaryIO]: + """ + Download file by file_id or Downloadable object to destination. + + If you want to automatically create destination (:class:`io.BytesIO`) use default + value of destination and handle result of this method. + + :param file: file_id or Downloadable object + :param destination: Filename, file path or instance of :class:`io.IOBase`. For e.g. :class:`io.BytesIO`, defaults to None + :param timeout: Total timeout in seconds, defaults to 30 + :param chunk_size: File chunks size, defaults to 64 kb + :param seek: Go to start of file when downloading is finished. Used only for destination with :class:`typing.BinaryIO` type, defaults to True + """ + if isinstance(file, str): + file_id = file + else: + # type is ignored in due to: + # Incompatible types in assignment (expression has type "Optional[Any]", variable has type "str") + file_id = getattr(file, "file_id", None) # type: ignore + if file_id is None: + raise TypeError("file can only be of the string or Downloadable type") + + file_ = await self.get_file(file_id) + + # `file_path` can be None for large files but this files can't be downloaded + # So we need to do type-cast + # https://github.com/aiogram/aiogram/pull/282/files#r394110017 + file_path = cast(str, file_.file_path) + + return await self.download_file( + file_path, destination=destination, timeout=timeout, chunk_size=chunk_size, seek=seek + ) + + async def __call__( + self, method: TelegramMethod[T], request_timeout: Optional[int] = None + ) -> T: + """ + Call API method + + :param method: + :return: + """ + return await self.session(self, method, timeout=request_timeout) + + def __hash__(self) -> int: + """ + Get hash for the token + + :return: + """ + return hash(self.__token) + + def __eq__(self, other: Any) -> bool: + """ + Compare current bot with another bot instance + + :param other: + :return: + """ + if not isinstance(other, Bot): + return False + return hash(self) == hash(other) + + async def add_sticker_to_set( + self, + user_id: int, + name: str, + sticker: InputSticker, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#addstickertoset + + :param user_id: User identifier of sticker set owner + :param name: Sticker set name + :param sticker: A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = AddStickerToSet( + user_id=user_id, + name=name, + sticker=sticker, + ) + return await self(call, request_timeout=request_timeout) + + async def answer_callback_query( + self, + callback_query_id: str, + text: Optional[str] = None, + show_alert: Optional[bool] = None, + url: Optional[str] = None, + cache_time: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to send answers to callback queries sent from `inline keyboards `_. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, :code:`True` is returned. + + Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via `@BotFather `_ and accept the terms. Otherwise, you may use links like :code:`t.me/your_bot?start=XXXX` that open your bot with a parameter. + + Source: https://core.telegram.org/bots/api#answercallbackquery + + :param callback_query_id: Unique identifier for the query to be answered + :param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters + :param show_alert: If :code:`True`, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to *false*. + :param url: URL that will be opened by the user's client. If you have created a :class:`aiogram.types.game.Game` and accepted the conditions via `@BotFather `_, specify the URL that opens your game - note that this will only work if the query comes from a `https://core.telegram.org/bots/api#inlinekeyboardbutton `_ *callback_game* button. + :param cache_time: The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. + :param request_timeout: Request timeout + :return: Otherwise, you may use links like :code:`t.me/your_bot?start=XXXX` that open your bot with a parameter. + """ + + call = AnswerCallbackQuery( + callback_query_id=callback_query_id, + text=text, + show_alert=show_alert, + url=url, + cache_time=cache_time, + ) + return await self(call, request_timeout=request_timeout) + + async def answer_inline_query( + self, + inline_query_id: str, + results: List[ + Union[ + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultContact, + InlineQueryResultGame, + InlineQueryResultDocument, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + ] + ], + cache_time: Optional[int] = None, + is_personal: Optional[bool] = None, + next_offset: Optional[str] = None, + button: Optional[InlineQueryResultsButton] = None, + switch_pm_parameter: Optional[str] = None, + switch_pm_text: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to send answers to an inline query. On success, :code:`True` is returned. + + No more than **50** results per query are allowed. + + Source: https://core.telegram.org/bots/api#answerinlinequery + + :param inline_query_id: Unique identifier for the answered query + :param results: A JSON-serialized array of results for the inline query + :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. + :param is_personal: Pass :code:`True` if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. + :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. + :param button: A JSON-serialized object describing a button to be shown above inline query results + :param switch_pm_parameter: `Deep-linking `_ parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only :code:`A-Z`, :code:`a-z`, :code:`0-9`, :code:`_` and :code:`-` are allowed. + :param switch_pm_text: If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter *switch_pm_parameter* + :param request_timeout: Request timeout + :return: On success, :code:`True` is returned. + """ + + call = AnswerInlineQuery( + inline_query_id=inline_query_id, + results=results, + cache_time=cache_time, + is_personal=is_personal, + next_offset=next_offset, + button=button, + switch_pm_parameter=switch_pm_parameter, + switch_pm_text=switch_pm_text, + ) + return await self(call, request_timeout=request_timeout) + + async def answer_pre_checkout_query( + self, + pre_checkout_query_id: str, + ok: bool, + error_message: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an :class:`aiogram.types.update.Update` with the field *pre_checkout_query*. Use this method to respond to such pre-checkout queries. On success, :code:`True` is returned. **Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. + + Source: https://core.telegram.org/bots/api#answerprecheckoutquery + + :param pre_checkout_query_id: Unique identifier for the query to be answered + :param ok: Specify :code:`True` if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use :code:`False` if there are any problems. + :param error_message: Required if *ok* is :code:`False`. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. + :param request_timeout: Request timeout + :return: **Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. + """ + + call = AnswerPreCheckoutQuery( + pre_checkout_query_id=pre_checkout_query_id, + ok=ok, + error_message=error_message, + ) + return await self(call, request_timeout=request_timeout) + + async def answer_shipping_query( + self, + shipping_query_id: str, + ok: bool, + shipping_options: Optional[List[ShippingOption]] = None, + error_message: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + If you sent an invoice requesting a shipping address and the parameter *is_flexible* was specified, the Bot API will send an :class:`aiogram.types.update.Update` with a *shipping_query* field to the bot. Use this method to reply to shipping queries. On success, :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#answershippingquery + + :param shipping_query_id: Unique identifier for the query to be answered + :param ok: Pass :code:`True` if delivery to the specified address is possible and :code:`False` if there are any problems (for example, if delivery to the specified address is not possible) + :param shipping_options: Required if *ok* is :code:`True`. A JSON-serialized array of available shipping options. + :param error_message: Required if *ok* is :code:`False`. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. + :param request_timeout: Request timeout + :return: On success, :code:`True` is returned. + """ + + call = AnswerShippingQuery( + shipping_query_id=shipping_query_id, + ok=ok, + shipping_options=shipping_options, + error_message=error_message, + ) + return await self(call, request_timeout=request_timeout) + + async def answer_web_app_query( + self, + web_app_query_id: str, + result: Union[ + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultContact, + InlineQueryResultGame, + InlineQueryResultDocument, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + ], + request_timeout: Optional[int] = None, + ) -> SentWebAppMessage: + """ + Use this method to set the result of an interaction with a `Web App `_ and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a :class:`aiogram.types.sent_web_app_message.SentWebAppMessage` object is returned. + + Source: https://core.telegram.org/bots/api#answerwebappquery + + :param web_app_query_id: Unique identifier for the query to be answered + :param result: A JSON-serialized object describing the message to be sent + :param request_timeout: Request timeout + :return: On success, a :class:`aiogram.types.sent_web_app_message.SentWebAppMessage` object is returned. + """ + + call = AnswerWebAppQuery( + web_app_query_id=web_app_query_id, + result=result, + ) + return await self(call, request_timeout=request_timeout) + + async def approve_chat_join_request( + self, + chat_id: Union[int, str], + user_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the *can_invite_users* administrator right. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#approvechatjoinrequest + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param user_id: Unique identifier of the target user + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = ApproveChatJoinRequest( + chat_id=chat_id, + user_id=user_id, + ) + return await self(call, request_timeout=request_timeout) + + async def ban_chat_member( + self, + chat_id: Union[int, str], + user_id: int, + until_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + revoke_messages: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless `unbanned `_ first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#banchatmember + + :param chat_id: Unique identifier for the target group or username of the target supergroup or channel (in the format :code:`@channelusername`) + :param user_id: Unique identifier of the target user + :param until_date: Date when the user will be unbanned; Unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only. + :param revoke_messages: Pass :code:`True` to delete all messages from the chat for the user that is being removed. If :code:`False`, the user will be able to see messages in the group that were sent before the user was removed. Always :code:`True` for supergroups and channels. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = BanChatMember( + chat_id=chat_id, + user_id=user_id, + until_date=until_date, + revoke_messages=revoke_messages, + ) + return await self(call, request_timeout=request_timeout) + + async def ban_chat_sender_chat( + self, + chat_id: Union[int, str], + sender_chat_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to ban a channel chat in a supergroup or a channel. Until the chat is `unbanned `_, the owner of the banned chat won't be able to send messages on behalf of **any of their channels**. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#banchatsenderchat + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param sender_chat_id: Unique identifier of the target sender chat + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = BanChatSenderChat( + chat_id=chat_id, + sender_chat_id=sender_chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def close( + self, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns :code:`True` on success. Requires no parameters. + + Source: https://core.telegram.org/bots/api#close + + :param request_timeout: Request timeout + :return: Requires no parameters. + """ + + call = Close() + return await self(call, request_timeout=request_timeout) + + async def close_forum_topic( + self, + chat_id: Union[int, str], + message_thread_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#closeforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param message_thread_id: Unique identifier for the target message thread of the forum topic + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = CloseForumTopic( + chat_id=chat_id, + message_thread_id=message_thread_id, + ) + return await self(call, request_timeout=request_timeout) + + async def copy_message( + self, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_id: int, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> MessageId: + """ + Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz :class:`aiogram.methods.poll.Poll` can be copied only if the value of the field *correct_option_id* is known to the bot. The method is analogous to the method :class:`aiogram.methods.forward_message.ForwardMessage`, but the copied message doesn't have a link to the original message. Returns the :class:`aiogram.types.message_id.MessageId` of the sent message on success. + + Source: https://core.telegram.org/bots/api#copymessage + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param from_chat_id: Unique identifier for the chat where the original message was sent (or channel username in the format :code:`@channelusername`) + :param message_id: Message identifier in the chat specified in *from_chat_id* + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept + :param parse_mode: Mode for parsing entities in the new caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media. Ignored if a new caption isn't specified. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: Returns the :class:`aiogram.types.message_id.MessageId` of the sent message on success. + """ + + call = CopyMessage( + chat_id=chat_id, + from_chat_id=from_chat_id, + message_id=message_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + disable_notification=disable_notification, + protect_content=protect_content, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def create_chat_invite_link( + self, + chat_id: Union[int, str], + name: Optional[str] = None, + expire_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + member_limit: Optional[int] = None, + creates_join_request: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> ChatInviteLink: + """ + Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method :class:`aiogram.methods.revoke_chat_invite_link.RevokeChatInviteLink`. Returns the new invite link as :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#createchatinvitelink + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param name: Invite link name; 0-32 characters + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + :param creates_join_request: :code:`True`, if users joining the chat via the link need to be approved by chat administrators. If :code:`True`, *member_limit* can't be specified + :param request_timeout: Request timeout + :return: Returns the new invite link as :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + """ + + call = CreateChatInviteLink( + chat_id=chat_id, + name=name, + expire_date=expire_date, + member_limit=member_limit, + creates_join_request=creates_join_request, + ) + return await self(call, request_timeout=request_timeout) + + async def create_forum_topic( + self, + chat_id: Union[int, str], + name: str, + icon_color: Optional[int] = None, + icon_custom_emoji_id: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> ForumTopic: + """ + Use this method to create a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns information about the created topic as a :class:`aiogram.types.forum_topic.ForumTopic` object. + + Source: https://core.telegram.org/bots/api#createforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param name: Topic name, 1-128 characters + :param icon_color: Color of the topic icon in RGB format. Currently, must be one of 7322096 (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2), or 16478047 (0xFB6F5F) + :param icon_custom_emoji_id: Unique identifier of the custom emoji shown as the topic icon. Use :class:`aiogram.methods.get_forum_topic_icon_stickers.GetForumTopicIconStickers` to get all allowed custom emoji identifiers. + :param request_timeout: Request timeout + :return: Returns information about the created topic as a :class:`aiogram.types.forum_topic.ForumTopic` object. + """ + + call = CreateForumTopic( + chat_id=chat_id, + name=name, + icon_color=icon_color, + icon_custom_emoji_id=icon_custom_emoji_id, + ) + return await self(call, request_timeout=request_timeout) + + async def create_invoice_link( + self, + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> str: + """ + Use this method to create a link for an invoice. Returns the created invoice link as *String* on success. + + Source: https://core.telegram.org/bots/api#createinvoicelink + + :param title: Product name, 1-32 characters + :param description: Product description, 1-255 characters + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param currency: Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_. + :param prices: Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_. + :param provider_token: Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_. + :param max_tip_amount: The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_. + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*. + :param provider_data: JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. + :param photo_size: Photo size in bytes + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_phone_number: Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_email: Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_shipping_address: Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_. + :param send_phone_number_to_provider: Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param send_email_to_provider: Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param is_flexible: Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_. + :param request_timeout: Request timeout + :return: Returns the created invoice link as *String* on success. + """ + + call = CreateInvoiceLink( + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + ) + return await self(call, request_timeout=request_timeout) + + async def create_new_sticker_set( + self, + user_id: int, + name: str, + title: str, + stickers: List[InputSticker], + sticker_type: Optional[str] = None, + needs_repainting: Optional[bool] = None, + sticker_format: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#createnewstickerset + + :param user_id: User identifier of created sticker set owner + :param name: Short name of sticker set, to be used in :code:`t.me/addstickers/` URLs (e.g., *animals*). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in :code:`"_by_"`. :code:`` is case insensitive. 1-64 characters. + :param title: Sticker set title, 1-64 characters + :param stickers: A JSON-serialized list of 1-50 initial stickers to be added to the sticker set + :param sticker_type: Type of stickers in the set, pass 'regular', 'mask', or 'custom_emoji'. By default, a regular sticker set is created. + :param needs_repainting: Pass :code:`True` if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only + :param sticker_format: Format of stickers in the set, must be one of 'static', 'animated', 'video' + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = CreateNewStickerSet( + user_id=user_id, + name=name, + title=title, + stickers=stickers, + sticker_type=sticker_type, + needs_repainting=needs_repainting, + sticker_format=sticker_format, + ) + return await self(call, request_timeout=request_timeout) + + async def decline_chat_join_request( + self, + chat_id: Union[int, str], + user_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the *can_invite_users* administrator right. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#declinechatjoinrequest + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param user_id: Unique identifier of the target user + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeclineChatJoinRequest( + chat_id=chat_id, + user_id=user_id, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_chat_photo( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletechatphoto + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeleteChatPhoto( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_chat_sticker_set( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field *can_set_sticker_set* optionally returned in :class:`aiogram.methods.get_chat.GetChat` requests to check if the bot can use this method. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletechatstickerset + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeleteChatStickerSet( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_forum_topic( + self, + chat_id: Union[int, str], + message_thread_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to delete a forum topic along with all its messages in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_delete_messages* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deleteforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param message_thread_id: Unique identifier for the target message thread of the forum topic + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeleteForumTopic( + chat_id=chat_id, + message_thread_id=message_thread_id, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_message( + self, + chat_id: Union[int, str], + message_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to delete a message, including service messages, with the following limitations: + + - A message can only be deleted if it was sent less than 48 hours ago. + + - Service messages about a supergroup, channel, or forum topic creation can't be deleted. + + - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. + + - Bots can delete outgoing messages in private chats, groups, and supergroups. + + - Bots can delete incoming messages in private chats. + + - Bots granted *can_post_messages* permissions can delete outgoing messages in channels. + + - If the bot is an administrator of a group, it can delete any message there. + + - If the bot has *can_delete_messages* permission in a supergroup or a channel, it can delete any message there. + + Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletemessage + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Identifier of the message to delete + :param request_timeout: Request timeout + :return: Use this method to delete a message, including service messages, with the following limitations: + """ + + call = DeleteMessage( + chat_id=chat_id, + message_id=message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_my_commands( + self, + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, `higher level commands `_ will be shown to affected users. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletemycommands + + :param scope: A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to :class:`aiogram.types.bot_command_scope_default.BotCommandScopeDefault`. + :param language_code: A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeleteMyCommands( + scope=scope, + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_sticker_from_set( + self, + sticker: str, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to delete a sticker from a set created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletestickerfromset + + :param sticker: File identifier of the sticker + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeleteStickerFromSet( + sticker=sticker, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_webhook( + self, + drop_pending_updates: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to remove webhook integration if you decide to switch back to :class:`aiogram.methods.get_updates.GetUpdates`. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletewebhook + + :param drop_pending_updates: Pass :code:`True` to drop all pending updates + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeleteWebhook( + drop_pending_updates=drop_pending_updates, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_chat_invite_link( + self, + chat_id: Union[int, str], + invite_link: str, + name: Optional[str] = None, + expire_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + member_limit: Optional[int] = None, + creates_join_request: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> ChatInviteLink: + """ + Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#editchatinvitelink + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param invite_link: The invite link to edit + :param name: Invite link name; 0-32 characters + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + :param creates_join_request: :code:`True`, if users joining the chat via the link need to be approved by chat administrators. If :code:`True`, *member_limit* can't be specified + :param request_timeout: Request timeout + :return: Returns the edited invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + """ + + call = EditChatInviteLink( + chat_id=chat_id, + invite_link=invite_link, + name=name, + expire_date=expire_date, + member_limit=member_limit, + creates_join_request=creates_join_request, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_forum_topic( + self, + chat_id: Union[int, str], + message_thread_id: int, + name: Optional[str] = None, + icon_custom_emoji_id: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#editforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param message_thread_id: Unique identifier for the target message thread of the forum topic + :param name: New topic name, 0-128 characters. If not specified or empty, the current name of the topic will be kept + :param icon_custom_emoji_id: New unique identifier of the custom emoji shown as the topic icon. Use :class:`aiogram.methods.get_forum_topic_icon_stickers.GetForumTopicIconStickers` to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = EditForumTopic( + chat_id=chat_id, + message_thread_id=message_thread_id, + name=name, + icon_custom_emoji_id=icon_custom_emoji_id, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_message_caption( + self, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + request_timeout: Optional[int] = None, + ) -> Union[Message, bool]: + """ + Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagecaption + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param chat_id: Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Required if *inline_message_id* is not specified. Identifier of the message to edit + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param caption: New caption of the message, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the message caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media. Supported only for animation, photo and video messages. + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. + :param request_timeout: Request timeout + :return: Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + """ + + call = EditMessageCaption( + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_message_live_location( + self, + latitude: float, + longitude: float, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + live_period: Optional[int] = None, + horizontal_accuracy: Optional[float] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + request_timeout: Optional[int] = None, + ) -> Union[Message, bool]: + """ + Use this method to edit live location messages. A location can be edited until its *live_period* expires or editing is explicitly disabled by a call to :class:`aiogram.methods.stop_message_live_location.StopMessageLiveLocation`. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#editmessagelivelocation + + :param latitude: Latitude of new location + :param longitude: Longitude of new location + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param chat_id: Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Required if *inline_message_id* is not specified. Identifier of the message to edit + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param live_period: New period in seconds during which the location can be updated, starting from the message send date. If 0x7FFFFFFF is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current *live_period* by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then *live_period* remains unchanged + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :param heading: Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :param proximity_alert_radius: The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :param reply_markup: A JSON-serialized object for a new `inline keyboard `_. + :param request_timeout: Request timeout + :return: On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. + """ + + call = EditMessageLiveLocation( + latitude=latitude, + longitude=longitude, + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + live_period=live_period, + horizontal_accuracy=horizontal_accuracy, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + reply_markup=reply_markup, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_message_media( + self, + media: Union[ + InputMediaAnimation, + InputMediaDocument, + InputMediaAudio, + InputMediaPhoto, + InputMediaVideo, + ], + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + request_timeout: Optional[int] = None, + ) -> Union[Message, bool]: + """ + Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagemedia + + :param media: A JSON-serialized object for a new media content of the message + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param chat_id: Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Required if *inline_message_id* is not specified. Identifier of the message to edit + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param reply_markup: A JSON-serialized object for a new `inline keyboard `_. + :param request_timeout: Request timeout + :return: Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + """ + + call = EditMessageMedia( + media=media, + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_message_reply_markup( + self, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + request_timeout: Optional[int] = None, + ) -> Union[Message, bool]: + """ + Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagereplymarkup + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param chat_id: Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Required if *inline_message_id* is not specified. Identifier of the message to edit + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. + :param request_timeout: Request timeout + :return: Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + """ + + call = EditMessageReplyMarkup( + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_message_text( + self, + text: str, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[LinkPreviewOptions] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + request_timeout: Optional[int] = None, + ) -> Union[Message, bool]: + """ + Use this method to edit text and `game `_ messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagetext + + :param text: New text of the message, 1-4096 characters after entities parsing + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param chat_id: Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Required if *inline_message_id* is not specified. Identifier of the message to edit + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param parse_mode: Mode for parsing entities in the message text. See `formatting options `_ for more details. + :param entities: A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode* + :param link_preview_options: Link preview generation options for the message + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. + :param disable_web_page_preview: Disables link previews for links in this message + :param request_timeout: Request timeout + :return: Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + """ + + call = EditMessageText( + text=text, + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + reply_markup=reply_markup, + disable_web_page_preview=disable_web_page_preview, + ) + return await self(call, request_timeout=request_timeout) + + async def export_chat_invite_link( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> str: + """ + Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as *String* on success. + + Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` or by calling the :class:`aiogram.methods.get_chat.GetChat` method. If your bot needs to generate a new primary invite link replacing its previous one, use :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` again. + + Source: https://core.telegram.org/bots/api#exportchatinvitelink + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param request_timeout: Request timeout + :return: If your bot needs to generate a new primary invite link replacing its previous one, use :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` again. + """ + + call = ExportChatInviteLink( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def forward_message( + self, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_id: int, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#forwardmessage + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param from_chat_id: Unique identifier for the chat where the original message was sent (or channel username in the format :code:`@channelusername`) + :param message_id: Message identifier in the chat specified in *from_chat_id* + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the forwarded message from forwarding and saving + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = ForwardMessage( + chat_id=chat_id, + from_chat_id=from_chat_id, + message_id=message_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + ) + return await self(call, request_timeout=request_timeout) + + async def get_chat( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> ChatFullInfo: + """ + Use this method to get up-to-date information about the chat. Returns a :class:`aiogram.types.chat_full_info.ChatFullInfo` object on success. + + Source: https://core.telegram.org/bots/api#getchat + + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`) + :param request_timeout: Request timeout + :return: Returns a :class:`aiogram.types.chat_full_info.ChatFullInfo` object on success. + """ + + call = GetChat( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def get_chat_administrators( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> List[ + Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ] + ]: + """ + Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of :class:`aiogram.types.chat_member.ChatMember` objects. + + Source: https://core.telegram.org/bots/api#getchatadministrators + + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`) + :param request_timeout: Request timeout + :return: Returns an Array of :class:`aiogram.types.chat_member.ChatMember` objects. + """ + + call = GetChatAdministrators( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def get_chat_member( + self, + chat_id: Union[int, str], + user_id: int, + request_timeout: Optional[int] = None, + ) -> Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ]: + """ + Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a :class:`aiogram.types.chat_member.ChatMember` object on success. + + Source: https://core.telegram.org/bots/api#getchatmember + + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`) + :param user_id: Unique identifier of the target user + :param request_timeout: Request timeout + :return: Returns a :class:`aiogram.types.chat_member.ChatMember` object on success. + """ + + call = GetChatMember( + chat_id=chat_id, + user_id=user_id, + ) + return await self(call, request_timeout=request_timeout) + + async def get_chat_member_count( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> int: + """ + Use this method to get the number of members in a chat. Returns *Int* on success. + + Source: https://core.telegram.org/bots/api#getchatmembercount + + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`) + :param request_timeout: Request timeout + :return: Returns *Int* on success. + """ + + call = GetChatMemberCount( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def get_chat_menu_button( + self, + chat_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Union[MenuButtonDefault, MenuButtonWebApp, MenuButtonCommands]: + """ + Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns :class:`aiogram.types.menu_button.MenuButton` on success. + + Source: https://core.telegram.org/bots/api#getchatmenubutton + + :param chat_id: Unique identifier for the target private chat. If not specified, default bot's menu button will be returned + :param request_timeout: Request timeout + :return: Returns :class:`aiogram.types.menu_button.MenuButton` on success. + """ + + call = GetChatMenuButton( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def get_custom_emoji_stickers( + self, + custom_emoji_ids: List[str], + request_timeout: Optional[int] = None, + ) -> List[Sticker]: + """ + Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of :class:`aiogram.types.sticker.Sticker` objects. + + Source: https://core.telegram.org/bots/api#getcustomemojistickers + + :param custom_emoji_ids: A JSON-serialized list of custom emoji identifiers. At most 200 custom emoji identifiers can be specified. + :param request_timeout: Request timeout + :return: Returns an Array of :class:`aiogram.types.sticker.Sticker` objects. + """ + + call = GetCustomEmojiStickers( + custom_emoji_ids=custom_emoji_ids, + ) + return await self(call, request_timeout=request_timeout) + + async def get_file( + self, + file_id: str, + request_timeout: Optional[int] = None, + ) -> File: + """ + Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a :class:`aiogram.types.file.File` object is returned. The file can then be downloaded via the link :code:`https://api.telegram.org/file/bot/`, where :code:`` is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling :class:`aiogram.methods.get_file.GetFile` again. + **Note:** This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. + + Source: https://core.telegram.org/bots/api#getfile + + :param file_id: File identifier to get information about + :param request_timeout: Request timeout + :return: You should save the file's MIME type and name (if available) when the File object is received. + """ + + call = GetFile( + file_id=file_id, + ) + return await self(call, request_timeout=request_timeout) + + async def get_forum_topic_icon_stickers( + self, + request_timeout: Optional[int] = None, + ) -> List[Sticker]: + """ + Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of :class:`aiogram.types.sticker.Sticker` objects. + + Source: https://core.telegram.org/bots/api#getforumtopiciconstickers + + :param request_timeout: Request timeout + :return: Returns an Array of :class:`aiogram.types.sticker.Sticker` objects. + """ + + call = GetForumTopicIconStickers() + return await self(call, request_timeout=request_timeout) + + async def get_game_high_scores( + self, + user_id: int, + chat_id: Optional[int] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> List[GameHighScore]: + """ + Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of :class:`aiogram.types.game_high_score.GameHighScore` objects. + + This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change. + + Source: https://core.telegram.org/bots/api#getgamehighscores + + :param user_id: Target user id + :param chat_id: Required if *inline_message_id* is not specified. Unique identifier for the target chat + :param message_id: Required if *inline_message_id* is not specified. Identifier of the sent message + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param request_timeout: Request timeout + :return: Please note that this behavior is subject to change. + """ + + call = GetGameHighScores( + user_id=user_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def get_me( + self, + request_timeout: Optional[int] = None, + ) -> User: + """ + A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a :class:`aiogram.types.user.User` object. + + Source: https://core.telegram.org/bots/api#getme + + :param request_timeout: Request timeout + :return: Returns basic information about the bot in form of a :class:`aiogram.types.user.User` object. + """ + + call = GetMe() + return await self(call, request_timeout=request_timeout) + + async def get_my_commands( + self, + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> List[BotCommand]: + """ + Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of :class:`aiogram.types.bot_command.BotCommand` objects. If commands aren't set, an empty list is returned. + + Source: https://core.telegram.org/bots/api#getmycommands + + :param scope: A JSON-serialized object, describing scope of users. Defaults to :class:`aiogram.types.bot_command_scope_default.BotCommandScopeDefault`. + :param language_code: A two-letter ISO 639-1 language code or an empty string + :param request_timeout: Request timeout + :return: If commands aren't set, an empty list is returned. + """ + + call = GetMyCommands( + scope=scope, + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def get_my_default_administrator_rights( + self, + for_channels: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> ChatAdministratorRights: + """ + Use this method to get the current default administrator rights of the bot. Returns :class:`aiogram.types.chat_administrator_rights.ChatAdministratorRights` on success. + + Source: https://core.telegram.org/bots/api#getmydefaultadministratorrights + + :param for_channels: Pass :code:`True` to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned. + :param request_timeout: Request timeout + :return: Returns :class:`aiogram.types.chat_administrator_rights.ChatAdministratorRights` on success. + """ + + call = GetMyDefaultAdministratorRights( + for_channels=for_channels, + ) + return await self(call, request_timeout=request_timeout) + + async def get_sticker_set( + self, + name: str, + request_timeout: Optional[int] = None, + ) -> StickerSet: + """ + Use this method to get a sticker set. On success, a :class:`aiogram.types.sticker_set.StickerSet` object is returned. + + Source: https://core.telegram.org/bots/api#getstickerset + + :param name: Name of the sticker set + :param request_timeout: Request timeout + :return: On success, a :class:`aiogram.types.sticker_set.StickerSet` object is returned. + """ + + call = GetStickerSet( + name=name, + ) + return await self(call, request_timeout=request_timeout) + + async def get_updates( + self, + offset: Optional[int] = None, + limit: Optional[int] = None, + timeout: Optional[int] = None, + allowed_updates: Optional[List[str]] = None, + request_timeout: Optional[int] = None, + ) -> List[Update]: + """ + Use this method to receive incoming updates using long polling (`wiki `_). Returns an Array of :class:`aiogram.types.update.Update` objects. + + **Notes** + + **1.** This method will not work if an outgoing webhook is set up. + + **2.** In order to avoid getting duplicate updates, recalculate *offset* after each server response. + + Source: https://core.telegram.org/bots/api#getupdates + + :param offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as :class:`aiogram.methods.get_updates.GetUpdates` is called with an *offset* higher than its *update_id*. The negative offset can be specified to retrieve updates starting from *-offset* update from the end of the updates queue. All previous updates will be forgotten. + :param limit: Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. + :param timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only. + :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. For example, specify :code:`["message", "edited_channel_post", "callback_query"]` to only receive updates of these types. See :class:`aiogram.types.update.Update` for a complete list of available update types. Specify an empty list to receive all update types except *chat_member*, *message_reaction*, and *message_reaction_count* (default). If not specified, the previous setting will be used. + :param request_timeout: Request timeout + :return: Returns an Array of :class:`aiogram.types.update.Update` objects. + """ + + call = GetUpdates( + offset=offset, + limit=limit, + timeout=timeout, + allowed_updates=allowed_updates, + ) + return await self(call, request_timeout=request_timeout) + + async def get_user_profile_photos( + self, + user_id: int, + offset: Optional[int] = None, + limit: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> UserProfilePhotos: + """ + Use this method to get a list of profile pictures for a user. Returns a :class:`aiogram.types.user_profile_photos.UserProfilePhotos` object. + + Source: https://core.telegram.org/bots/api#getuserprofilephotos + + :param user_id: Unique identifier of the target user + :param offset: Sequential number of the first photo to be returned. By default, all photos are returned. + :param limit: Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. + :param request_timeout: Request timeout + :return: Returns a :class:`aiogram.types.user_profile_photos.UserProfilePhotos` object. + """ + + call = GetUserProfilePhotos( + user_id=user_id, + offset=offset, + limit=limit, + ) + return await self(call, request_timeout=request_timeout) + + async def get_webhook_info( + self, + request_timeout: Optional[int] = None, + ) -> WebhookInfo: + """ + Use this method to get current webhook status. Requires no parameters. On success, returns a :class:`aiogram.types.webhook_info.WebhookInfo` object. If the bot is using :class:`aiogram.methods.get_updates.GetUpdates`, will return an object with the *url* field empty. + + Source: https://core.telegram.org/bots/api#getwebhookinfo + + :param request_timeout: Request timeout + :return: If the bot is using :class:`aiogram.methods.get_updates.GetUpdates`, will return an object with the *url* field empty. + """ + + call = GetWebhookInfo() + return await self(call, request_timeout=request_timeout) + + async def leave_chat( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method for your bot to leave a group, supergroup or channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#leavechat + + :param chat_id: Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = LeaveChat( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def log_out( + self, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to log out from the cloud Bot API server before launching the bot locally. You **must** log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns :code:`True` on success. Requires no parameters. + + Source: https://core.telegram.org/bots/api#logout + + :param request_timeout: Request timeout + :return: Requires no parameters. + """ + + call = LogOut() + return await self(call, request_timeout=request_timeout) + + async def pin_chat_message( + self, + chat_id: Union[int, str], + message_id: int, + business_connection_id: Optional[str] = None, + disable_notification: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#pinchatmessage + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Identifier of a message to pin + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be pinned + :param disable_notification: Pass :code:`True` if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = PinChatMessage( + chat_id=chat_id, + message_id=message_id, + business_connection_id=business_connection_id, + disable_notification=disable_notification, + ) + return await self(call, request_timeout=request_timeout) + + async def promote_chat_member( + self, + chat_id: Union[int, str], + user_id: int, + is_anonymous: Optional[bool] = None, + can_manage_chat: Optional[bool] = None, + can_delete_messages: Optional[bool] = None, + can_manage_video_chats: Optional[bool] = None, + can_restrict_members: Optional[bool] = None, + can_promote_members: Optional[bool] = None, + can_change_info: Optional[bool] = None, + can_invite_users: Optional[bool] = None, + can_post_stories: Optional[bool] = None, + can_edit_stories: Optional[bool] = None, + can_delete_stories: Optional[bool] = None, + can_post_messages: Optional[bool] = None, + can_edit_messages: Optional[bool] = None, + can_pin_messages: Optional[bool] = None, + can_manage_topics: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass :code:`False` for all boolean parameters to demote a user. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#promotechatmember + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param user_id: Unique identifier of the target user + :param is_anonymous: Pass :code:`True` if the administrator's presence in the chat is hidden + :param can_manage_chat: Pass :code:`True` if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages and ignore slow mode. Implied by any other administrator privilege. + :param can_delete_messages: Pass :code:`True` if the administrator can delete messages of other users + :param can_manage_video_chats: Pass :code:`True` if the administrator can manage video chats + :param can_restrict_members: Pass :code:`True` if the administrator can restrict, ban or unban chat members, or access supergroup statistics + :param can_promote_members: Pass :code:`True` if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him) + :param can_change_info: Pass :code:`True` if the administrator can change chat title, photo and other settings + :param can_invite_users: Pass :code:`True` if the administrator can invite new users to the chat + :param can_post_stories: Pass :code:`True` if the administrator can post stories to the chat + :param can_edit_stories: Pass :code:`True` if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive + :param can_delete_stories: Pass :code:`True` if the administrator can delete stories posted by other users + :param can_post_messages: Pass :code:`True` if the administrator can post messages in the channel, or access channel statistics; for channels only + :param can_edit_messages: Pass :code:`True` if the administrator can edit messages of other users and can pin messages; for channels only + :param can_pin_messages: Pass :code:`True` if the administrator can pin messages; for supergroups only + :param can_manage_topics: Pass :code:`True` if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = PromoteChatMember( + chat_id=chat_id, + user_id=user_id, + is_anonymous=is_anonymous, + can_manage_chat=can_manage_chat, + can_delete_messages=can_delete_messages, + can_manage_video_chats=can_manage_video_chats, + can_restrict_members=can_restrict_members, + can_promote_members=can_promote_members, + can_change_info=can_change_info, + can_invite_users=can_invite_users, + can_post_stories=can_post_stories, + can_edit_stories=can_edit_stories, + can_delete_stories=can_delete_stories, + can_post_messages=can_post_messages, + can_edit_messages=can_edit_messages, + can_pin_messages=can_pin_messages, + can_manage_topics=can_manage_topics, + ) + return await self(call, request_timeout=request_timeout) + + async def reopen_forum_topic( + self, + chat_id: Union[int, str], + message_thread_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#reopenforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param message_thread_id: Unique identifier for the target message thread of the forum topic + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = ReopenForumTopic( + chat_id=chat_id, + message_thread_id=message_thread_id, + ) + return await self(call, request_timeout=request_timeout) + + async def restrict_chat_member( + self, + chat_id: Union[int, str], + user_id: int, + permissions: ChatPermissions, + use_independent_chat_permissions: Optional[bool] = None, + until_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass :code:`True` for all permissions to lift restrictions from a user. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#restrictchatmember + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param user_id: Unique identifier of the target user + :param permissions: A JSON-serialized object for new user permissions + :param use_independent_chat_permissions: Pass :code:`True` if chat permissions are set independently. Otherwise, the *can_send_other_messages* and *can_add_web_page_previews* permissions will imply the *can_send_messages*, *can_send_audios*, *can_send_documents*, *can_send_photos*, *can_send_videos*, *can_send_video_notes*, and *can_send_voice_notes* permissions; the *can_send_polls* permission will imply the *can_send_messages* permission. + :param until_date: Date when restrictions will be lifted for the user; Unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = RestrictChatMember( + chat_id=chat_id, + user_id=user_id, + permissions=permissions, + use_independent_chat_permissions=use_independent_chat_permissions, + until_date=until_date, + ) + return await self(call, request_timeout=request_timeout) + + async def revoke_chat_invite_link( + self, + chat_id: Union[int, str], + invite_link: str, + request_timeout: Optional[int] = None, + ) -> ChatInviteLink: + """ + Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#revokechatinvitelink + + :param chat_id: Unique identifier of the target chat or username of the target channel (in the format :code:`@channelusername`) + :param invite_link: The invite link to revoke + :param request_timeout: Request timeout + :return: Returns the revoked invite link as :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + """ + + call = RevokeChatInviteLink( + chat_id=chat_id, + invite_link=invite_link, + ) + return await self(call, request_timeout=request_timeout) + + async def send_animation( + self, + chat_id: Union[int, str], + animation: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendanimation + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent animation in seconds + :param width: Animation width + :param height: Animation height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Animation caption (may also be used when resending animation by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the animation caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the animation needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. + """ + + call = SendAnimation( + chat_id=chat_id, + animation=animation, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_audio( + self, + chat_id: Union[int, str], + audio: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + For sending voice messages, use the :class:`aiogram.methods.send_voice.SendVoice` method instead. + + Source: https://core.telegram.org/bots/api#sendaudio + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Audio caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the audio caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the audio in seconds + :param performer: Performer + :param title: Track name + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + """ + + call = SendAudio( + chat_id=chat_id, + audio=audio, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_chat_action( + self, + chat_id: Union[int, str], + action: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns :code:`True` on success. + + Example: The `ImageBot `_ needs some time to process a request and upload the image. Instead of sending a text message along the lines of 'Retrieving image, please wait…', the bot may use :class:`aiogram.methods.send_chat_action.SendChatAction` with *action* = *upload_photo*. The user will see a 'sending photo' status for the bot. + + We only recommend using this method when a response from the bot will take a **noticeable** amount of time to arrive. + + Source: https://core.telegram.org/bots/api#sendchataction + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param action: Type of action to broadcast. Choose one, depending on what the user is about to receive: *typing* for `text messages `_, *upload_photo* for `photos `_, *record_video* or *upload_video* for `videos `_, *record_voice* or *upload_voice* for `voice notes `_, *upload_document* for `general files `_, *choose_sticker* for `stickers `_, *find_location* for `location data `_, *record_video_note* or *upload_video_note* for `video notes `_. + :param business_connection_id: Unique identifier of the business connection on behalf of which the action will be sent + :param message_thread_id: Unique identifier for the target message thread; for supergroups only + :param request_timeout: Request timeout + :return: The user will see a 'sending photo' status for the bot. + """ + + call = SendChatAction( + chat_id=chat_id, + action=action, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_contact( + self, + chat_id: Union[int, str], + phone_number: str, + first_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send phone contacts. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendcontact + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param phone_number: Contact's phone number + :param first_name: Contact's first name + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param last_name: Contact's last name + :param vcard: Additional data about the contact in the form of a `vCard `_, 0-2048 bytes + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendContact( + chat_id=chat_id, + phone_number=phone_number, + first_name=first_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + last_name=last_name, + vcard=vcard, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_dice( + self, + chat_id: Union[int, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send an animated emoji that will display a random value. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#senddice + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param emoji: Emoji on which the dice throw animation is based. Currently, must be one of '🎲', '🎯', '🏀', '⚽', '🎳', or '🎰'. Dice can have values 1-6 for '🎲', '🎯' and '🎳', values 1-5 for '🏀' and '⚽', and values 1-64 for '🎰'. Defaults to '🎲' + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendDice( + chat_id=chat_id, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_document( + self, + chat_id: Union[int, str], + document: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send general files. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#senddocument + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param document: File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Document caption (may also be used when resending documents by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the document caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + """ + + call = SendDocument( + chat_id=chat_id, + document=document, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_game( + self, + chat_id: int, + game_short_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send a game. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendgame + + :param chat_id: Unique identifier for the target chat + :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via `@BotFather `_. + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendGame( + chat_id=chat_id, + game_short_name=game_short_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_invoice( + self, + chat_id: Union[int, str], + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + message_thread_id: Optional[int] = None, + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + start_parameter: Optional[str] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send invoices. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendinvoice + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param title: Product name, 1-32 characters + :param description: Product description, 1-255 characters + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param currency: Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_. + :param prices: Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_. + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param provider_token: Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_. + :param max_tip_amount: The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_. + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*. + :param start_parameter: Unique deep-linking parameter. If left empty, **forwarded copies** of the sent message will have a *Pay* button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a *URL* button with a deep link to the bot (instead of a *Pay* button), with the value used as the start parameter + :param provider_data: JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size in bytes + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_phone_number: Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_email: Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_shipping_address: Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_. + :param send_phone_number_to_provider: Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param send_email_to_provider: Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param is_flexible: Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Pay :code:`total price`' button will be shown. If not empty, the first button must be a Pay button. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendInvoice( + chat_id=chat_id, + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + message_thread_id=message_thread_id, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + start_parameter=start_parameter, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_location( + self, + chat_id: Union[int, str], + latitude: float, + longitude: float, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send point on the map. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendlocation + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param latitude: Latitude of the location + :param longitude: Longitude of the location + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :param live_period: Period in seconds during which the location will be updated (see `Live Locations `_, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + :param heading: For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :param proximity_alert_radius: For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendLocation( + chat_id=chat_id, + latitude=latitude, + longitude=longitude, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_media_group( + self, + chat_id: Union[int, str], + media: List[Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> List[Message]: + """ + Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of `Messages `_ that were sent is returned. + + Source: https://core.telegram.org/bots/api#sendmediagroup + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param media: A JSON-serialized array describing messages to be sent, must include 2-10 items + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends messages `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent messages from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the messages are a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, an array of `Messages `_ that were sent is returned. + """ + + call = SendMediaGroup( + chat_id=chat_id, + media=media, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_message( + self, + chat_id: Union[int, str], + text: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[Union[LinkPreviewOptions, Default]] = Default( + "link_preview" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send text messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendmessage + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param text: Text of the message to be sent, 1-4096 characters after entities parsing + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param parse_mode: Mode for parsing entities in the message text. See `formatting options `_ for more details. + :param entities: A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode* + :param link_preview_options: Link preview generation options for the message + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param disable_web_page_preview: Disables link previews for links in this message + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendMessage( + chat_id=chat_id, + text=text, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + disable_web_page_preview=disable_web_page_preview, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_photo( + self, + chat_id: Union[int, str], + photo: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send photos. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendphoto + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Photo caption (may also be used when resending photos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the photo caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the photo needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendPhoto( + chat_id=chat_id, + photo=photo, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_poll( + self, + chat_id: Union[int, str], + question: str, + options: List[Union[InputPollOption, str]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + question_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + question_entities: Optional[List[MessageEntity]] = None, + is_anonymous: Optional[bool] = None, + type: Optional[str] = None, + allows_multiple_answers: Optional[bool] = None, + correct_option_id: Optional[int] = None, + explanation: Optional[str] = None, + explanation_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + explanation_entities: Optional[List[MessageEntity]] = None, + open_period: Optional[int] = None, + close_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + is_closed: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send a native poll. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpoll + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param question: Poll question, 1-300 characters + :param options: A JSON-serialized list of 2-10 answer options + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param question_parse_mode: Mode for parsing entities in the question. See `formatting options `_ for more details. Currently, only custom emoji entities are allowed + :param question_entities: A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of *question_parse_mode* + :param is_anonymous: :code:`True`, if the poll needs to be anonymous, defaults to :code:`True` + :param type: Poll type, 'quiz' or 'regular', defaults to 'regular' + :param allows_multiple_answers: :code:`True`, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to :code:`False` + :param correct_option_id: 0-based identifier of the correct answer option, required for polls in quiz mode + :param explanation: Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing + :param explanation_parse_mode: Mode for parsing entities in the explanation. See `formatting options `_ for more details. + :param explanation_entities: A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of *explanation_parse_mode* + :param open_period: Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with *close_date*. + :param close_date: Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with *open_period*. + :param is_closed: Pass :code:`True` if the poll needs to be immediately closed. This can be useful for poll preview. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendPoll( + chat_id=chat_id, + question=question, + options=options, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + question_parse_mode=question_parse_mode, + question_entities=question_entities, + is_anonymous=is_anonymous, + type=type, + allows_multiple_answers=allows_multiple_answers, + correct_option_id=correct_option_id, + explanation=explanation, + explanation_parse_mode=explanation_parse_mode, + explanation_entities=explanation_entities, + open_period=open_period, + close_date=close_date, + is_closed=is_closed, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_sticker( + self, + chat_id: Union[int, str], + sticker: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send static .WEBP, `animated `_ .TGS, or `video `_ .WEBM stickers. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendsticker + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param sticker: Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. :ref:`More information on Sending Files » `. Video and animated stickers can't be sent via an HTTP URL. + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param emoji: Emoji associated with the sticker; only for just uploaded stickers + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendSticker( + chat_id=chat_id, + sticker=sticker, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_venue( + self, + chat_id: Union[int, str], + latitude: float, + longitude: float, + title: str, + address: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send information about a venue. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvenue + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param latitude: Latitude of the venue + :param longitude: Longitude of the venue + :param title: Name of the venue + :param address: Address of the venue + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param foursquare_id: Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.) + :param google_place_id: Google Places identifier of the venue + :param google_place_type: Google Places type of the venue. (See `supported types `_.) + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendVenue( + chat_id=chat_id, + latitude=latitude, + longitude=longitude, + title=title, + address=address, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_video( + self, + chat_id: Union[int, str], + video: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + supports_streaming: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvideo + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param video: Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent video in seconds + :param width: Video width + :param height: Video height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Video caption (may also be used when resending videos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the video caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the video needs to be covered with a spoiler animation + :param supports_streaming: Pass :code:`True` if the uploaded video is suitable for streaming + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + """ + + call = SendVideo( + chat_id=chat_id, + video=video, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + supports_streaming=supports_streaming, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_video_note( + self, + chat_id: Union[int, str], + video_note: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + length: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + As of `v.4.0 `_, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvideonote + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param video_note: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. :ref:`More information on Sending Files » `. Sending video notes by a URL is currently unsupported + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent video in seconds + :param length: Video width and height, i.e. diameter of the video message + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendVideoNote( + chat_id=chat_id, + video_note=video_note, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + length=length, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def send_voice( + self, + chat_id: Union[int, str], + voice: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as :class:`aiogram.types.audio.Audio` or :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvoice + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param voice: Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Voice message caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the voice message caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the voice message in seconds + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :param request_timeout: Request timeout + :return: Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + """ + + call = SendVoice( + chat_id=chat_id, + voice=voice, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def set_chat_administrator_custom_title( + self, + chat_id: Union[int, str], + user_id: int, + custom_title: str, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatadministratorcustomtitle + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param user_id: Unique identifier of the target user + :param custom_title: New custom title for the administrator; 0-16 characters, emoji are not allowed + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetChatAdministratorCustomTitle( + chat_id=chat_id, + user_id=user_id, + custom_title=custom_title, + ) + return await self(call, request_timeout=request_timeout) + + async def set_chat_description( + self, + chat_id: Union[int, str], + description: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatdescription + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param description: New chat description, 0-255 characters + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetChatDescription( + chat_id=chat_id, + description=description, + ) + return await self(call, request_timeout=request_timeout) + + async def set_chat_menu_button( + self, + chat_id: Optional[int] = None, + menu_button: Optional[ + Union[MenuButtonCommands, MenuButtonWebApp, MenuButtonDefault] + ] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the bot's menu button in a private chat, or the default menu button. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatmenubutton + + :param chat_id: Unique identifier for the target private chat. If not specified, default bot's menu button will be changed + :param menu_button: A JSON-serialized object for the bot's new menu button. Defaults to :class:`aiogram.types.menu_button_default.MenuButtonDefault` + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetChatMenuButton( + chat_id=chat_id, + menu_button=menu_button, + ) + return await self(call, request_timeout=request_timeout) + + async def set_chat_permissions( + self, + chat_id: Union[int, str], + permissions: ChatPermissions, + use_independent_chat_permissions: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the *can_restrict_members* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatpermissions + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param permissions: A JSON-serialized object for new default chat permissions + :param use_independent_chat_permissions: Pass :code:`True` if chat permissions are set independently. Otherwise, the *can_send_other_messages* and *can_add_web_page_previews* permissions will imply the *can_send_messages*, *can_send_audios*, *can_send_documents*, *can_send_photos*, *can_send_videos*, *can_send_video_notes*, and *can_send_voice_notes* permissions; the *can_send_polls* permission will imply the *can_send_messages* permission. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetChatPermissions( + chat_id=chat_id, + permissions=permissions, + use_independent_chat_permissions=use_independent_chat_permissions, + ) + return await self(call, request_timeout=request_timeout) + + async def set_chat_photo( + self, + chat_id: Union[int, str], + photo: InputFile, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatphoto + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param photo: New chat photo, uploaded using multipart/form-data + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetChatPhoto( + chat_id=chat_id, + photo=photo, + ) + return await self(call, request_timeout=request_timeout) + + async def set_chat_sticker_set( + self, + chat_id: Union[int, str], + sticker_set_name: str, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field *can_set_sticker_set* optionally returned in :class:`aiogram.methods.get_chat.GetChat` requests to check if the bot can use this method. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatstickerset + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param sticker_set_name: Name of the sticker set to be set as the group sticker set + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetChatStickerSet( + chat_id=chat_id, + sticker_set_name=sticker_set_name, + ) + return await self(call, request_timeout=request_timeout) + + async def set_chat_title( + self, + chat_id: Union[int, str], + title: str, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchattitle + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param title: New chat title, 1-128 characters + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetChatTitle( + chat_id=chat_id, + title=title, + ) + return await self(call, request_timeout=request_timeout) + + async def set_game_score( + self, + user_id: int, + score: int, + force: Optional[bool] = None, + disable_edit_message: Optional[bool] = None, + chat_id: Optional[int] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> Union[Message, bool]: + """ + Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Returns an error, if the new score is not greater than the user's current score in the chat and *force* is :code:`False`. + + Source: https://core.telegram.org/bots/api#setgamescore + + :param user_id: User identifier + :param score: New score, must be non-negative + :param force: Pass :code:`True` if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters + :param disable_edit_message: Pass :code:`True` if the game message should not be automatically edited to include the current scoreboard + :param chat_id: Required if *inline_message_id* is not specified. Unique identifier for the target chat + :param message_id: Required if *inline_message_id* is not specified. Identifier of the sent message + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param request_timeout: Request timeout + :return: Returns an error, if the new score is not greater than the user's current score in the chat and *force* is :code:`False`. + """ + + call = SetGameScore( + user_id=user_id, + score=score, + force=force, + disable_edit_message=disable_edit_message, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def set_my_commands( + self, + commands: List[BotCommand], + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the list of the bot's commands. See `this manual `_ for more details about bot commands. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmycommands + + :param commands: A JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified. + :param scope: A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to :class:`aiogram.types.bot_command_scope_default.BotCommandScopeDefault`. + :param language_code: A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetMyCommands( + commands=commands, + scope=scope, + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def set_my_default_administrator_rights( + self, + rights: Optional[ChatAdministratorRights] = None, + for_channels: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmydefaultadministratorrights + + :param rights: A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared. + :param for_channels: Pass :code:`True` to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetMyDefaultAdministratorRights( + rights=rights, + for_channels=for_channels, + ) + return await self(call, request_timeout=request_timeout) + + async def set_passport_data_errors( + self, + user_id: int, + errors: List[ + Union[ + PassportElementErrorDataField, + PassportElementErrorFrontSide, + PassportElementErrorReverseSide, + PassportElementErrorSelfie, + PassportElementErrorFile, + PassportElementErrorFiles, + PassportElementErrorTranslationFile, + PassportElementErrorTranslationFiles, + PassportElementErrorUnspecified, + ] + ], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns :code:`True` on success. + Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues. + + Source: https://core.telegram.org/bots/api#setpassportdataerrors + + :param user_id: User identifier + :param errors: A JSON-serialized array describing the errors + :param request_timeout: Request timeout + :return: Supply some details in the error message to make sure the user knows how to correct the issues. + """ + + call = SetPassportDataErrors( + user_id=user_id, + errors=errors, + ) + return await self(call, request_timeout=request_timeout) + + async def set_sticker_position_in_set( + self, + sticker: str, + position: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to move a sticker in a set created by the bot to a specific position. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickerpositioninset + + :param sticker: File identifier of the sticker + :param position: New sticker position in the set, zero-based + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetStickerPositionInSet( + sticker=sticker, + position=position, + ) + return await self(call, request_timeout=request_timeout) + + async def set_webhook( + self, + url: str, + certificate: Optional[InputFile] = None, + ip_address: Optional[str] = None, + max_connections: Optional[int] = None, + allowed_updates: Optional[List[str]] = None, + drop_pending_updates: Optional[bool] = None, + secret_token: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized :class:`aiogram.types.update.Update`. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns :code:`True` on success. + If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter *secret_token*. If specified, the request will contain a header 'X-Telegram-Bot-Api-Secret-Token' with the secret token as content. + + **Notes** + + **1.** You will not be able to receive updates using :class:`aiogram.methods.get_updates.GetUpdates` for as long as an outgoing webhook is set up. + + **2.** To use a self-signed certificate, you need to upload your `public key certificate `_ using *certificate* parameter. Please upload as InputFile, sending a String will not work. + + **3.** Ports currently supported *for webhooks*: **443, 80, 88, 8443**. + If you're having any trouble setting up webhooks, please check out this `amazing guide to webhooks `_. + + Source: https://core.telegram.org/bots/api#setwebhook + + :param url: HTTPS URL to send updates to. Use an empty string to remove webhook integration + :param certificate: Upload your public key certificate so that the root certificate in use can be checked. See our `self-signed guide `_ for details. + :param ip_address: The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS + :param max_connections: The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to *40*. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput. + :param allowed_updates: A JSON-serialized list of the update types you want your bot to receive. For example, specify :code:`["message", "edited_channel_post", "callback_query"]` to only receive updates of these types. See :class:`aiogram.types.update.Update` for a complete list of available update types. Specify an empty list to receive all update types except *chat_member*, *message_reaction*, and *message_reaction_count* (default). If not specified, the previous setting will be used. + :param drop_pending_updates: Pass :code:`True` to drop all pending updates + :param secret_token: A secret token to be sent in a header 'X-Telegram-Bot-Api-Secret-Token' in every webhook request, 1-256 characters. Only characters :code:`A-Z`, :code:`a-z`, :code:`0-9`, :code:`_` and :code:`-` are allowed. The header is useful to ensure that the request comes from a webhook set by you. + :param request_timeout: Request timeout + :return: Please upload as InputFile, sending a String will not work. + """ + + call = SetWebhook( + url=url, + certificate=certificate, + ip_address=ip_address, + max_connections=max_connections, + allowed_updates=allowed_updates, + drop_pending_updates=drop_pending_updates, + secret_token=secret_token, + ) + return await self(call, request_timeout=request_timeout) + + async def stop_message_live_location( + self, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + request_timeout: Optional[int] = None, + ) -> Union[Message, bool]: + """ + Use this method to stop updating a live location message before *live_period* expires. On success, if the message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#stopmessagelivelocation + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param chat_id: Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Required if *inline_message_id* is not specified. Identifier of the message with live location to stop + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param reply_markup: A JSON-serialized object for a new `inline keyboard `_. + :param request_timeout: Request timeout + :return: On success, if the message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. + """ + + call = StopMessageLiveLocation( + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + ) + return await self(call, request_timeout=request_timeout) + + async def stop_poll( + self, + chat_id: Union[int, str], + message_id: int, + business_connection_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + request_timeout: Optional[int] = None, + ) -> Poll: + """ + Use this method to stop a poll which was sent by the bot. On success, the stopped :class:`aiogram.types.poll.Poll` is returned. + + Source: https://core.telegram.org/bots/api#stoppoll + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Identifier of the original message with the poll + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param reply_markup: A JSON-serialized object for a new message `inline keyboard `_. + :param request_timeout: Request timeout + :return: On success, the stopped :class:`aiogram.types.poll.Poll` is returned. + """ + + call = StopPoll( + chat_id=chat_id, + message_id=message_id, + business_connection_id=business_connection_id, + reply_markup=reply_markup, + ) + return await self(call, request_timeout=request_timeout) + + async def unban_chat_member( + self, + chat_id: Union[int, str], + user_id: int, + only_if_banned: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to unban a previously banned user in a supergroup or channel. The user will **not** return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be **removed** from the chat. If you don't want this, use the parameter *only_if_banned*. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unbanchatmember + + :param chat_id: Unique identifier for the target group or username of the target supergroup or channel (in the format :code:`@channelusername`) + :param user_id: Unique identifier of the target user + :param only_if_banned: Do nothing if the user is not banned + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = UnbanChatMember( + chat_id=chat_id, + user_id=user_id, + only_if_banned=only_if_banned, + ) + return await self(call, request_timeout=request_timeout) + + async def unban_chat_sender_chat( + self, + chat_id: Union[int, str], + sender_chat_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unbanchatsenderchat + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param sender_chat_id: Unique identifier of the target sender chat + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = UnbanChatSenderChat( + chat_id=chat_id, + sender_chat_id=sender_chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def unpin_all_chat_messages( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinallchatmessages + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = UnpinAllChatMessages( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def unpin_all_forum_topic_messages( + self, + chat_id: Union[int, str], + message_thread_id: int, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to clear the list of pinned messages in a forum topic. The bot must be an administrator in the chat for this to work and must have the *can_pin_messages* administrator right in the supergroup. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinallforumtopicmessages + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param message_thread_id: Unique identifier for the target message thread of the forum topic + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = UnpinAllForumTopicMessages( + chat_id=chat_id, + message_thread_id=message_thread_id, + ) + return await self(call, request_timeout=request_timeout) + + async def unpin_chat_message( + self, + chat_id: Union[int, str], + business_connection_id: Optional[str] = None, + message_id: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinchatmessage + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be unpinned + :param message_id: Identifier of the message to unpin. Required if *business_connection_id* is specified. If not specified, the most recent pinned message (by sending date) will be unpinned. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = UnpinChatMessage( + chat_id=chat_id, + business_connection_id=business_connection_id, + message_id=message_id, + ) + return await self(call, request_timeout=request_timeout) + + async def upload_sticker_file( + self, + user_id: int, + sticker: InputFile, + sticker_format: str, + request_timeout: Optional[int] = None, + ) -> File: + """ + Use this method to upload a file with a sticker for later use in the :class:`aiogram.methods.create_new_sticker_set.CreateNewStickerSet`, :class:`aiogram.methods.add_sticker_to_set.AddStickerToSet`, or :class:`aiogram.methods.replace_sticker_in_set.ReplaceStickerInSet` methods (the file can be used multiple times). Returns the uploaded :class:`aiogram.types.file.File` on success. + + Source: https://core.telegram.org/bots/api#uploadstickerfile + + :param user_id: User identifier of sticker file owner + :param sticker: A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See `https://core.telegram.org/stickers `_`https://core.telegram.org/stickers `_ for technical requirements. :ref:`More information on Sending Files » ` + :param sticker_format: Format of the sticker, must be one of 'static', 'animated', 'video' + :param request_timeout: Request timeout + :return: Returns the uploaded :class:`aiogram.types.file.File` on success. + """ + + call = UploadStickerFile( + user_id=user_id, + sticker=sticker, + sticker_format=sticker_format, + ) + return await self(call, request_timeout=request_timeout) + + async def close_general_forum_topic( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#closegeneralforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = CloseGeneralForumTopic( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_general_forum_topic( + self, + chat_id: Union[int, str], + name: str, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#editgeneralforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param name: New topic name, 1-128 characters + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = EditGeneralForumTopic( + chat_id=chat_id, + name=name, + ) + return await self(call, request_timeout=request_timeout) + + async def hide_general_forum_topic( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. The topic will be automatically closed if it was open. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#hidegeneralforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = HideGeneralForumTopic( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def reopen_general_forum_topic( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. The topic will be automatically unhidden if it was hidden. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#reopengeneralforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = ReopenGeneralForumTopic( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def unhide_general_forum_topic( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unhidegeneralforumtopic + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = UnhideGeneralForumTopic( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_sticker_set( + self, + name: str, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to delete a sticker set that was created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletestickerset + + :param name: Sticker set name + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeleteStickerSet( + name=name, + ) + return await self(call, request_timeout=request_timeout) + + async def get_my_description( + self, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> BotDescription: + """ + Use this method to get the current bot description for the given user language. Returns :class:`aiogram.types.bot_description.BotDescription` on success. + + Source: https://core.telegram.org/bots/api#getmydescription + + :param language_code: A two-letter ISO 639-1 language code or an empty string + :param request_timeout: Request timeout + :return: Returns :class:`aiogram.types.bot_description.BotDescription` on success. + """ + + call = GetMyDescription( + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def get_my_short_description( + self, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> BotShortDescription: + """ + Use this method to get the current bot short description for the given user language. Returns :class:`aiogram.types.bot_short_description.BotShortDescription` on success. + + Source: https://core.telegram.org/bots/api#getmyshortdescription + + :param language_code: A two-letter ISO 639-1 language code or an empty string + :param request_timeout: Request timeout + :return: Returns :class:`aiogram.types.bot_short_description.BotShortDescription` on success. + """ + + call = GetMyShortDescription( + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def set_custom_emoji_sticker_set_thumbnail( + self, + name: str, + custom_emoji_id: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to set the thumbnail of a custom emoji sticker set. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail + + :param name: Sticker set name + :param custom_emoji_id: Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetCustomEmojiStickerSetThumbnail( + name=name, + custom_emoji_id=custom_emoji_id, + ) + return await self(call, request_timeout=request_timeout) + + async def set_my_description( + self, + description: Optional[str] = None, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmydescription + + :param description: New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language. + :param language_code: A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetMyDescription( + description=description, + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def set_my_short_description( + self, + short_description: Optional[str] = None, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmyshortdescription + + :param short_description: New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language. + :param language_code: A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetMyShortDescription( + short_description=short_description, + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def set_sticker_emoji_list( + self, + sticker: str, + emoji_list: List[str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickeremojilist + + :param sticker: File identifier of the sticker + :param emoji_list: A JSON-serialized list of 1-20 emoji associated with the sticker + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetStickerEmojiList( + sticker=sticker, + emoji_list=emoji_list, + ) + return await self(call, request_timeout=request_timeout) + + async def set_sticker_keywords( + self, + sticker: str, + keywords: Optional[List[str]] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickerkeywords + + :param sticker: File identifier of the sticker + :param keywords: A JSON-serialized list of 0-20 search keywords for the sticker with total length of up to 64 characters + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetStickerKeywords( + sticker=sticker, + keywords=keywords, + ) + return await self(call, request_timeout=request_timeout) + + async def set_sticker_mask_position( + self, + sticker: str, + mask_position: Optional[MaskPosition] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the `mask position `_ of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickermaskposition + + :param sticker: File identifier of the sticker + :param mask_position: A JSON-serialized object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetStickerMaskPosition( + sticker=sticker, + mask_position=mask_position, + ) + return await self(call, request_timeout=request_timeout) + + async def set_sticker_set_thumbnail( + self, + name: str, + user_id: int, + format: str, + thumbnail: Optional[Union[InputFile, str]] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickersetthumbnail + + :param name: Sticker set name + :param user_id: User identifier of the sticker set owner + :param format: Format of the thumbnail, must be one of 'static' for a **.WEBP** or **.PNG** image, 'animated' for a **.TGS** animation, or 'video' for a **WEBM** video + :param thumbnail: A **.WEBP** or **.PNG** image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a **.TGS** animation with a thumbnail up to 32 kilobytes in size (see `https://core.telegram.org/stickers#animation-requirements `_`https://core.telegram.org/stickers#animation-requirements `_ for animated sticker technical requirements), or a **WEBM** video with the thumbnail up to 32 kilobytes in size; see `https://core.telegram.org/stickers#video-requirements `_`https://core.telegram.org/stickers#video-requirements `_ for video sticker technical requirements. Pass a *file_id* as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » `. Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetStickerSetThumbnail( + name=name, + user_id=user_id, + format=format, + thumbnail=thumbnail, + ) + return await self(call, request_timeout=request_timeout) + + async def set_sticker_set_title( + self, + name: str, + title: str, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to set the title of a created sticker set. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickersettitle + + :param name: Sticker set name + :param title: Sticker set title, 1-64 characters + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetStickerSetTitle( + name=name, + title=title, + ) + return await self(call, request_timeout=request_timeout) + + async def get_my_name( + self, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> BotName: + """ + Use this method to get the current bot name for the given user language. Returns :class:`aiogram.types.bot_name.BotName` on success. + + Source: https://core.telegram.org/bots/api#getmyname + + :param language_code: A two-letter ISO 639-1 language code or an empty string + :param request_timeout: Request timeout + :return: Returns :class:`aiogram.types.bot_name.BotName` on success. + """ + + call = GetMyName( + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def set_my_name( + self, + name: Optional[str] = None, + language_code: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the bot's name. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmyname + + :param name: New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language. + :param language_code: A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetMyName( + name=name, + language_code=language_code, + ) + return await self(call, request_timeout=request_timeout) + + async def unpin_all_general_forum_topic_messages( + self, + chat_id: Union[int, str], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the *can_pin_messages* administrator right in the supergroup. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages + + :param chat_id: Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`) + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = UnpinAllGeneralForumTopicMessages( + chat_id=chat_id, + ) + return await self(call, request_timeout=request_timeout) + + async def copy_messages( + self, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_ids: List[int], + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[bool] = None, + remove_caption: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> List[MessageId]: + """ + Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz :class:`aiogram.methods.poll.Poll` can be copied only if the value of the field *correct_option_id* is known to the bot. The method is analogous to the method :class:`aiogram.methods.forward_messages.ForwardMessages`, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of :class:`aiogram.types.message_id.MessageId` of the sent messages is returned. + + Source: https://core.telegram.org/bots/api#copymessages + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param from_chat_id: Unique identifier for the chat where the original messages were sent (or channel username in the format :code:`@channelusername`) + :param message_ids: A JSON-serialized list of 1-100 identifiers of messages in the chat *from_chat_id* to copy. The identifiers must be specified in a strictly increasing order. + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends the messages `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent messages from forwarding and saving + :param remove_caption: Pass :code:`True` to copy the messages without their captions + :param request_timeout: Request timeout + :return: On success, an array of :class:`aiogram.types.message_id.MessageId` of the sent messages is returned. + """ + + call = CopyMessages( + chat_id=chat_id, + from_chat_id=from_chat_id, + message_ids=message_ids, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + remove_caption=remove_caption, + ) + return await self(call, request_timeout=request_timeout) + + async def delete_messages( + self, + chat_id: Union[int, str], + message_ids: List[int], + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletemessages + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_ids: A JSON-serialized list of 1-100 identifiers of messages to delete. See :class:`aiogram.methods.delete_message.DeleteMessage` for limitations on which messages can be deleted + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = DeleteMessages( + chat_id=chat_id, + message_ids=message_ids, + ) + return await self(call, request_timeout=request_timeout) + + async def forward_messages( + self, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_ids: List[int], + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> List[MessageId]: + """ + Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of :class:`aiogram.types.message_id.MessageId` of the sent messages is returned. + + Source: https://core.telegram.org/bots/api#forwardmessages + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param from_chat_id: Unique identifier for the chat where the original messages were sent (or channel username in the format :code:`@channelusername`) + :param message_ids: A JSON-serialized list of 1-100 identifiers of messages in the chat *from_chat_id* to forward. The identifiers must be specified in a strictly increasing order. + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends the messages `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the forwarded messages from forwarding and saving + :param request_timeout: Request timeout + :return: On success, an array of :class:`aiogram.types.message_id.MessageId` of the sent messages is returned. + """ + + call = ForwardMessages( + chat_id=chat_id, + from_chat_id=from_chat_id, + message_ids=message_ids, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + ) + return await self(call, request_timeout=request_timeout) + + async def get_user_chat_boosts( + self, + chat_id: Union[int, str], + user_id: int, + request_timeout: Optional[int] = None, + ) -> UserChatBoosts: + """ + Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a :class:`aiogram.types.user_chat_boosts.UserChatBoosts` object. + + Source: https://core.telegram.org/bots/api#getuserchatboosts + + :param chat_id: Unique identifier for the chat or username of the channel (in the format :code:`@channelusername`) + :param user_id: Unique identifier of the target user + :param request_timeout: Request timeout + :return: Returns a :class:`aiogram.types.user_chat_boosts.UserChatBoosts` object. + """ + + call = GetUserChatBoosts( + chat_id=chat_id, + user_id=user_id, + ) + return await self(call, request_timeout=request_timeout) + + async def set_message_reaction( + self, + chat_id: Union[int, str], + message_id: int, + reaction: Optional[ + List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + ] = None, + is_big: Optional[bool] = None, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmessagereaction + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_id: Identifier of the target message. If the message belongs to a media group, the reaction is set to the first non-deleted message in the group instead. + :param reaction: A JSON-serialized list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots. + :param is_big: Pass :code:`True` to set the reaction with a big animation + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = SetMessageReaction( + chat_id=chat_id, + message_id=message_id, + reaction=reaction, + is_big=is_big, + ) + return await self(call, request_timeout=request_timeout) + + async def get_business_connection( + self, + business_connection_id: str, + request_timeout: Optional[int] = None, + ) -> BusinessConnection: + """ + Use this method to get information about the connection of the bot with a business account. Returns a :class:`aiogram.types.business_connection.BusinessConnection` object on success. + + Source: https://core.telegram.org/bots/api#getbusinessconnection + + :param business_connection_id: Unique identifier of the business connection + :param request_timeout: Request timeout + :return: Returns a :class:`aiogram.types.business_connection.BusinessConnection` object on success. + """ + + call = GetBusinessConnection( + business_connection_id=business_connection_id, + ) + return await self(call, request_timeout=request_timeout) + + async def replace_sticker_in_set( + self, + user_id: int, + name: str, + old_sticker: str, + sticker: InputSticker, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling :class:`aiogram.methods.delete_sticker_from_set.DeleteStickerFromSet`, then :class:`aiogram.methods.add_sticker_to_set.AddStickerToSet`, then :class:`aiogram.methods.set_sticker_position_in_set.SetStickerPositionInSet`. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#replacestickerinset + + :param user_id: User identifier of the sticker set owner + :param name: Sticker set name + :param old_sticker: File identifier of the replaced sticker + :param sticker: A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged. + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = ReplaceStickerInSet( + user_id=user_id, + name=name, + old_sticker=old_sticker, + sticker=sticker, + ) + return await self(call, request_timeout=request_timeout) + + async def refund_star_payment( + self, + user_id: int, + telegram_payment_charge_id: str, + request_timeout: Optional[int] = None, + ) -> bool: + """ + Refunds a successful payment in `Telegram Stars `_. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#refundstarpayment + + :param user_id: Identifier of the user whose payment will be refunded + :param telegram_payment_charge_id: Telegram payment identifier + :param request_timeout: Request timeout + :return: Returns :code:`True` on success. + """ + + call = RefundStarPayment( + user_id=user_id, + telegram_payment_charge_id=telegram_payment_charge_id, + ) + return await self(call, request_timeout=request_timeout) + + async def get_star_transactions( + self, + offset: Optional[int] = None, + limit: Optional[int] = None, + request_timeout: Optional[int] = None, + ) -> StarTransactions: + """ + Returns the bot's Telegram Star transactions in chronological order. On success, returns a :class:`aiogram.types.star_transactions.StarTransactions` object. + + Source: https://core.telegram.org/bots/api#getstartransactions + + :param offset: Number of transactions to skip in the response + :param limit: The maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100. + :param request_timeout: Request timeout + :return: On success, returns a :class:`aiogram.types.star_transactions.StarTransactions` object. + """ + + call = GetStarTransactions( + offset=offset, + limit=limit, + ) + return await self(call, request_timeout=request_timeout) + + async def send_paid_media( + self, + chat_id: Union[int, str], + star_count: int, + media: List[Union[InputPaidMediaPhoto, InputPaidMediaVideo]], + business_connection_id: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[str] = None, + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[bool] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + request_timeout: Optional[int] = None, + ) -> Message: + """ + Use this method to send paid media. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpaidmedia + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`). If the chat is a channel, all Telegram Star proceeds from this media will be credited to the chat's balance. Otherwise, they will be credited to the bot's balance. + :param star_count: The number of Telegram Stars that must be paid to buy access to the media + :param media: A JSON-serialized array describing the media to be sent; up to 10 items + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param caption: Media caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the media caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param request_timeout: Request timeout + :return: On success, the sent :class:`aiogram.types.message.Message` is returned. + """ + + call = SendPaidMedia( + chat_id=chat_id, + star_count=star_count, + media=media, + business_connection_id=business_connection_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + disable_notification=disable_notification, + protect_content=protect_content, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + ) + return await self(call, request_timeout=request_timeout) + + async def create_chat_subscription_invite_link( + self, + chat_id: Union[int, str], + subscription_period: Union[datetime.datetime, datetime.timedelta, int], + subscription_price: int, + name: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> ChatInviteLink: + """ + Use this method to create a `subscription invite link `_ for a channel chat. The bot must have the *can_invite_users* administrator rights. The link can be edited using the method :class:`aiogram.methods.edit_chat_subscription_invite_link.EditChatSubscriptionInviteLink` or revoked using the method :class:`aiogram.methods.revoke_chat_invite_link.RevokeChatInviteLink`. Returns the new invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#createchatsubscriptioninvitelink + + :param chat_id: Unique identifier for the target channel chat or username of the target channel (in the format :code:`@channelusername`) + :param subscription_period: The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days). + :param subscription_price: The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-2500 + :param name: Invite link name; 0-32 characters + :param request_timeout: Request timeout + :return: Returns the new invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + """ + + call = CreateChatSubscriptionInviteLink( + chat_id=chat_id, + subscription_period=subscription_period, + subscription_price=subscription_price, + name=name, + ) + return await self(call, request_timeout=request_timeout) + + async def edit_chat_subscription_invite_link( + self, + chat_id: Union[int, str], + invite_link: str, + name: Optional[str] = None, + request_timeout: Optional[int] = None, + ) -> ChatInviteLink: + """ + Use this method to edit a subscription invite link created by the bot. The bot must have the *can_invite_users* administrator rights. Returns the edited invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#editchatsubscriptioninvitelink + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param invite_link: The invite link to edit + :param name: Invite link name; 0-32 characters + :param request_timeout: Request timeout + :return: Returns the edited invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + """ + + call = EditChatSubscriptionInviteLink( + chat_id=chat_id, + invite_link=invite_link, + name=name, + ) + return await self(call, request_timeout=request_timeout) diff --git a/env/Lib/site-packages/aiogram/client/context_controller.py b/env/Lib/site-packages/aiogram/client/context_controller.py new file mode 100644 index 0000000..97795a7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/context_controller.py @@ -0,0 +1,33 @@ +from typing import TYPE_CHECKING, Any, Optional + +from pydantic import BaseModel, PrivateAttr +from typing_extensions import Self + +if TYPE_CHECKING: + from aiogram.client.bot import Bot + + +class BotContextController(BaseModel): + _bot: Optional["Bot"] = PrivateAttr() + + def model_post_init(self, __context: Any) -> None: + self._bot = __context.get("bot") if __context else None + + def as_(self, bot: Optional["Bot"]) -> Self: + """ + Bind object to a bot instance. + + :param bot: Bot instance + :return: self + """ + self._bot = bot + return self + + @property + def bot(self) -> Optional["Bot"]: + """ + Get bot instance. + + :return: Bot instance + """ + return self._bot diff --git a/env/Lib/site-packages/aiogram/client/default.py b/env/Lib/site-packages/aiogram/client/default.py new file mode 100644 index 0000000..6c857be --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/default.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import sys +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Dict, Optional + +if TYPE_CHECKING: + from aiogram.types import LinkPreviewOptions + + +# @dataclass ?? +class Default: + # Is not a dataclass because of JSON serialization. + + __slots__ = ("_name",) + + def __init__(self, name: str) -> None: + self._name = name + + @property + def name(self) -> str: + return self._name + + def __str__(self) -> str: + return f"Default({self._name!r})" + + def __repr__(self) -> str: + return f"<{self}>" + + +_dataclass_properties: Dict[str, Any] = {} +if sys.version_info >= (3, 10): + # Speedup attribute access for dataclasses in Python 3.10+ + _dataclass_properties.update({"slots": True, "kw_only": True}) + + +@dataclass(**_dataclass_properties) +class DefaultBotProperties: + """ + Default bot properties. + """ + + parse_mode: Optional[str] = None + """Default parse mode for messages.""" + disable_notification: Optional[bool] = None + """Sends the message silently. Users will receive a notification with no sound.""" + protect_content: Optional[bool] = None + """Protects content from copying.""" + allow_sending_without_reply: Optional[bool] = None + """Allows to send messages without reply.""" + link_preview: Optional[LinkPreviewOptions] = None + """Link preview settings.""" + link_preview_is_disabled: Optional[bool] = None + """Disables link preview.""" + link_preview_prefer_small_media: Optional[bool] = None + """Prefer small media in link preview.""" + link_preview_prefer_large_media: Optional[bool] = None + """Prefer large media in link preview.""" + link_preview_show_above_text: Optional[bool] = None + """Show link preview above text.""" + show_caption_above_media: Optional[bool] = None + """Show caption above media.""" + + def __post_init__(self) -> None: + has_any_link_preview_option = any( + ( + self.link_preview_is_disabled, + self.link_preview_prefer_small_media, + self.link_preview_prefer_large_media, + self.link_preview_show_above_text, + ) + ) + + if has_any_link_preview_option and self.link_preview is None: + from ..types import LinkPreviewOptions + + self.link_preview = LinkPreviewOptions( + is_disabled=self.link_preview_is_disabled, + prefer_small_media=self.link_preview_prefer_small_media, + prefer_large_media=self.link_preview_prefer_large_media, + show_above_text=self.link_preview_show_above_text, + ) + + def __getitem__(self, item: str) -> Any: + return getattr(self, item, None) diff --git a/env/Lib/site-packages/aiogram/client/session/__init__.py b/env/Lib/site-packages/aiogram/client/session/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/client/session/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/session/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..b9e3c26 Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/session/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/session/__pycache__/aiohttp.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/session/__pycache__/aiohttp.cpython-311.pyc new file mode 100644 index 0000000..1f1da0f Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/session/__pycache__/aiohttp.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/session/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/session/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..4140596 Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/session/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/session/aiohttp.py b/env/Lib/site-packages/aiogram/client/session/aiohttp.py new file mode 100644 index 0000000..69f36bf --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/session/aiohttp.py @@ -0,0 +1,215 @@ +from __future__ import annotations + +import asyncio +import ssl +from typing import ( + TYPE_CHECKING, + Any, + AsyncGenerator, + Dict, + Iterable, + List, + Optional, + Tuple, + Type, + Union, + cast, +) + +import certifi +from aiohttp import BasicAuth, ClientError, ClientSession, FormData, TCPConnector +from aiohttp.hdrs import USER_AGENT +from aiohttp.http import SERVER_SOFTWARE + +from aiogram.__meta__ import __version__ +from aiogram.methods import TelegramMethod + +from ...exceptions import TelegramNetworkError +from ...methods.base import TelegramType +from ...types import InputFile +from .base import BaseSession + +if TYPE_CHECKING: + from ..bot import Bot + +_ProxyBasic = Union[str, Tuple[str, BasicAuth]] +_ProxyChain = Iterable[_ProxyBasic] +_ProxyType = Union[_ProxyChain, _ProxyBasic] + + +def _retrieve_basic(basic: _ProxyBasic) -> Dict[str, Any]: + from aiohttp_socks.utils import parse_proxy_url # type: ignore + + proxy_auth: Optional[BasicAuth] = None + + if isinstance(basic, str): + proxy_url = basic + else: + proxy_url, proxy_auth = basic + + proxy_type, host, port, username, password = parse_proxy_url(proxy_url) + if isinstance(proxy_auth, BasicAuth): + username = proxy_auth.login + password = proxy_auth.password + + return { + "proxy_type": proxy_type, + "host": host, + "port": port, + "username": username, + "password": password, + "rdns": True, + } + + +def _prepare_connector(chain_or_plain: _ProxyType) -> Tuple[Type["TCPConnector"], Dict[str, Any]]: + from aiohttp_socks import ( # type: ignore + ChainProxyConnector, + ProxyConnector, + ProxyInfo, + ) + + # since tuple is Iterable(compatible with _ProxyChain) object, we assume that + # user wants chained proxies if tuple is a pair of string(url) and BasicAuth + if isinstance(chain_or_plain, str) or ( + isinstance(chain_or_plain, tuple) and len(chain_or_plain) == 2 + ): + chain_or_plain = cast(_ProxyBasic, chain_or_plain) + return ProxyConnector, _retrieve_basic(chain_or_plain) + + chain_or_plain = cast(_ProxyChain, chain_or_plain) + infos: List[ProxyInfo] = [] + for basic in chain_or_plain: + infos.append(ProxyInfo(**_retrieve_basic(basic))) + + return ChainProxyConnector, {"proxy_infos": infos} + + +class AiohttpSession(BaseSession): + def __init__( + self, proxy: Optional[_ProxyType] = None, limit: int = 100, **kwargs: Any + ) -> None: + """ + Client session based on aiohttp. + + :param proxy: The proxy to be used for requests. Default is None. + :param limit: The total number of simultaneous connections. Default is 100. + :param kwargs: Additional keyword arguments. + """ + super().__init__(**kwargs) + + self._session: Optional[ClientSession] = None + self._connector_type: Type[TCPConnector] = TCPConnector + self._connector_init: Dict[str, Any] = { + "ssl": ssl.create_default_context(cafile=certifi.where()), + "limit": limit, + "ttl_dns_cache": 3600, # Workaround for https://github.com/aiogram/aiogram/issues/1500 + } + self._should_reset_connector = True # flag determines connector state + self._proxy: Optional[_ProxyType] = None + + if proxy is not None: + try: + self._setup_proxy_connector(proxy) + except ImportError as exc: # pragma: no cover + raise RuntimeError( + "In order to use aiohttp client for proxy requests, install " + "https://pypi.org/project/aiohttp-socks/" + ) from exc + + def _setup_proxy_connector(self, proxy: _ProxyType) -> None: + self._connector_type, self._connector_init = _prepare_connector(proxy) + self._proxy = proxy + + @property + def proxy(self) -> Optional[_ProxyType]: + return self._proxy + + @proxy.setter + def proxy(self, proxy: _ProxyType) -> None: + self._setup_proxy_connector(proxy) + self._should_reset_connector = True + + async def create_session(self) -> ClientSession: + if self._should_reset_connector: + await self.close() + + if self._session is None or self._session.closed: + self._session = ClientSession( + connector=self._connector_type(**self._connector_init), + headers={ + USER_AGENT: f"{SERVER_SOFTWARE} aiogram/{__version__}", + }, + ) + self._should_reset_connector = False + + return self._session + + async def close(self) -> None: + if self._session is not None and not self._session.closed: + await self._session.close() + + # Wait 250 ms for the underlying SSL connections to close + # https://docs.aiohttp.org/en/stable/client_advanced.html#graceful-shutdown + await asyncio.sleep(0.25) + + def build_form_data(self, bot: Bot, method: TelegramMethod[TelegramType]) -> FormData: + form = FormData(quote_fields=False) + files: Dict[str, InputFile] = {} + for key, value in method.model_dump(warnings=False).items(): + value = self.prepare_value(value, bot=bot, files=files) + if not value: + continue + form.add_field(key, value) + for key, value in files.items(): + form.add_field( + key, + value.read(bot), + filename=value.filename or key, + ) + return form + + async def make_request( + self, bot: Bot, method: TelegramMethod[TelegramType], timeout: Optional[int] = None + ) -> TelegramType: + session = await self.create_session() + + url = self.api.api_url(token=bot.token, method=method.__api_method__) + form = self.build_form_data(bot=bot, method=method) + + try: + async with session.post( + url, data=form, timeout=self.timeout if timeout is None else timeout + ) as resp: + raw_result = await resp.text() + except asyncio.TimeoutError: + raise TelegramNetworkError(method=method, message="Request timeout error") + except ClientError as e: + raise TelegramNetworkError(method=method, message=f"{type(e).__name__}: {e}") + response = self.check_response( + bot=bot, method=method, status_code=resp.status, content=raw_result + ) + return cast(TelegramType, response.result) + + async def stream_content( + self, + url: str, + headers: Optional[Dict[str, Any]] = None, + timeout: int = 30, + chunk_size: int = 65536, + raise_for_status: bool = True, + ) -> AsyncGenerator[bytes, None]: + if headers is None: + headers = {} + + session = await self.create_session() + + async with session.get( + url, timeout=timeout, headers=headers, raise_for_status=raise_for_status + ) as resp: + async for chunk in resp.content.iter_chunked(chunk_size): + yield chunk + + async def __aenter__(self) -> AiohttpSession: + await self.create_session() + return self diff --git a/env/Lib/site-packages/aiogram/client/session/base.py b/env/Lib/site-packages/aiogram/client/session/base.py new file mode 100644 index 0000000..82ec469 --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/session/base.py @@ -0,0 +1,265 @@ +from __future__ import annotations + +import abc +import datetime +import json +import secrets +from enum import Enum +from http import HTTPStatus +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + AsyncGenerator, + Callable, + Dict, + Final, + Optional, + Type, + cast, +) + +from pydantic import ValidationError + +from aiogram.exceptions import ( + ClientDecodeError, + RestartingTelegram, + TelegramAPIError, + TelegramBadRequest, + TelegramConflictError, + TelegramEntityTooLarge, + TelegramForbiddenError, + TelegramMigrateToChat, + TelegramNotFound, + TelegramRetryAfter, + TelegramServerError, + TelegramUnauthorizedError, +) + +from ...methods import Response, TelegramMethod +from ...methods.base import TelegramType +from ...types import InputFile, TelegramObject +from ..default import Default +from ..telegram import PRODUCTION, TelegramAPIServer +from .middlewares.manager import RequestMiddlewareManager + +if TYPE_CHECKING: + from ..bot import Bot + +_JsonLoads = Callable[..., Any] +_JsonDumps = Callable[..., str] + +DEFAULT_TIMEOUT: Final[float] = 60.0 + + +class BaseSession(abc.ABC): + """ + This is base class for all HTTP sessions in aiogram. + + If you want to create your own session, you must inherit from this class. + """ + + def __init__( + self, + api: TelegramAPIServer = PRODUCTION, + json_loads: _JsonLoads = json.loads, + json_dumps: _JsonDumps = json.dumps, + timeout: float = DEFAULT_TIMEOUT, + ) -> None: + """ + + :param api: Telegram Bot API URL patterns + :param json_loads: JSON loader + :param json_dumps: JSON dumper + :param timeout: Session scope request timeout + """ + self.api = api + self.json_loads = json_loads + self.json_dumps = json_dumps + self.timeout = timeout + + self.middleware = RequestMiddlewareManager() + + def check_response( + self, bot: Bot, method: TelegramMethod[TelegramType], status_code: int, content: str + ) -> Response[TelegramType]: + """ + Check response status + """ + try: + json_data = self.json_loads(content) + except Exception as e: + # Handled error type can't be classified as specific error + # in due to decoder can be customized and raise any exception + + raise ClientDecodeError("Failed to decode object", e, content) + + try: + response_type = Response[method.__returning__] # type: ignore + response = response_type.model_validate(json_data, context={"bot": bot}) + except ValidationError as e: + raise ClientDecodeError("Failed to deserialize object", e, json_data) + + if HTTPStatus.OK <= status_code <= HTTPStatus.IM_USED and response.ok: + return response + + description = cast(str, response.description) + + if parameters := response.parameters: + if parameters.retry_after: + raise TelegramRetryAfter( + method=method, message=description, retry_after=parameters.retry_after + ) + if parameters.migrate_to_chat_id: + raise TelegramMigrateToChat( + method=method, + message=description, + migrate_to_chat_id=parameters.migrate_to_chat_id, + ) + if status_code == HTTPStatus.BAD_REQUEST: + raise TelegramBadRequest(method=method, message=description) + if status_code == HTTPStatus.NOT_FOUND: + raise TelegramNotFound(method=method, message=description) + if status_code == HTTPStatus.CONFLICT: + raise TelegramConflictError(method=method, message=description) + if status_code == HTTPStatus.UNAUTHORIZED: + raise TelegramUnauthorizedError(method=method, message=description) + if status_code == HTTPStatus.FORBIDDEN: + raise TelegramForbiddenError(method=method, message=description) + if status_code == HTTPStatus.REQUEST_ENTITY_TOO_LARGE: + raise TelegramEntityTooLarge(method=method, message=description) + if status_code >= HTTPStatus.INTERNAL_SERVER_ERROR: + if "restart" in description: + raise RestartingTelegram(method=method, message=description) + raise TelegramServerError(method=method, message=description) + + raise TelegramAPIError( + method=method, + message=description, + ) + + @abc.abstractmethod + async def close(self) -> None: # pragma: no cover + """ + Close client session + """ + pass + + @abc.abstractmethod + async def make_request( + self, + bot: Bot, + method: TelegramMethod[TelegramType], + timeout: Optional[int] = None, + ) -> TelegramType: # pragma: no cover + """ + Make request to Telegram Bot API + + :param bot: Bot instance + :param method: Method instance + :param timeout: Request timeout + :return: + :raise TelegramApiError: + """ + pass + + @abc.abstractmethod + async def stream_content( + self, + url: str, + headers: Optional[Dict[str, Any]] = None, + timeout: int = 30, + chunk_size: int = 65536, + raise_for_status: bool = True, + ) -> AsyncGenerator[bytes, None]: # pragma: no cover + """ + Stream reader + """ + yield b"" + + def prepare_value( + self, + value: Any, + bot: Bot, + files: Dict[str, Any], + _dumps_json: bool = True, + ) -> Any: + """ + Prepare value before send + """ + if value is None: + return None + if isinstance(value, str): + return value + if isinstance(value, Default): + default_value = bot.default[value.name] + return self.prepare_value(default_value, bot=bot, files=files, _dumps_json=_dumps_json) + if isinstance(value, InputFile): + key = secrets.token_urlsafe(10) + files[key] = value + return f"attach://{key}" + if isinstance(value, dict): + value = { + key: prepared_item + for key, item in value.items() + if ( + prepared_item := self.prepare_value( + item, bot=bot, files=files, _dumps_json=False + ) + ) + is not None + } + if _dumps_json: + return self.json_dumps(value) + return value + if isinstance(value, list): + value = [ + prepared_item + for item in value + if ( + prepared_item := self.prepare_value( + item, bot=bot, files=files, _dumps_json=False + ) + ) + is not None + ] + if _dumps_json: + return self.json_dumps(value) + return value + if isinstance(value, datetime.timedelta): + now = datetime.datetime.now() + return str(round((now + value).timestamp())) + if isinstance(value, datetime.datetime): + return str(round(value.timestamp())) + if isinstance(value, Enum): + return self.prepare_value(value.value, bot=bot, files=files) + if isinstance(value, TelegramObject): + return self.prepare_value( + value.model_dump(warnings=False), + bot=bot, + files=files, + _dumps_json=_dumps_json, + ) + if _dumps_json: + return self.json_dumps(value) + return value + + async def __call__( + self, + bot: Bot, + method: TelegramMethod[TelegramType], + timeout: Optional[int] = None, + ) -> TelegramType: + middleware = self.middleware.wrap_middlewares(self.make_request, timeout=timeout) + return cast(TelegramType, await middleware(bot, method)) + + async def __aenter__(self) -> BaseSession: + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + await self.close() diff --git a/env/Lib/site-packages/aiogram/client/session/middlewares/__init__.py b/env/Lib/site-packages/aiogram/client/session/middlewares/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..e13aa3e Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..1ecc3ee Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/manager.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/manager.cpython-311.pyc new file mode 100644 index 0000000..f5fe65b Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/manager.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/request_logging.cpython-311.pyc b/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/request_logging.cpython-311.pyc new file mode 100644 index 0000000..1a91f75 Binary files /dev/null and b/env/Lib/site-packages/aiogram/client/session/middlewares/__pycache__/request_logging.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/client/session/middlewares/base.py b/env/Lib/site-packages/aiogram/client/session/middlewares/base.py new file mode 100644 index 0000000..c5f3e7c --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/session/middlewares/base.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Protocol + +from aiogram.methods import Response, TelegramMethod +from aiogram.methods.base import TelegramType + +if TYPE_CHECKING: + from ...bot import Bot + + +class NextRequestMiddlewareType(Protocol[TelegramType]): # pragma: no cover + async def __call__( + self, + bot: "Bot", + method: TelegramMethod[TelegramType], + ) -> Response[TelegramType]: + pass + + +class RequestMiddlewareType(Protocol): # pragma: no cover + async def __call__( + self, + make_request: NextRequestMiddlewareType[TelegramType], + bot: "Bot", + method: TelegramMethod[TelegramType], + ) -> Response[TelegramType]: + pass + + +class BaseRequestMiddleware(ABC): + """ + Generic middleware class + """ + + @abstractmethod + async def __call__( + self, + make_request: NextRequestMiddlewareType[TelegramType], + bot: "Bot", + method: TelegramMethod[TelegramType], + ) -> Response[TelegramType]: + """ + Execute middleware + + :param make_request: Wrapped make_request in middlewares chain + :param bot: bot for request making + :param method: Request method (Subclass of :class:`aiogram.methods.base.TelegramMethod`) + + :return: :class:`aiogram.methods.Response` + """ + pass diff --git a/env/Lib/site-packages/aiogram/client/session/middlewares/manager.py b/env/Lib/site-packages/aiogram/client/session/middlewares/manager.py new file mode 100644 index 0000000..2346715 --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/session/middlewares/manager.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from functools import partial +from typing import Any, Callable, List, Optional, Sequence, Union, cast, overload + +from aiogram.client.session.middlewares.base import ( + NextRequestMiddlewareType, + RequestMiddlewareType, +) +from aiogram.methods.base import TelegramType + + +class RequestMiddlewareManager(Sequence[RequestMiddlewareType]): + def __init__(self) -> None: + self._middlewares: List[RequestMiddlewareType] = [] + + def register( + self, + middleware: RequestMiddlewareType, + ) -> RequestMiddlewareType: + self._middlewares.append(middleware) + return middleware + + def unregister(self, middleware: RequestMiddlewareType) -> None: + self._middlewares.remove(middleware) + + def __call__( + self, + middleware: Optional[RequestMiddlewareType] = None, + ) -> Union[ + Callable[[RequestMiddlewareType], RequestMiddlewareType], + RequestMiddlewareType, + ]: + if middleware is None: + return self.register + return self.register(middleware) + + @overload + def __getitem__(self, item: int) -> RequestMiddlewareType: + pass + + @overload + def __getitem__(self, item: slice) -> Sequence[RequestMiddlewareType]: + pass + + def __getitem__( + self, item: Union[int, slice] + ) -> Union[RequestMiddlewareType, Sequence[RequestMiddlewareType]]: + return self._middlewares[item] + + def __len__(self) -> int: + return len(self._middlewares) + + def wrap_middlewares( + self, + callback: NextRequestMiddlewareType[TelegramType], + **kwargs: Any, + ) -> NextRequestMiddlewareType[TelegramType]: + middleware = partial(callback, **kwargs) + for m in reversed(self._middlewares): + middleware = partial(m, middleware) + return cast(NextRequestMiddlewareType[TelegramType], middleware) diff --git a/env/Lib/site-packages/aiogram/client/session/middlewares/request_logging.py b/env/Lib/site-packages/aiogram/client/session/middlewares/request_logging.py new file mode 100644 index 0000000..af7b9d6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/session/middlewares/request_logging.py @@ -0,0 +1,37 @@ +import logging +from typing import TYPE_CHECKING, Any, List, Optional, Type + +from aiogram import loggers +from aiogram.methods import TelegramMethod +from aiogram.methods.base import Response, TelegramType + +from .base import BaseRequestMiddleware, NextRequestMiddlewareType + +if TYPE_CHECKING: + from ...bot import Bot + +logger = logging.getLogger(__name__) + + +class RequestLogging(BaseRequestMiddleware): + def __init__(self, ignore_methods: Optional[List[Type[TelegramMethod[Any]]]] = None): + """ + Middleware for logging outgoing requests + + :param ignore_methods: methods to ignore in logging middleware + """ + self.ignore_methods = ignore_methods if ignore_methods else [] + + async def __call__( + self, + make_request: NextRequestMiddlewareType[TelegramType], + bot: "Bot", + method: TelegramMethod[TelegramType], + ) -> Response[TelegramType]: + if type(method) not in self.ignore_methods: + loggers.middlewares.info( + "Make request with method=%r by bot id=%d", + type(method).__name__, + bot.id, + ) + return await make_request(bot, method) diff --git a/env/Lib/site-packages/aiogram/client/telegram.py b/env/Lib/site-packages/aiogram/client/telegram.py new file mode 100644 index 0000000..5e29722 --- /dev/null +++ b/env/Lib/site-packages/aiogram/client/telegram.py @@ -0,0 +1,103 @@ +from abc import ABC, abstractmethod +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Union + + +class FilesPathWrapper(ABC): + @abstractmethod + def to_local(self, path: Union[Path, str]) -> Union[Path, str]: + pass + + @abstractmethod + def to_server(self, path: Union[Path, str]) -> Union[Path, str]: + pass + + +class BareFilesPathWrapper(FilesPathWrapper): + def to_local(self, path: Union[Path, str]) -> Union[Path, str]: + return path + + def to_server(self, path: Union[Path, str]) -> Union[Path, str]: + return path + + +class SimpleFilesPathWrapper(FilesPathWrapper): + def __init__(self, server_path: Path, local_path: Path) -> None: + self.server_path = server_path + self.local_path = local_path + + @classmethod + def _resolve( + cls, base1: Union[Path, str], base2: Union[Path, str], value: Union[Path, str] + ) -> Path: + relative = Path(value).relative_to(base1) + return base2 / relative + + def to_local(self, path: Union[Path, str]) -> Union[Path, str]: + return self._resolve(base1=self.server_path, base2=self.local_path, value=path) + + def to_server(self, path: Union[Path, str]) -> Union[Path, str]: + return self._resolve(base1=self.local_path, base2=self.server_path, value=path) + + +@dataclass(frozen=True) +class TelegramAPIServer: + """ + Base config for API Endpoints + """ + + base: str + """Base URL""" + file: str + """Files URL""" + is_local: bool = False + """Mark this server is + in `local mode `_.""" + wrap_local_file: FilesPathWrapper = BareFilesPathWrapper() + """Callback to wrap files path in local mode""" + + def api_url(self, token: str, method: str) -> str: + """ + Generate URL for API methods + + :param token: Bot token + :param method: API method name (case insensitive) + :return: URL + """ + return self.base.format(token=token, method=method) + + def file_url(self, token: str, path: str) -> str: + """ + Generate URL for downloading files + + :param token: Bot token + :param path: file path + :return: URL + """ + return self.file.format(token=token, path=path) + + @classmethod + def from_base(cls, base: str, **kwargs: Any) -> "TelegramAPIServer": + """ + Use this method to auto-generate TelegramAPIServer instance from base URL + + :param base: Base URL + :return: instance of :class:`TelegramAPIServer` + """ + base = base.rstrip("/") + return cls( + base=f"{base}/bot{{token}}/{{method}}", + file=f"{base}/file/bot{{token}}/{{path}}", + **kwargs, + ) + + +PRODUCTION = TelegramAPIServer( + base="https://api.telegram.org/bot{token}/{method}", + file="https://api.telegram.org/file/bot{token}/{path}", +) +TEST = TelegramAPIServer( + base="https://api.telegram.org/bot{token}/test/{method}", + file="https://api.telegram.org/file/bot{token}/test/{path}", +) diff --git a/env/Lib/site-packages/aiogram/dispatcher/__init__.py b/env/Lib/site-packages/aiogram/dispatcher/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/dispatcher/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..f299e3c Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/__pycache__/dispatcher.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/__pycache__/dispatcher.cpython-311.pyc new file mode 100644 index 0000000..75a1afa Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/__pycache__/dispatcher.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/__pycache__/flags.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/__pycache__/flags.cpython-311.pyc new file mode 100644 index 0000000..cc8a68e Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/__pycache__/flags.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/__pycache__/router.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/__pycache__/router.cpython-311.pyc new file mode 100644 index 0000000..3956fa5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/__pycache__/router.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/dispatcher.py b/env/Lib/site-packages/aiogram/dispatcher/dispatcher.py new file mode 100644 index 0000000..8b6987c --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/dispatcher.py @@ -0,0 +1,598 @@ +from __future__ import annotations + +import asyncio +import contextvars +import signal +import warnings +from asyncio import CancelledError, Event, Future, Lock +from contextlib import suppress +from typing import Any, AsyncGenerator, Dict, List, Optional, Set, Union + +from .. import loggers +from ..client.bot import Bot +from ..exceptions import TelegramAPIError +from ..fsm.middleware import FSMContextMiddleware +from ..fsm.storage.base import BaseEventIsolation, BaseStorage +from ..fsm.storage.memory import DisabledEventIsolation, MemoryStorage +from ..fsm.strategy import FSMStrategy +from ..methods import GetUpdates, TelegramMethod +from ..methods.base import TelegramType +from ..types import Update, User +from ..types.base import UNSET, UNSET_TYPE +from ..types.update import UpdateTypeLookupError +from ..utils.backoff import Backoff, BackoffConfig +from .event.bases import UNHANDLED, SkipHandler +from .event.telegram import TelegramEventObserver +from .middlewares.error import ErrorsMiddleware +from .middlewares.user_context import UserContextMiddleware +from .router import Router + +DEFAULT_BACKOFF_CONFIG = BackoffConfig(min_delay=1.0, max_delay=5.0, factor=1.3, jitter=0.1) + + +class Dispatcher(Router): + """ + Root router + """ + + def __init__( + self, + *, # * - Preventing to pass instance of Bot to the FSM storage + storage: Optional[BaseStorage] = None, + fsm_strategy: FSMStrategy = FSMStrategy.USER_IN_CHAT, + events_isolation: Optional[BaseEventIsolation] = None, + disable_fsm: bool = False, + name: Optional[str] = None, + **kwargs: Any, + ) -> None: + """ + Root router + + :param storage: Storage for FSM + :param fsm_strategy: FSM strategy + :param events_isolation: Events isolation + :param disable_fsm: Disable FSM, note that if you disable FSM + then you should not use storage and events isolation + :param kwargs: Other arguments, will be passed as keyword arguments to handlers + """ + super(Dispatcher, self).__init__(name=name) + + if storage and not isinstance(storage, BaseStorage): + raise TypeError( + f"FSM storage should be instance of 'BaseStorage' not {type(storage).__name__}" + ) + + # Telegram API provides originally only one event type - Update + # For making easily interactions with events here is registered handler which helps + # to separate Update to different event types like Message, CallbackQuery etc. + self.update = self.observers["update"] = TelegramEventObserver( + router=self, event_name="update" + ) + self.update.register(self._listen_update) + + # Error handlers should work is out of all other functions + # and should be registered before all others middlewares + self.update.outer_middleware(ErrorsMiddleware(self)) + + # User context middleware makes small optimization for all other builtin + # middlewares via caching the user and chat instances in the event context + self.update.outer_middleware(UserContextMiddleware()) + + # FSM middleware should always be registered after User context middleware + # because here is used context from previous step + self.fsm = FSMContextMiddleware( + storage=storage or MemoryStorage(), + strategy=fsm_strategy, + events_isolation=events_isolation or DisabledEventIsolation(), + ) + if not disable_fsm: + # Note that when FSM middleware is disabled, the event isolation is also disabled + # Because the isolation mechanism is a part of the FSM + self.update.outer_middleware(self.fsm) + self.shutdown.register(self.fsm.close) + + self.workflow_data: Dict[str, Any] = kwargs + self._running_lock = Lock() + self._stop_signal: Optional[Event] = None + self._stopped_signal: Optional[Event] = None + self._handle_update_tasks: Set[asyncio.Task[Any]] = set() + + def __getitem__(self, item: str) -> Any: + return self.workflow_data[item] + + def __setitem__(self, key: str, value: Any) -> None: + self.workflow_data[key] = value + + def __delitem__(self, key: str) -> None: + del self.workflow_data[key] + + def get(self, key: str, /, default: Optional[Any] = None) -> Optional[Any]: + return self.workflow_data.get(key, default) + + @property + def storage(self) -> BaseStorage: + return self.fsm.storage + + @property + def parent_router(self) -> Optional[Router]: + """ + Dispatcher has no parent router and can't be included to any other routers or dispatchers + + :return: + """ + return None # noqa: RET501 + + @parent_router.setter + def parent_router(self, value: Router) -> None: + """ + Dispatcher is root Router then configuring parent router is not allowed + + :param value: + :return: + """ + raise RuntimeError("Dispatcher can not be attached to another Router.") + + async def feed_update(self, bot: Bot, update: Update, **kwargs: Any) -> Any: + """ + Main entry point for incoming updates + Response of this method can be used as Webhook response + + :param bot: + :param update: + """ + loop = asyncio.get_running_loop() + handled = False + start_time = loop.time() + + if update.bot != bot: + # Re-mounting update to the current bot instance for making possible to + # use it in shortcuts. + # Here is update is re-created because we need to propagate context to + # all nested objects and attributes of the Update, but it + # is impossible without roundtrip to JSON :( + # The preferred way is that pass already mounted Bot instance to this update + # before call feed_update method + update = Update.model_validate(update.model_dump(), context={"bot": bot}) + + try: + response = await self.update.wrap_outer_middleware( + self.update.trigger, + update, + { + **self.workflow_data, + **kwargs, + "bot": bot, + }, + ) + handled = response is not UNHANDLED + return response + finally: + finish_time = loop.time() + duration = (finish_time - start_time) * 1000 + loggers.event.info( + "Update id=%s is %s. Duration %d ms by bot id=%d", + update.update_id, + "handled" if handled else "not handled", + duration, + bot.id, + ) + + async def feed_raw_update(self, bot: Bot, update: Dict[str, Any], **kwargs: Any) -> Any: + """ + Main entry point for incoming updates with automatic Dict->Update serializer + + :param bot: + :param update: + :param kwargs: + """ + parsed_update = Update.model_validate(update, context={"bot": bot}) + return await self._feed_webhook_update(bot=bot, update=parsed_update, **kwargs) + + @classmethod + async def _listen_updates( + cls, + bot: Bot, + polling_timeout: int = 30, + backoff_config: BackoffConfig = DEFAULT_BACKOFF_CONFIG, + allowed_updates: Optional[List[str]] = None, + ) -> AsyncGenerator[Update, None]: + """ + Endless updates reader with correctly handling any server-side or connection errors. + + So you may not worry that the polling will stop working. + """ + backoff = Backoff(config=backoff_config) + get_updates = GetUpdates(timeout=polling_timeout, allowed_updates=allowed_updates) + kwargs = {} + if bot.session.timeout: + # Request timeout can be lower than session timeout and that's OK. + # To prevent false-positive TimeoutError we should wait longer than polling timeout + kwargs["request_timeout"] = int(bot.session.timeout + polling_timeout) + failed = False + while True: + try: + updates = await bot(get_updates, **kwargs) + except Exception as e: + failed = True + # In cases when Telegram Bot API was inaccessible don't need to stop polling + # process because some developers can't make auto-restarting of the script + loggers.dispatcher.error("Failed to fetch updates - %s: %s", type(e).__name__, e) + # And also backoff timeout is best practice to retry any network activity + loggers.dispatcher.warning( + "Sleep for %f seconds and try again... (tryings = %d, bot id = %d)", + backoff.next_delay, + backoff.counter, + bot.id, + ) + await backoff.asleep() + continue + + # In case when network connection was fixed let's reset the backoff + # to initial value and then process updates + if failed: + loggers.dispatcher.info( + "Connection established (tryings = %d, bot id = %d)", + backoff.counter, + bot.id, + ) + backoff.reset() + failed = False + + for update in updates: + yield update + # The getUpdates method returns the earliest 100 unconfirmed updates. + # To confirm an update, use the offset parameter when calling getUpdates + # All updates with update_id less than or equal to offset will be marked + # as confirmed on the server and will no longer be returned. + get_updates.offset = update.update_id + 1 + + async def _listen_update(self, update: Update, **kwargs: Any) -> Any: + """ + Main updates listener + + Workflow: + - Detect content type and propagate to observers in current router + - If no one filter is pass - propagate update to child routers as Update + + :param update: + :param kwargs: + :return: + """ + try: + update_type = update.event_type + event = update.event + except UpdateTypeLookupError as e: + warnings.warn( + "Detected unknown update type.\n" + "Seems like Telegram Bot API was updated and you have " + "installed not latest version of aiogram framework" + f"\nUpdate: {update.model_dump_json(exclude_unset=True)}", + RuntimeWarning, + ) + raise SkipHandler() from e + + kwargs.update(event_update=update) + + return await self.propagate_event(update_type=update_type, event=event, **kwargs) + + @classmethod + async def silent_call_request(cls, bot: Bot, result: TelegramMethod[Any]) -> None: + """ + Simulate answer into WebHook + + :param bot: + :param result: + :return: + """ + try: + await bot(result) + except TelegramAPIError as e: + # In due to WebHook mechanism doesn't allow getting response for + # requests called in answer to WebHook request. + # Need to skip unsuccessful responses. + # For debugging here is added logging. + loggers.event.error("Failed to make answer: %s: %s", e.__class__.__name__, e) + + async def _process_update( + self, bot: Bot, update: Update, call_answer: bool = True, **kwargs: Any + ) -> bool: + """ + Propagate update to event listeners + + :param bot: instance of Bot + :param update: instance of Update + :param call_answer: need to execute response as Telegram method (like answer into webhook) + :param kwargs: contextual data for middlewares, filters and handlers + :return: status + """ + try: + response = await self.feed_update(bot, update, **kwargs) + if call_answer and isinstance(response, TelegramMethod): + await self.silent_call_request(bot=bot, result=response) + return response is not UNHANDLED + + except Exception as e: + loggers.event.exception( + "Cause exception while process update id=%d by bot id=%d\n%s: %s", + update.update_id, + bot.id, + e.__class__.__name__, + e, + ) + return True # because update was processed but unsuccessful + + async def _polling( + self, + bot: Bot, + polling_timeout: int = 30, + handle_as_tasks: bool = True, + backoff_config: BackoffConfig = DEFAULT_BACKOFF_CONFIG, + allowed_updates: Optional[List[str]] = None, + **kwargs: Any, + ) -> None: + """ + Internal polling process + + :param bot: + :param kwargs: + :return: + """ + user: User = await bot.me() + loggers.dispatcher.info( + "Run polling for bot @%s id=%d - %r", user.username, bot.id, user.full_name + ) + try: + async for update in self._listen_updates( + bot, + polling_timeout=polling_timeout, + backoff_config=backoff_config, + allowed_updates=allowed_updates, + ): + handle_update = self._process_update(bot=bot, update=update, **kwargs) + if handle_as_tasks: + handle_update_task = asyncio.create_task(handle_update) + self._handle_update_tasks.add(handle_update_task) + handle_update_task.add_done_callback(self._handle_update_tasks.discard) + else: + await handle_update + finally: + loggers.dispatcher.info( + "Polling stopped for bot @%s id=%d - %r", user.username, bot.id, user.full_name + ) + + async def _feed_webhook_update(self, bot: Bot, update: Update, **kwargs: Any) -> Any: + """ + The same with `Dispatcher.process_update()` but returns real response instead of bool + """ + try: + return await self.feed_update(bot, update, **kwargs) + except Exception as e: + loggers.event.exception( + "Cause exception while process update id=%d by bot id=%d\n%s: %s", + update.update_id, + bot.id, + e.__class__.__name__, + e, + ) + raise + + async def feed_webhook_update( + self, bot: Bot, update: Union[Update, Dict[str, Any]], _timeout: float = 55, **kwargs: Any + ) -> Optional[TelegramMethod[TelegramType]]: + if not isinstance(update, Update): # Allow to use raw updates + update = Update.model_validate(update, context={"bot": bot}) + + ctx = contextvars.copy_context() + loop = asyncio.get_running_loop() + waiter = loop.create_future() + + def release_waiter(*_: Any) -> None: + if not waiter.done(): + waiter.set_result(None) + + timeout_handle = loop.call_later(_timeout, release_waiter) + + process_updates: Future[Any] = asyncio.ensure_future( + self._feed_webhook_update(bot=bot, update=update, **kwargs) + ) + process_updates.add_done_callback(release_waiter, context=ctx) + + def process_response(task: Future[Any]) -> None: + warnings.warn( + "Detected slow response into webhook.\n" + "Telegram is waiting for response only first 60 seconds and then re-send update.\n" + "For preventing this situation response into webhook returned immediately " + "and handler is moved to background and still processing update.", + RuntimeWarning, + ) + try: + result = task.result() + except Exception as e: + raise e + if isinstance(result, TelegramMethod): + asyncio.ensure_future(self.silent_call_request(bot=bot, result=result)) + + try: + try: + await waiter + except CancelledError: # pragma: no cover + process_updates.remove_done_callback(release_waiter) + process_updates.cancel() + raise + + if process_updates.done(): + # TODO: handle exceptions + response: Any = process_updates.result() + if isinstance(response, TelegramMethod): + return response + + else: + process_updates.remove_done_callback(release_waiter) + process_updates.add_done_callback(process_response, context=ctx) + + finally: + timeout_handle.cancel() + + return None + + async def stop_polling(self) -> None: + """ + Execute this method if you want to stop polling programmatically + + :return: + """ + if not self._running_lock.locked(): + raise RuntimeError("Polling is not started") + if not self._stop_signal or not self._stopped_signal: + return + self._stop_signal.set() + await self._stopped_signal.wait() + + def _signal_stop_polling(self, sig: signal.Signals) -> None: + if not self._running_lock.locked(): + return + + loggers.dispatcher.warning("Received %s signal", sig.name) + if not self._stop_signal: + return + self._stop_signal.set() + + async def start_polling( + self, + *bots: Bot, + polling_timeout: int = 10, + handle_as_tasks: bool = True, + backoff_config: BackoffConfig = DEFAULT_BACKOFF_CONFIG, + allowed_updates: Optional[Union[List[str], UNSET_TYPE]] = UNSET, + handle_signals: bool = True, + close_bot_session: bool = True, + **kwargs: Any, + ) -> None: + """ + Polling runner + + :param bots: Bot instances (one or more) + :param polling_timeout: Long-polling wait time + :param handle_as_tasks: Run task for each event and no wait result + :param backoff_config: backoff-retry config + :param allowed_updates: List of the update types you want your bot to receive + By default, all used update types are enabled (resolved from handlers) + :param handle_signals: handle signals (SIGINT/SIGTERM) + :param close_bot_session: close bot sessions on shutdown + :param kwargs: contextual data + :return: + """ + if not bots: + raise ValueError("At least one bot instance is required to start polling") + if "bot" in kwargs: + raise ValueError( + "Keyword argument 'bot' is not acceptable, " + "the bot instance should be passed as positional argument" + ) + + async with self._running_lock: # Prevent to run this method twice at a once + if self._stop_signal is None: + self._stop_signal = Event() + if self._stopped_signal is None: + self._stopped_signal = Event() + + if allowed_updates is UNSET: + allowed_updates = self.resolve_used_update_types() + + self._stop_signal.clear() + self._stopped_signal.clear() + + if handle_signals: + loop = asyncio.get_running_loop() + with suppress(NotImplementedError): # pragma: no cover + # Signals handling is not supported on Windows + # It also can't be covered on Windows + loop.add_signal_handler( + signal.SIGTERM, self._signal_stop_polling, signal.SIGTERM + ) + loop.add_signal_handler( + signal.SIGINT, self._signal_stop_polling, signal.SIGINT + ) + + workflow_data = { + "dispatcher": self, + "bots": bots, + **self.workflow_data, + **kwargs, + } + if "bot" in workflow_data: + workflow_data.pop("bot") + + await self.emit_startup(bot=bots[-1], **workflow_data) + loggers.dispatcher.info("Start polling") + try: + tasks: List[asyncio.Task[Any]] = [ + asyncio.create_task( + self._polling( + bot=bot, + handle_as_tasks=handle_as_tasks, + polling_timeout=polling_timeout, + backoff_config=backoff_config, + allowed_updates=allowed_updates, + **workflow_data, + ) + ) + for bot in bots + ] + tasks.append(asyncio.create_task(self._stop_signal.wait())) + done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + + for task in pending: + # (mostly) Graceful shutdown unfinished tasks + task.cancel() + with suppress(CancelledError): + await task + # Wait finished tasks to propagate unhandled exceptions + await asyncio.gather(*done) + + finally: + loggers.dispatcher.info("Polling stopped") + try: + await self.emit_shutdown(bot=bots[-1], **workflow_data) + finally: + if close_bot_session: + await asyncio.gather(*(bot.session.close() for bot in bots)) + self._stopped_signal.set() + + def run_polling( + self, + *bots: Bot, + polling_timeout: int = 10, + handle_as_tasks: bool = True, + backoff_config: BackoffConfig = DEFAULT_BACKOFF_CONFIG, + allowed_updates: Optional[Union[List[str], UNSET_TYPE]] = UNSET, + handle_signals: bool = True, + close_bot_session: bool = True, + **kwargs: Any, + ) -> None: + """ + Run many bots with polling + + :param bots: Bot instances (one or more) + :param polling_timeout: Long-polling wait time + :param handle_as_tasks: Run task for each event and no wait result + :param backoff_config: backoff-retry config + :param allowed_updates: List of the update types you want your bot to receive + :param handle_signals: handle signals (SIGINT/SIGTERM) + :param close_bot_session: close bot sessions on shutdown + :param kwargs: contextual data + :return: + """ + with suppress(KeyboardInterrupt): + return asyncio.run( + self.start_polling( + *bots, + **kwargs, + polling_timeout=polling_timeout, + handle_as_tasks=handle_as_tasks, + backoff_config=backoff_config, + allowed_updates=allowed_updates, + handle_signals=handle_signals, + close_bot_session=close_bot_session, + ) + ) diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/__init__.py b/env/Lib/site-packages/aiogram/dispatcher/event/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..86e914c Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/bases.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/bases.cpython-311.pyc new file mode 100644 index 0000000..b11bc82 Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/bases.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/event.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/event.cpython-311.pyc new file mode 100644 index 0000000..4e1b355 Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/event.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/handler.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/handler.cpython-311.pyc new file mode 100644 index 0000000..f389527 Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/handler.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/telegram.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/telegram.cpython-311.pyc new file mode 100644 index 0000000..eb29919 Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/event/__pycache__/telegram.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/bases.py b/env/Lib/site-packages/aiogram/dispatcher/event/bases.py new file mode 100644 index 0000000..1765683 --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/event/bases.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import Any, Awaitable, Callable, Dict, NoReturn, Optional, TypeVar, Union +from unittest.mock import sentinel + +from ...types import TelegramObject +from ..middlewares.base import BaseMiddleware + +MiddlewareEventType = TypeVar("MiddlewareEventType", bound=TelegramObject) +NextMiddlewareType = Callable[[MiddlewareEventType, Dict[str, Any]], Awaitable[Any]] +MiddlewareType = Union[ + BaseMiddleware, + Callable[ + [NextMiddlewareType[MiddlewareEventType], MiddlewareEventType, Dict[str, Any]], + Awaitable[Any], + ], +] + +UNHANDLED = sentinel.UNHANDLED +REJECTED = sentinel.REJECTED + + +class SkipHandler(Exception): + pass + + +class CancelHandler(Exception): + pass + + +def skip(message: Optional[str] = None) -> NoReturn: + """ + Raise an SkipHandler + """ + raise SkipHandler(message or "Event skipped") diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/event.py b/env/Lib/site-packages/aiogram/dispatcher/event/event.py new file mode 100644 index 0000000..3cbcffe --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/event/event.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from typing import Any, Callable, List + +from .handler import CallbackType, HandlerObject + + +class EventObserver: + """ + Simple events observer + + Is used for managing events is not related with Telegram + (For example startup/shutdown processes) + + Handlers can be registered via decorator or method + + .. code-block:: python + + .register(my_handler) + + .. code-block:: python + + @() + async def my_handler(*args, **kwargs): ... + """ + + def __init__(self) -> None: + self.handlers: List[HandlerObject] = [] + + def register(self, callback: CallbackType) -> None: + """ + Register callback with filters + """ + self.handlers.append(HandlerObject(callback=callback)) + + async def trigger(self, *args: Any, **kwargs: Any) -> None: + """ + Propagate event to handlers. + Handler will be called when all its filters is pass. + """ + for handler in self.handlers: + await handler.call(*args, **kwargs) + + def __call__(self) -> Callable[[CallbackType], CallbackType]: + """ + Decorator for registering event handlers + """ + + def wrapper(callback: CallbackType) -> CallbackType: + self.register(callback) + return callback + + return wrapper diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/handler.py b/env/Lib/site-packages/aiogram/dispatcher/event/handler.py new file mode 100644 index 0000000..8c283dd --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/event/handler.py @@ -0,0 +1,99 @@ +import asyncio +import contextvars +import inspect +import warnings +from dataclasses import dataclass, field +from functools import partial +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +from magic_filter.magic import MagicFilter as OriginalMagicFilter + +from aiogram.dispatcher.flags import extract_flags_from_object +from aiogram.filters.base import Filter +from aiogram.handlers import BaseHandler +from aiogram.utils.magic_filter import MagicFilter +from aiogram.utils.warnings import Recommendation + +CallbackType = Callable[..., Any] + + +@dataclass +class CallableObject: + callback: CallbackType + awaitable: bool = field(init=False) + params: Set[str] = field(init=False) + varkw: bool = field(init=False) + + def __post_init__(self) -> None: + callback = inspect.unwrap(self.callback) + self.awaitable = inspect.isawaitable(callback) or inspect.iscoroutinefunction(callback) + spec = inspect.getfullargspec(callback) + self.params = {*spec.args, *spec.kwonlyargs} + self.varkw = spec.varkw is not None + + def _prepare_kwargs(self, kwargs: Dict[str, Any]) -> Dict[str, Any]: + if self.varkw: + return kwargs + + return {k: kwargs[k] for k in self.params if k in kwargs} + + async def call(self, *args: Any, **kwargs: Any) -> Any: + wrapped = partial(self.callback, *args, **self._prepare_kwargs(kwargs)) + if self.awaitable: + return await wrapped() + + loop = asyncio.get_event_loop() + context = contextvars.copy_context() + wrapped = partial(context.run, wrapped) + return await loop.run_in_executor(None, wrapped) + + +@dataclass +class FilterObject(CallableObject): + magic: Optional[MagicFilter] = None + + def __post_init__(self) -> None: + if isinstance(self.callback, OriginalMagicFilter): + # MagicFilter instance is callable but generates + # only "CallOperation" instead of applying the filter + self.magic = self.callback + self.callback = self.callback.resolve + if not isinstance(self.magic, MagicFilter): + # Issue: https://github.com/aiogram/aiogram/issues/990 + warnings.warn( + category=Recommendation, + message="You are using F provided by magic_filter package directly, " + "but it lacks `.as_()` extension." + "\n Please change the import statement: from `from magic_filter import F` " + "to `from aiogram import F` to silence this warning.", + stacklevel=6, + ) + + super(FilterObject, self).__post_init__() + + if isinstance(self.callback, Filter): + self.awaitable = True + + +@dataclass +class HandlerObject(CallableObject): + filters: Optional[List[FilterObject]] = None + flags: Dict[str, Any] = field(default_factory=dict) + + def __post_init__(self) -> None: + super(HandlerObject, self).__post_init__() + callback = inspect.unwrap(self.callback) + if inspect.isclass(callback) and issubclass(callback, BaseHandler): + self.awaitable = True + self.flags.update(extract_flags_from_object(callback)) + + async def check(self, *args: Any, **kwargs: Any) -> Tuple[bool, Dict[str, Any]]: + if not self.filters: + return True, kwargs + for event_filter in self.filters: + check = await event_filter.call(*args, **kwargs) + if not check: + return False, kwargs + if isinstance(check, dict): + kwargs.update(check) + return True, kwargs diff --git a/env/Lib/site-packages/aiogram/dispatcher/event/telegram.py b/env/Lib/site-packages/aiogram/dispatcher/event/telegram.py new file mode 100644 index 0000000..afa8938 --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/event/telegram.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional + +from aiogram.dispatcher.middlewares.manager import MiddlewareManager + +from ...exceptions import UnsupportedKeywordArgument +from ...filters.base import Filter +from ...types import TelegramObject +from .bases import REJECTED, UNHANDLED, MiddlewareType, SkipHandler +from .handler import CallbackType, FilterObject, HandlerObject + +if TYPE_CHECKING: + from aiogram.dispatcher.router import Router + + +class TelegramEventObserver: + """ + Event observer for Telegram events + + Here you can register handler with filter. + This observer will stop event propagation when first handler is pass. + """ + + def __init__(self, router: Router, event_name: str) -> None: + self.router: Router = router + self.event_name: str = event_name + + self.handlers: List[HandlerObject] = [] + + self.middleware = MiddlewareManager() + self.outer_middleware = MiddlewareManager() + + # Re-used filters check method from already implemented handler object + # with dummy callback which never will be used + self._handler = HandlerObject(callback=lambda: True, filters=[]) + + def filter(self, *filters: CallbackType) -> None: + """ + Register filter for all handlers of this event observer + + :param filters: positional filters + """ + if self._handler.filters is None: + self._handler.filters = [] + self._handler.filters.extend([FilterObject(filter_) for filter_ in filters]) + + def _resolve_middlewares(self) -> List[MiddlewareType[TelegramObject]]: + middlewares: List[MiddlewareType[TelegramObject]] = [] + for router in reversed(tuple(self.router.chain_head)): + observer = router.observers.get(self.event_name) + if observer: + middlewares.extend(observer.middleware) + + return middlewares + + def register( + self, + callback: CallbackType, + *filters: CallbackType, + flags: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> CallbackType: + """ + Register event handler + """ + if kwargs: + raise UnsupportedKeywordArgument( + "Passing any additional keyword arguments to the registrar method " + "is not supported.\n" + "This error may be caused when you are trying to register filters like in 2.x " + "version of this framework, if it's true just look at correspoding " + "documentation pages.\n" + f"Please remove the {set(kwargs.keys())} arguments from this call.\n" + ) + + if flags is None: + flags = {} + + for item in filters: + if isinstance(item, Filter): + item.update_handler_flags(flags=flags) + + self.handlers.append( + HandlerObject( + callback=callback, + filters=[FilterObject(filter_) for filter_ in filters], + flags=flags, + ) + ) + + return callback + + def wrap_outer_middleware( + self, callback: Any, event: TelegramObject, data: Dict[str, Any] + ) -> Any: + wrapped_outer = self.middleware.wrap_middlewares( + self.outer_middleware, + callback, + ) + return wrapped_outer(event, data) + + def check_root_filters(self, event: TelegramObject, **kwargs: Any) -> Any: + return self._handler.check(event, **kwargs) + + async def trigger(self, event: TelegramObject, **kwargs: Any) -> Any: + """ + Propagate event to handlers and stops propagation on first match. + Handler will be called when all its filters are pass. + """ + for handler in self.handlers: + kwargs["handler"] = handler + result, data = await handler.check(event, **kwargs) + if result: + kwargs.update(data) + try: + wrapped_inner = self.outer_middleware.wrap_middlewares( + self._resolve_middlewares(), + handler.call, + ) + return await wrapped_inner(event, kwargs) + except SkipHandler: + continue + + return UNHANDLED + + def __call__( + self, + *filters: CallbackType, + flags: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> Callable[[CallbackType], CallbackType]: + """ + Decorator for registering event handlers + """ + + def wrapper(callback: CallbackType) -> CallbackType: + self.register(callback, *filters, flags=flags, **kwargs) + return callback + + return wrapper diff --git a/env/Lib/site-packages/aiogram/dispatcher/flags.py b/env/Lib/site-packages/aiogram/dispatcher/flags.py new file mode 100644 index 0000000..aad8a29 --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/flags.py @@ -0,0 +1,127 @@ +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union, cast, overload + +from magic_filter import AttrDict, MagicFilter + +if TYPE_CHECKING: + from aiogram.dispatcher.event.handler import HandlerObject + + +@dataclass(frozen=True) +class Flag: + name: str + value: Any + + +@dataclass(frozen=True) +class FlagDecorator: + flag: Flag + + @classmethod + def _with_flag(cls, flag: Flag) -> "FlagDecorator": + return cls(flag) + + def _with_value(self, value: Any) -> "FlagDecorator": + new_flag = Flag(self.flag.name, value) + return self._with_flag(new_flag) + + @overload + def __call__(self, value: Callable[..., Any], /) -> Callable[..., Any]: # type: ignore + pass + + @overload + def __call__(self, value: Any, /) -> "FlagDecorator": + pass + + @overload + def __call__(self, **kwargs: Any) -> "FlagDecorator": + pass + + def __call__( + self, + value: Optional[Any] = None, + **kwargs: Any, + ) -> Union[Callable[..., Any], "FlagDecorator"]: + if value and kwargs: + raise ValueError("The arguments `value` and **kwargs can not be used together") + + if value is not None and callable(value): + value.aiogram_flag = { + **extract_flags_from_object(value), + self.flag.name: self.flag.value, + } + return cast(Callable[..., Any], value) + return self._with_value(AttrDict(kwargs) if value is None else value) + + +if TYPE_CHECKING: + + class _ChatActionFlagProtocol(FlagDecorator): + def __call__( # type: ignore[override] + self, + action: str = ..., + interval: float = ..., + initial_sleep: float = ..., + **kwargs: Any, + ) -> FlagDecorator: + pass + + +class FlagGenerator: + def __getattr__(self, name: str) -> FlagDecorator: + if name[0] == "_": + raise AttributeError("Flag name must NOT start with underscore") + return FlagDecorator(Flag(name, True)) + + if TYPE_CHECKING: + chat_action: _ChatActionFlagProtocol + + +def extract_flags_from_object(obj: Any) -> Dict[str, Any]: + if not hasattr(obj, "aiogram_flag"): + return {} + return cast(Dict[str, Any], obj.aiogram_flag) + + +def extract_flags(handler: Union["HandlerObject", Dict[str, Any]]) -> Dict[str, Any]: + """ + Extract flags from handler or middleware context data + + :param handler: handler object or data + :return: dictionary with all handler flags + """ + if isinstance(handler, dict) and "handler" in handler: + handler = handler["handler"] + if hasattr(handler, "flags"): + return handler.flags + return {} + + +def get_flag( + handler: Union["HandlerObject", Dict[str, Any]], + name: str, + *, + default: Optional[Any] = None, +) -> Any: + """ + Get flag by name + + :param handler: handler object or data + :param name: name of the flag + :param default: default value (None) + :return: value of the flag or default + """ + flags = extract_flags(handler) + return flags.get(name, default) + + +def check_flags(handler: Union["HandlerObject", Dict[str, Any]], magic: MagicFilter) -> Any: + """ + Check flags via magic filter + + :param handler: handler object or data + :param magic: instance of the magic + :return: the result of magic filter check + """ + flags = extract_flags(handler) + return magic.resolve(AttrDict(flags)) diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/__init__.py b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..0cf8139 Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..d4a6c6a Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/error.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/error.cpython-311.pyc new file mode 100644 index 0000000..10d41a9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/error.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/manager.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/manager.cpython-311.pyc new file mode 100644 index 0000000..96bf53e Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/manager.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/user_context.cpython-311.pyc b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/user_context.cpython-311.pyc new file mode 100644 index 0000000..26c54da Binary files /dev/null and b/env/Lib/site-packages/aiogram/dispatcher/middlewares/__pycache__/user_context.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/base.py b/env/Lib/site-packages/aiogram/dispatcher/middlewares/base.py new file mode 100644 index 0000000..15b0b4a --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/middlewares/base.py @@ -0,0 +1,29 @@ +from abc import ABC, abstractmethod +from typing import Any, Awaitable, Callable, Dict, TypeVar + +from aiogram.types import TelegramObject + +T = TypeVar("T") + + +class BaseMiddleware(ABC): + """ + Generic middleware class + """ + + @abstractmethod + async def __call__( + self, + handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: # pragma: no cover + """ + Execute middleware + + :param handler: Wrapped handler in middlewares chain + :param event: Incoming event (Subclass of :class:`aiogram.types.base.TelegramObject`) + :param data: Contextual data. Will be mapped to handler arguments + :return: :class:`Any` + """ + pass diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/error.py b/env/Lib/site-packages/aiogram/dispatcher/middlewares/error.py new file mode 100644 index 0000000..4b68c0b --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/middlewares/error.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, cast + +from ...types import TelegramObject, Update +from ...types.error_event import ErrorEvent +from ..event.bases import UNHANDLED, CancelHandler, SkipHandler +from .base import BaseMiddleware + +if TYPE_CHECKING: + from ..router import Router + + +class ErrorsMiddleware(BaseMiddleware): + def __init__(self, router: Router): + self.router = router + + async def __call__( + self, + handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + try: + return await handler(event, data) + except (SkipHandler, CancelHandler): # pragma: no cover + raise + except Exception as e: + response = await self.router.propagate_event( + update_type="error", + event=ErrorEvent(update=cast(Update, event), exception=e), + **data, + ) + if response is not UNHANDLED: + return response + raise diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/manager.py b/env/Lib/site-packages/aiogram/dispatcher/middlewares/manager.py new file mode 100644 index 0000000..bcad4de --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/middlewares/manager.py @@ -0,0 +1,65 @@ +import functools +from typing import Any, Callable, Dict, List, Optional, Sequence, Union, overload + +from aiogram.dispatcher.event.bases import ( + MiddlewareEventType, + MiddlewareType, + NextMiddlewareType, +) +from aiogram.dispatcher.event.handler import CallbackType +from aiogram.types import TelegramObject + + +class MiddlewareManager(Sequence[MiddlewareType[TelegramObject]]): + def __init__(self) -> None: + self._middlewares: List[MiddlewareType[TelegramObject]] = [] + + def register( + self, + middleware: MiddlewareType[TelegramObject], + ) -> MiddlewareType[TelegramObject]: + self._middlewares.append(middleware) + return middleware + + def unregister(self, middleware: MiddlewareType[TelegramObject]) -> None: + self._middlewares.remove(middleware) + + def __call__( + self, + middleware: Optional[MiddlewareType[TelegramObject]] = None, + ) -> Union[ + Callable[[MiddlewareType[TelegramObject]], MiddlewareType[TelegramObject]], + MiddlewareType[TelegramObject], + ]: + if middleware is None: + return self.register + return self.register(middleware) + + @overload + def __getitem__(self, item: int) -> MiddlewareType[TelegramObject]: + pass + + @overload + def __getitem__(self, item: slice) -> Sequence[MiddlewareType[TelegramObject]]: + pass + + def __getitem__( + self, item: Union[int, slice] + ) -> Union[MiddlewareType[TelegramObject], Sequence[MiddlewareType[TelegramObject]]]: + return self._middlewares[item] + + def __len__(self) -> int: + return len(self._middlewares) + + @staticmethod + def wrap_middlewares( + middlewares: Sequence[MiddlewareType[MiddlewareEventType]], handler: CallbackType + ) -> NextMiddlewareType[MiddlewareEventType]: + @functools.wraps(handler) + def handler_wrapper(event: TelegramObject, kwargs: Dict[str, Any]) -> Any: + return handler(event, **kwargs) + + middleware = handler_wrapper + for m in reversed(middlewares): + middleware = functools.partial(m, middleware) # type: ignore[assignment] + return middleware diff --git a/env/Lib/site-packages/aiogram/dispatcher/middlewares/user_context.py b/env/Lib/site-packages/aiogram/dispatcher/middlewares/user_context.py new file mode 100644 index 0000000..aa03ee6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/middlewares/user_context.py @@ -0,0 +1,178 @@ +from dataclasses import dataclass +from typing import Any, Awaitable, Callable, Dict, Optional + +from aiogram.dispatcher.middlewares.base import BaseMiddleware +from aiogram.types import ( + Chat, + ChatBoostSourcePremium, + InaccessibleMessage, + TelegramObject, + Update, + User, +) + +EVENT_CONTEXT_KEY = "event_context" + +EVENT_FROM_USER_KEY = "event_from_user" +EVENT_CHAT_KEY = "event_chat" +EVENT_THREAD_ID_KEY = "event_thread_id" + + +@dataclass(frozen=True) +class EventContext: + chat: Optional[Chat] = None + user: Optional[User] = None + thread_id: Optional[int] = None + business_connection_id: Optional[str] = None + + @property + def user_id(self) -> Optional[int]: + return self.user.id if self.user else None + + @property + def chat_id(self) -> Optional[int]: + return self.chat.id if self.chat else None + + +class UserContextMiddleware(BaseMiddleware): + async def __call__( + self, + handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + if not isinstance(event, Update): + raise RuntimeError("UserContextMiddleware got an unexpected event type!") + event_context = data[EVENT_CONTEXT_KEY] = self.resolve_event_context(event=event) + + # Backward compatibility + if event_context.user is not None: + data[EVENT_FROM_USER_KEY] = event_context.user + if event_context.chat is not None: + data[EVENT_CHAT_KEY] = event_context.chat + if event_context.thread_id is not None: + data[EVENT_THREAD_ID_KEY] = event_context.thread_id + + return await handler(event, data) + + @classmethod + def resolve_event_context(cls, event: Update) -> EventContext: + """ + Resolve chat and user instance from Update object + """ + if event.message: + return EventContext( + chat=event.message.chat, + user=event.message.from_user, + thread_id=( + event.message.message_thread_id if event.message.is_topic_message else None + ), + ) + if event.edited_message: + return EventContext( + chat=event.edited_message.chat, + user=event.edited_message.from_user, + thread_id=( + event.edited_message.message_thread_id + if event.edited_message.is_topic_message + else None + ), + ) + if event.channel_post: + return EventContext(chat=event.channel_post.chat) + if event.edited_channel_post: + return EventContext(chat=event.edited_channel_post.chat) + if event.inline_query: + return EventContext(user=event.inline_query.from_user) + if event.chosen_inline_result: + return EventContext(user=event.chosen_inline_result.from_user) + if event.callback_query: + callback_query_message = event.callback_query.message + if callback_query_message: + return EventContext( + chat=callback_query_message.chat, + user=event.callback_query.from_user, + thread_id=( + callback_query_message.message_thread_id + if not isinstance(callback_query_message, InaccessibleMessage) + and callback_query_message.is_topic_message + else None + ), + business_connection_id=( + callback_query_message.business_connection_id + if not isinstance(callback_query_message, InaccessibleMessage) + else None + ), + ) + return EventContext(user=event.callback_query.from_user) + if event.shipping_query: + return EventContext(user=event.shipping_query.from_user) + if event.pre_checkout_query: + return EventContext(user=event.pre_checkout_query.from_user) + if event.poll_answer: + return EventContext( + chat=event.poll_answer.voter_chat, + user=event.poll_answer.user, + ) + if event.my_chat_member: + return EventContext( + chat=event.my_chat_member.chat, user=event.my_chat_member.from_user + ) + if event.chat_member: + return EventContext(chat=event.chat_member.chat, user=event.chat_member.from_user) + if event.chat_join_request: + return EventContext( + chat=event.chat_join_request.chat, user=event.chat_join_request.from_user + ) + if event.message_reaction: + return EventContext( + chat=event.message_reaction.chat, + user=event.message_reaction.user, + ) + if event.message_reaction_count: + return EventContext(chat=event.message_reaction_count.chat) + if event.chat_boost: + # We only check the premium source, because only it has a sender user, + # other sources have a user, but it is not the sender, but the recipient + if isinstance(event.chat_boost.boost.source, ChatBoostSourcePremium): + return EventContext( + chat=event.chat_boost.chat, + user=event.chat_boost.boost.source.user, + ) + + return EventContext(chat=event.chat_boost.chat) + if event.removed_chat_boost: + return EventContext(chat=event.removed_chat_boost.chat) + if event.deleted_business_messages: + return EventContext( + chat=event.deleted_business_messages.chat, + business_connection_id=event.deleted_business_messages.business_connection_id, + ) + if event.business_connection: + return EventContext( + user=event.business_connection.user, + business_connection_id=event.business_connection.id, + ) + if event.business_message: + return EventContext( + chat=event.business_message.chat, + user=event.business_message.from_user, + thread_id=( + event.business_message.message_thread_id + if event.business_message.is_topic_message + else None + ), + business_connection_id=event.business_message.business_connection_id, + ) + if event.edited_business_message: + return EventContext( + chat=event.edited_business_message.chat, + user=event.edited_business_message.from_user, + thread_id=( + event.edited_business_message.message_thread_id + if event.edited_business_message.is_topic_message + else None + ), + business_connection_id=event.edited_business_message.business_connection_id, + ) + return EventContext() diff --git a/env/Lib/site-packages/aiogram/dispatcher/router.py b/env/Lib/site-packages/aiogram/dispatcher/router.py new file mode 100644 index 0000000..400c1c0 --- /dev/null +++ b/env/Lib/site-packages/aiogram/dispatcher/router.py @@ -0,0 +1,271 @@ +from __future__ import annotations + +from typing import Any, Dict, Final, Generator, List, Optional, Set + +from ..types import TelegramObject +from .event.bases import REJECTED, UNHANDLED +from .event.event import EventObserver +from .event.telegram import TelegramEventObserver + +INTERNAL_UPDATE_TYPES: Final[frozenset[str]] = frozenset({"update", "error"}) + + +class Router: + """ + Router can route update, and it nested update types like messages, callback query, + polls and all other event types. + + Event handlers can be registered in observer by two ways: + + - By observer method - :obj:`router..register(handler, )` + - By decorator - :obj:`@router.()` + """ + + def __init__(self, *, name: Optional[str] = None) -> None: + """ + :param name: Optional router name, can be useful for debugging + """ + + self.name = name or hex(id(self)) + + self._parent_router: Optional[Router] = None + self.sub_routers: List[Router] = [] + + # Observers + self.message = TelegramEventObserver(router=self, event_name="message") + self.edited_message = TelegramEventObserver(router=self, event_name="edited_message") + self.channel_post = TelegramEventObserver(router=self, event_name="channel_post") + self.edited_channel_post = TelegramEventObserver( + router=self, event_name="edited_channel_post" + ) + self.inline_query = TelegramEventObserver(router=self, event_name="inline_query") + self.chosen_inline_result = TelegramEventObserver( + router=self, event_name="chosen_inline_result" + ) + self.callback_query = TelegramEventObserver(router=self, event_name="callback_query") + self.shipping_query = TelegramEventObserver(router=self, event_name="shipping_query") + self.pre_checkout_query = TelegramEventObserver( + router=self, event_name="pre_checkout_query" + ) + self.poll = TelegramEventObserver(router=self, event_name="poll") + self.poll_answer = TelegramEventObserver(router=self, event_name="poll_answer") + self.my_chat_member = TelegramEventObserver(router=self, event_name="my_chat_member") + self.chat_member = TelegramEventObserver(router=self, event_name="chat_member") + self.chat_join_request = TelegramEventObserver(router=self, event_name="chat_join_request") + self.message_reaction = TelegramEventObserver(router=self, event_name="message_reaction") + self.message_reaction_count = TelegramEventObserver( + router=self, event_name="message_reaction_count" + ) + self.chat_boost = TelegramEventObserver(router=self, event_name="chat_boost") + self.removed_chat_boost = TelegramEventObserver( + router=self, event_name="removed_chat_boost" + ) + self.deleted_business_messages = TelegramEventObserver( + router=self, event_name="deleted_business_messages" + ) + self.business_connection = TelegramEventObserver( + router=self, event_name="business_connection" + ) + self.edited_business_message = TelegramEventObserver( + router=self, event_name="edited_business_message" + ) + self.business_message = TelegramEventObserver(router=self, event_name="business_message") + + self.errors = self.error = TelegramEventObserver(router=self, event_name="error") + + self.startup = EventObserver() + self.shutdown = EventObserver() + + self.observers: Dict[str, TelegramEventObserver] = { + "message": self.message, + "edited_message": self.edited_message, + "channel_post": self.channel_post, + "edited_channel_post": self.edited_channel_post, + "inline_query": self.inline_query, + "chosen_inline_result": self.chosen_inline_result, + "callback_query": self.callback_query, + "shipping_query": self.shipping_query, + "pre_checkout_query": self.pre_checkout_query, + "poll": self.poll, + "poll_answer": self.poll_answer, + "my_chat_member": self.my_chat_member, + "chat_member": self.chat_member, + "chat_join_request": self.chat_join_request, + "message_reaction": self.message_reaction, + "message_reaction_count": self.message_reaction_count, + "chat_boost": self.chat_boost, + "removed_chat_boost": self.removed_chat_boost, + "deleted_business_messages": self.deleted_business_messages, + "business_connection": self.business_connection, + "edited_business_message": self.edited_business_message, + "business_message": self.business_message, + "error": self.errors, + } + + def __str__(self) -> str: + return f"{type(self).__name__} {self.name!r}" + + def __repr__(self) -> str: + return f"<{self}>" + + def resolve_used_update_types(self, skip_events: Optional[Set[str]] = None) -> List[str]: + """ + Resolve registered event names + + Is useful for getting updates only for registered event types. + + :param skip_events: skip specified event names + :return: set of registered names + """ + handlers_in_use: Set[str] = set() + if skip_events is None: + skip_events = set() + skip_events = {*skip_events, *INTERNAL_UPDATE_TYPES} + + for router in self.chain_tail: + for update_name, observer in router.observers.items(): + if observer.handlers and update_name not in skip_events: + handlers_in_use.add(update_name) + + return list(sorted(handlers_in_use)) # NOQA: C413 + + async def propagate_event(self, update_type: str, event: TelegramObject, **kwargs: Any) -> Any: + kwargs.update(event_router=self) + observer = self.observers.get(update_type) + + async def _wrapped(telegram_event: TelegramObject, **data: Any) -> Any: + return await self._propagate_event( + observer=observer, update_type=update_type, event=telegram_event, **data + ) + + if observer: + return await observer.wrap_outer_middleware(_wrapped, event=event, data=kwargs) + return await _wrapped(event, **kwargs) + + async def _propagate_event( + self, + observer: Optional[TelegramEventObserver], + update_type: str, + event: TelegramObject, + **kwargs: Any, + ) -> Any: + response = UNHANDLED + if observer: + # Check globally defined filters before any other handler will be checked. + # This check is placed here instead of `trigger` method to add possibility + # to pass context to handlers from global filters. + result, data = await observer.check_root_filters(event, **kwargs) + if not result: + return UNHANDLED + kwargs.update(data) + + response = await observer.trigger(event, **kwargs) + if response is REJECTED: # pragma: no cover + # Possible only if some handler returns REJECTED + return UNHANDLED + if response is not UNHANDLED: + return response + + for router in self.sub_routers: + response = await router.propagate_event(update_type=update_type, event=event, **kwargs) + if response is not UNHANDLED: + break + + return response + + @property + def chain_head(self) -> Generator[Router, None, None]: + router: Optional[Router] = self + while router: + yield router + router = router.parent_router + + @property + def chain_tail(self) -> Generator[Router, None, None]: + yield self + for router in self.sub_routers: + yield from router.chain_tail + + @property + def parent_router(self) -> Optional[Router]: + return self._parent_router + + @parent_router.setter + def parent_router(self, router: Router) -> None: + """ + Internal property setter of parent router fot this router. + Do not use this method in own code. + All routers should be included via `include_router` method. + + Self- and circular- referencing are not allowed here + + :param router: + """ + if not isinstance(router, Router): + raise ValueError(f"router should be instance of Router not {type(router).__name__!r}") + if self._parent_router: + raise RuntimeError(f"Router is already attached to {self._parent_router!r}") + if self == router: + raise RuntimeError("Self-referencing routers is not allowed") + + parent: Optional[Router] = router + while parent is not None: + if parent == self: + raise RuntimeError("Circular referencing of Router is not allowed") + + parent = parent.parent_router + + self._parent_router = router + router.sub_routers.append(self) + + def include_routers(self, *routers: Router) -> None: + """ + Attach multiple routers. + + :param routers: + :return: + """ + if not routers: + raise ValueError("At least one router must be provided") + for router in routers: + self.include_router(router) + + def include_router(self, router: Router) -> Router: + """ + Attach another router. + + :param router: + :return: + """ + if not isinstance(router, Router): + raise ValueError( + f"router should be instance of Router not {type(router).__class__.__name__}" + ) + router.parent_router = self + return router + + async def emit_startup(self, *args: Any, **kwargs: Any) -> None: + """ + Recursively call startup callbacks + + :param args: + :param kwargs: + :return: + """ + kwargs.update(router=self) + await self.startup.trigger(*args, **kwargs) + for router in self.sub_routers: + await router.emit_startup(*args, **kwargs) + + async def emit_shutdown(self, *args: Any, **kwargs: Any) -> None: + """ + Recursively call shutdown callbacks to graceful shutdown + + :param args: + :param kwargs: + :return: + """ + kwargs.update(router=self) + await self.shutdown.trigger(*args, **kwargs) + for router in self.sub_routers: + await router.emit_shutdown(*args, **kwargs) diff --git a/env/Lib/site-packages/aiogram/enums/__init__.py b/env/Lib/site-packages/aiogram/enums/__init__.py new file mode 100644 index 0000000..f8c4532 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/__init__.py @@ -0,0 +1,59 @@ +from .bot_command_scope_type import BotCommandScopeType +from .chat_action import ChatAction +from .chat_boost_source_type import ChatBoostSourceType +from .chat_member_status import ChatMemberStatus +from .chat_type import ChatType +from .content_type import ContentType +from .currency import Currency +from .dice_emoji import DiceEmoji +from .encrypted_passport_element import EncryptedPassportElement +from .inline_query_result_type import InlineQueryResultType +from .input_media_type import InputMediaType +from .input_paid_media_type import InputPaidMediaType +from .keyboard_button_poll_type_type import KeyboardButtonPollTypeType +from .mask_position_point import MaskPositionPoint +from .menu_button_type import MenuButtonType +from .message_entity_type import MessageEntityType +from .message_origin_type import MessageOriginType +from .paid_media_type import PaidMediaType +from .parse_mode import ParseMode +from .passport_element_error_type import PassportElementErrorType +from .poll_type import PollType +from .reaction_type_type import ReactionTypeType +from .revenue_withdrawal_state_type import RevenueWithdrawalStateType +from .sticker_format import StickerFormat +from .sticker_type import StickerType +from .topic_icon_color import TopicIconColor +from .transaction_partner_type import TransactionPartnerType +from .update_type import UpdateType + +__all__ = ( + "BotCommandScopeType", + "ChatAction", + "ChatBoostSourceType", + "ChatMemberStatus", + "ChatType", + "ContentType", + "Currency", + "DiceEmoji", + "EncryptedPassportElement", + "InlineQueryResultType", + "InputMediaType", + "InputPaidMediaType", + "KeyboardButtonPollTypeType", + "MaskPositionPoint", + "MenuButtonType", + "MessageEntityType", + "MessageOriginType", + "PaidMediaType", + "ParseMode", + "PassportElementErrorType", + "PollType", + "ReactionTypeType", + "RevenueWithdrawalStateType", + "StickerFormat", + "StickerType", + "TopicIconColor", + "TransactionPartnerType", + "UpdateType", +) diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..46aed5f Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/bot_command_scope_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/bot_command_scope_type.cpython-311.pyc new file mode 100644 index 0000000..9257634 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/bot_command_scope_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/chat_action.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/chat_action.cpython-311.pyc new file mode 100644 index 0000000..ccea966 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/chat_action.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/chat_boost_source_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/chat_boost_source_type.cpython-311.pyc new file mode 100644 index 0000000..38a2035 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/chat_boost_source_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/chat_member_status.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/chat_member_status.cpython-311.pyc new file mode 100644 index 0000000..56fc5f0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/chat_member_status.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/chat_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/chat_type.cpython-311.pyc new file mode 100644 index 0000000..06f39bb Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/chat_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/content_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/content_type.cpython-311.pyc new file mode 100644 index 0000000..98c28e4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/content_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/currency.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/currency.cpython-311.pyc new file mode 100644 index 0000000..e09e3c0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/currency.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/dice_emoji.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/dice_emoji.cpython-311.pyc new file mode 100644 index 0000000..f44f896 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/dice_emoji.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/encrypted_passport_element.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/encrypted_passport_element.cpython-311.pyc new file mode 100644 index 0000000..0f12c3b Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/encrypted_passport_element.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/inline_query_result_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/inline_query_result_type.cpython-311.pyc new file mode 100644 index 0000000..c3a5fe4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/inline_query_result_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/input_media_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/input_media_type.cpython-311.pyc new file mode 100644 index 0000000..47e46d2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/input_media_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/input_paid_media_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/input_paid_media_type.cpython-311.pyc new file mode 100644 index 0000000..2316e0f Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/input_paid_media_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/keyboard_button_poll_type_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/keyboard_button_poll_type_type.cpython-311.pyc new file mode 100644 index 0000000..616b235 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/keyboard_button_poll_type_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/mask_position_point.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/mask_position_point.cpython-311.pyc new file mode 100644 index 0000000..f697a4e Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/mask_position_point.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/menu_button_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/menu_button_type.cpython-311.pyc new file mode 100644 index 0000000..3c9d400 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/menu_button_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/message_entity_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/message_entity_type.cpython-311.pyc new file mode 100644 index 0000000..fc266ea Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/message_entity_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/message_origin_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/message_origin_type.cpython-311.pyc new file mode 100644 index 0000000..17c5630 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/message_origin_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/paid_media_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/paid_media_type.cpython-311.pyc new file mode 100644 index 0000000..433b4a3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/paid_media_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/parse_mode.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/parse_mode.cpython-311.pyc new file mode 100644 index 0000000..011d423 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/parse_mode.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/passport_element_error_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/passport_element_error_type.cpython-311.pyc new file mode 100644 index 0000000..6abd8b3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/passport_element_error_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/poll_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/poll_type.cpython-311.pyc new file mode 100644 index 0000000..e23f58e Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/poll_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/reaction_type_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/reaction_type_type.cpython-311.pyc new file mode 100644 index 0000000..3511a4d Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/reaction_type_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/revenue_withdrawal_state_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/revenue_withdrawal_state_type.cpython-311.pyc new file mode 100644 index 0000000..5f20a95 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/revenue_withdrawal_state_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/sticker_format.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/sticker_format.cpython-311.pyc new file mode 100644 index 0000000..df062cf Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/sticker_format.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/sticker_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/sticker_type.cpython-311.pyc new file mode 100644 index 0000000..cc769aa Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/sticker_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/topic_icon_color.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/topic_icon_color.cpython-311.pyc new file mode 100644 index 0000000..70c3a0a Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/topic_icon_color.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/transaction_partner_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/transaction_partner_type.cpython-311.pyc new file mode 100644 index 0000000..4067baa Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/transaction_partner_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/__pycache__/update_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/enums/__pycache__/update_type.cpython-311.pyc new file mode 100644 index 0000000..53f49c2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/enums/__pycache__/update_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/enums/bot_command_scope_type.py b/env/Lib/site-packages/aiogram/enums/bot_command_scope_type.py new file mode 100644 index 0000000..f099431 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/bot_command_scope_type.py @@ -0,0 +1,17 @@ +from enum import Enum + + +class BotCommandScopeType(str, Enum): + """ + This object represents the scope to which bot commands are applied. + + Source: https://core.telegram.org/bots/api#botcommandscope + """ + + DEFAULT = "default" + ALL_PRIVATE_CHATS = "all_private_chats" + ALL_GROUP_CHATS = "all_group_chats" + ALL_CHAT_ADMINISTRATORS = "all_chat_administrators" + CHAT = "chat" + CHAT_ADMINISTRATORS = "chat_administrators" + CHAT_MEMBER = "chat_member" diff --git a/env/Lib/site-packages/aiogram/enums/chat_action.py b/env/Lib/site-packages/aiogram/enums/chat_action.py new file mode 100644 index 0000000..4402b5b --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/chat_action.py @@ -0,0 +1,32 @@ +from enum import Enum + + +class ChatAction(str, Enum): + """ + This object represents bot actions. + + Choose one, depending on what the user is about to receive: + + - typing for text messages, + - upload_photo for photos, + - record_video or upload_video for videos, + - record_voice or upload_voice for voice notes, + - upload_document for general files, + - choose_sticker for stickers, + - find_location for location data, + - record_video_note or upload_video_note for video notes. + + Source: https://core.telegram.org/bots/api#sendchataction + """ + + TYPING = "typing" + UPLOAD_PHOTO = "upload_photo" + RECORD_VIDEO = "record_video" + UPLOAD_VIDEO = "upload_video" + RECORD_VOICE = "record_voice" + UPLOAD_VOICE = "upload_voice" + UPLOAD_DOCUMENT = "upload_document" + CHOOSE_STICKER = "choose_sticker" + FIND_LOCATION = "find_location" + RECORD_VIDEO_NOTE = "record_video_note" + UPLOAD_VIDEO_NOTE = "upload_video_note" diff --git a/env/Lib/site-packages/aiogram/enums/chat_boost_source_type.py b/env/Lib/site-packages/aiogram/enums/chat_boost_source_type.py new file mode 100644 index 0000000..c95c31d --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/chat_boost_source_type.py @@ -0,0 +1,13 @@ +from enum import Enum + + +class ChatBoostSourceType(str, Enum): + """ + This object represents a type of chat boost source. + + Source: https://core.telegram.org/bots/api#chatboostsource + """ + + PREMIUM = "premium" + GIFT_CODE = "gift_code" + GIVEAWAY = "giveaway" diff --git a/env/Lib/site-packages/aiogram/enums/chat_member_status.py b/env/Lib/site-packages/aiogram/enums/chat_member_status.py new file mode 100644 index 0000000..db6f921 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/chat_member_status.py @@ -0,0 +1,16 @@ +from enum import Enum + + +class ChatMemberStatus(str, Enum): + """ + This object represents chat member status. + + Source: https://core.telegram.org/bots/api#chatmember + """ + + CREATOR = "creator" + ADMINISTRATOR = "administrator" + MEMBER = "member" + RESTRICTED = "restricted" + LEFT = "left" + KICKED = "kicked" diff --git a/env/Lib/site-packages/aiogram/enums/chat_type.py b/env/Lib/site-packages/aiogram/enums/chat_type.py new file mode 100644 index 0000000..10dccc8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/chat_type.py @@ -0,0 +1,15 @@ +from enum import Enum + + +class ChatType(str, Enum): + """ + This object represents a chat type + + Source: https://core.telegram.org/bots/api#chat + """ + + SENDER = "sender" + PRIVATE = "private" + GROUP = "group" + SUPERGROUP = "supergroup" + CHANNEL = "channel" diff --git a/env/Lib/site-packages/aiogram/enums/content_type.py b/env/Lib/site-packages/aiogram/enums/content_type.py new file mode 100644 index 0000000..5d64db1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/content_type.py @@ -0,0 +1,66 @@ +from enum import Enum + + +class ContentType(str, Enum): + """ + This object represents a type of content in message + """ + + UNKNOWN = "unknown" + ANY = "any" + TEXT = "text" + ANIMATION = "animation" + AUDIO = "audio" + DOCUMENT = "document" + PAID_MEDIA = "paid_media" + PHOTO = "photo" + STICKER = "sticker" + STORY = "story" + VIDEO = "video" + VIDEO_NOTE = "video_note" + VOICE = "voice" + CONTACT = "contact" + DICE = "dice" + GAME = "game" + POLL = "poll" + VENUE = "venue" + LOCATION = "location" + NEW_CHAT_MEMBERS = "new_chat_members" + LEFT_CHAT_MEMBER = "left_chat_member" + NEW_CHAT_TITLE = "new_chat_title" + NEW_CHAT_PHOTO = "new_chat_photo" + DELETE_CHAT_PHOTO = "delete_chat_photo" + GROUP_CHAT_CREATED = "group_chat_created" + SUPERGROUP_CHAT_CREATED = "supergroup_chat_created" + CHANNEL_CHAT_CREATED = "channel_chat_created" + MESSAGE_AUTO_DELETE_TIMER_CHANGED = "message_auto_delete_timer_changed" + MIGRATE_TO_CHAT_ID = "migrate_to_chat_id" + MIGRATE_FROM_CHAT_ID = "migrate_from_chat_id" + PINNED_MESSAGE = "pinned_message" + INVOICE = "invoice" + SUCCESSFUL_PAYMENT = "successful_payment" + REFUNDED_PAYMENT = "refunded_payment" + USERS_SHARED = "users_shared" + CHAT_SHARED = "chat_shared" + CONNECTED_WEBSITE = "connected_website" + WRITE_ACCESS_ALLOWED = "write_access_allowed" + PASSPORT_DATA = "passport_data" + PROXIMITY_ALERT_TRIGGERED = "proximity_alert_triggered" + BOOST_ADDED = "boost_added" + CHAT_BACKGROUND_SET = "chat_background_set" + FORUM_TOPIC_CREATED = "forum_topic_created" + FORUM_TOPIC_EDITED = "forum_topic_edited" + FORUM_TOPIC_CLOSED = "forum_topic_closed" + FORUM_TOPIC_REOPENED = "forum_topic_reopened" + GENERAL_FORUM_TOPIC_HIDDEN = "general_forum_topic_hidden" + GENERAL_FORUM_TOPIC_UNHIDDEN = "general_forum_topic_unhidden" + GIVEAWAY_CREATED = "giveaway_created" + GIVEAWAY = "giveaway" + GIVEAWAY_WINNERS = "giveaway_winners" + GIVEAWAY_COMPLETED = "giveaway_completed" + VIDEO_CHAT_SCHEDULED = "video_chat_scheduled" + VIDEO_CHAT_STARTED = "video_chat_started" + VIDEO_CHAT_ENDED = "video_chat_ended" + VIDEO_CHAT_PARTICIPANTS_INVITED = "video_chat_participants_invited" + WEB_APP_DATA = "web_app_data" + USER_SHARED = "user_shared" diff --git a/env/Lib/site-packages/aiogram/enums/currency.py b/env/Lib/site-packages/aiogram/enums/currency.py new file mode 100644 index 0000000..563651b --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/currency.py @@ -0,0 +1,96 @@ +from enum import Enum + + +class Currency(str, Enum): + """ + Currencies supported by Telegram Bot API + + Source: https://core.telegram.org/bots/payments#supported-currencies + """ + + AED = "AED" + AFN = "AFN" + ALL = "ALL" + AMD = "AMD" + ARS = "ARS" + AUD = "AUD" + AZN = "AZN" + BAM = "BAM" + BDT = "BDT" + BGN = "BGN" + BND = "BND" + BOB = "BOB" + BRL = "BRL" + BYN = "BYN" + CAD = "CAD" + CHF = "CHF" + CLP = "CLP" + CNY = "CNY" + COP = "COP" + CRC = "CRC" + CZK = "CZK" + DKK = "DKK" + DOP = "DOP" + DZD = "DZD" + EGP = "EGP" + ETB = "ETB" + EUR = "EUR" + GBP = "GBP" + GEL = "GEL" + GTQ = "GTQ" + HKD = "HKD" + HNL = "HNL" + HRK = "HRK" + HUF = "HUF" + IDR = "IDR" + ILS = "ILS" + INR = "INR" + ISK = "ISK" + JMD = "JMD" + JPY = "JPY" + KES = "KES" + KGS = "KGS" + KRW = "KRW" + KZT = "KZT" + LBP = "LBP" + LKR = "LKR" + MAD = "MAD" + MDL = "MDL" + MNT = "MNT" + MUR = "MUR" + MVR = "MVR" + MXN = "MXN" + MYR = "MYR" + MZN = "MZN" + NGN = "NGN" + NIO = "NIO" + NOK = "NOK" + NPR = "NPR" + NZD = "NZD" + PAB = "PAB" + PEN = "PEN" + PHP = "PHP" + PKR = "PKR" + PLN = "PLN" + PYG = "PYG" + QAR = "QAR" + RON = "RON" + RSD = "RSD" + RUB = "RUB" + SAR = "SAR" + SEK = "SEK" + SGD = "SGD" + THB = "THB" + TJS = "TJS" + TRY = "TRY" + TTD = "TTD" + TWD = "TWD" + TZS = "TZS" + UAH = "UAH" + UGX = "UGX" + USD = "USD" + UYU = "UYU" + UZS = "UZS" + VND = "VND" + YER = "YER" + ZAR = "ZAR" diff --git a/env/Lib/site-packages/aiogram/enums/dice_emoji.py b/env/Lib/site-packages/aiogram/enums/dice_emoji.py new file mode 100644 index 0000000..6851932 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/dice_emoji.py @@ -0,0 +1,16 @@ +from enum import Enum + + +class DiceEmoji(str, Enum): + """ + Emoji on which the dice throw animation is based + + Source: https://core.telegram.org/bots/api#dice + """ + + DICE = "🎲" + DART = "🎯" + BASKETBALL = "🏀" + FOOTBALL = "⚽" + SLOT_MACHINE = "🎰" + BOWLING = "🎳" diff --git a/env/Lib/site-packages/aiogram/enums/encrypted_passport_element.py b/env/Lib/site-packages/aiogram/enums/encrypted_passport_element.py new file mode 100644 index 0000000..ebb4b2e --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/encrypted_passport_element.py @@ -0,0 +1,23 @@ +from enum import Enum + + +class EncryptedPassportElement(str, Enum): + """ + This object represents type of encrypted passport element. + + Source: https://core.telegram.org/bots/api#encryptedpassportelement + """ + + PERSONAL_DETAILS = "personal_details" + PASSPORT = "passport" + DRIVER_LICENSE = "driver_license" + IDENTITY_CARD = "identity_card" + INTERNAL_PASSPORT = "internal_passport" + ADDRESS = "address" + UTILITY_BILL = "utility_bill" + BANK_STATEMENT = "bank_statement" + RENTAL_AGREEMENT = "rental_agreement" + PASSPORT_REGISTRATION = "passport_registration" + TEMPORARY_REGISTRATION = "temporary_registration" + PHONE_NUMBER = "phone_number" + EMAIL = "email" diff --git a/env/Lib/site-packages/aiogram/enums/inline_query_result_type.py b/env/Lib/site-packages/aiogram/enums/inline_query_result_type.py new file mode 100644 index 0000000..ae20045 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/inline_query_result_type.py @@ -0,0 +1,23 @@ +from enum import Enum + + +class InlineQueryResultType(str, Enum): + """ + Type of inline query result + + Source: https://core.telegram.org/bots/api#inlinequeryresult + """ + + AUDIO = "audio" + DOCUMENT = "document" + GIF = "gif" + MPEG4_GIF = "mpeg4_gif" + PHOTO = "photo" + STICKER = "sticker" + VIDEO = "video" + VOICE = "voice" + ARTICLE = "article" + CONTACT = "contact" + GAME = "game" + LOCATION = "location" + VENUE = "venue" diff --git a/env/Lib/site-packages/aiogram/enums/input_media_type.py b/env/Lib/site-packages/aiogram/enums/input_media_type.py new file mode 100644 index 0000000..30741dd --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/input_media_type.py @@ -0,0 +1,15 @@ +from enum import Enum + + +class InputMediaType(str, Enum): + """ + This object represents input media type + + Source: https://core.telegram.org/bots/api#inputmedia + """ + + ANIMATION = "animation" + AUDIO = "audio" + DOCUMENT = "document" + PHOTO = "photo" + VIDEO = "video" diff --git a/env/Lib/site-packages/aiogram/enums/input_paid_media_type.py b/env/Lib/site-packages/aiogram/enums/input_paid_media_type.py new file mode 100644 index 0000000..fc132e2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/input_paid_media_type.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class InputPaidMediaType(str, Enum): + """ + This object represents the type of a media in a paid message. + + Source: https://core.telegram.org/bots/api#inputpaidmedia + """ + + PHOTO = "photo" + VIDEO = "video" diff --git a/env/Lib/site-packages/aiogram/enums/keyboard_button_poll_type_type.py b/env/Lib/site-packages/aiogram/enums/keyboard_button_poll_type_type.py new file mode 100644 index 0000000..b6b692f --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/keyboard_button_poll_type_type.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class KeyboardButtonPollTypeType(str, Enum): + """ + This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed. + + Source: https://core.telegram.org/bots/api#keyboardbuttonpolltype + """ + + QUIZ = "quiz" + REGULAR = "regular" diff --git a/env/Lib/site-packages/aiogram/enums/mask_position_point.py b/env/Lib/site-packages/aiogram/enums/mask_position_point.py new file mode 100644 index 0000000..348ae00 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/mask_position_point.py @@ -0,0 +1,14 @@ +from enum import Enum + + +class MaskPositionPoint(str, Enum): + """ + The part of the face relative to which the mask should be placed. + + Source: https://core.telegram.org/bots/api#maskposition + """ + + FOREHEAD = "forehead" + EYES = "eyes" + MOUTH = "mouth" + CHIN = "chin" diff --git a/env/Lib/site-packages/aiogram/enums/menu_button_type.py b/env/Lib/site-packages/aiogram/enums/menu_button_type.py new file mode 100644 index 0000000..4c1015b --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/menu_button_type.py @@ -0,0 +1,13 @@ +from enum import Enum + + +class MenuButtonType(str, Enum): + """ + This object represents an type of Menu button + + Source: https://core.telegram.org/bots/api#menubuttondefault + """ + + DEFAULT = "default" + COMMANDS = "commands" + WEB_APP = "web_app" diff --git a/env/Lib/site-packages/aiogram/enums/message_entity_type.py b/env/Lib/site-packages/aiogram/enums/message_entity_type.py new file mode 100644 index 0000000..b67dc03 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/message_entity_type.py @@ -0,0 +1,29 @@ +from enum import Enum + + +class MessageEntityType(str, Enum): + """ + This object represents type of message entity + + Source: https://core.telegram.org/bots/api#messageentity + """ + + MENTION = "mention" + HASHTAG = "hashtag" + CASHTAG = "cashtag" + BOT_COMMAND = "bot_command" + URL = "url" + EMAIL = "email" + PHONE_NUMBER = "phone_number" + BOLD = "bold" + ITALIC = "italic" + UNDERLINE = "underline" + STRIKETHROUGH = "strikethrough" + SPOILER = "spoiler" + BLOCKQUOTE = "blockquote" + EXPANDABLE_BLOCKQUOTE = "expandable_blockquote" + CODE = "code" + PRE = "pre" + TEXT_LINK = "text_link" + TEXT_MENTION = "text_mention" + CUSTOM_EMOJI = "custom_emoji" diff --git a/env/Lib/site-packages/aiogram/enums/message_origin_type.py b/env/Lib/site-packages/aiogram/enums/message_origin_type.py new file mode 100644 index 0000000..9543665 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/message_origin_type.py @@ -0,0 +1,14 @@ +from enum import Enum + + +class MessageOriginType(str, Enum): + """ + This object represents origin of a message. + + Source: https://core.telegram.org/bots/api#messageorigin + """ + + USER = "user" + HIDDEN_USER = "hidden_user" + CHAT = "chat" + CHANNEL = "channel" diff --git a/env/Lib/site-packages/aiogram/enums/paid_media_type.py b/env/Lib/site-packages/aiogram/enums/paid_media_type.py new file mode 100644 index 0000000..930028f --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/paid_media_type.py @@ -0,0 +1,13 @@ +from enum import Enum + + +class PaidMediaType(str, Enum): + """ + This object represents the type of a media in a paid message. + + Source: https://core.telegram.org/bots/api#paidmedia + """ + + PHOTO = "photo" + PREVIEW = "preview" + VIDEO = "video" diff --git a/env/Lib/site-packages/aiogram/enums/parse_mode.py b/env/Lib/site-packages/aiogram/enums/parse_mode.py new file mode 100644 index 0000000..f17dd98 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/parse_mode.py @@ -0,0 +1,13 @@ +from enum import Enum + + +class ParseMode(str, Enum): + """ + Formatting options + + Source: https://core.telegram.org/bots/api#formatting-options + """ + + MARKDOWN_V2 = "MarkdownV2" + MARKDOWN = "Markdown" + HTML = "HTML" diff --git a/env/Lib/site-packages/aiogram/enums/passport_element_error_type.py b/env/Lib/site-packages/aiogram/enums/passport_element_error_type.py new file mode 100644 index 0000000..cdcb480 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/passport_element_error_type.py @@ -0,0 +1,19 @@ +from enum import Enum + + +class PassportElementErrorType(str, Enum): + """ + This object represents a passport element error type. + + Source: https://core.telegram.org/bots/api#passportelementerror + """ + + DATA = "data" + FRONT_SIDE = "front_side" + REVERSE_SIDE = "reverse_side" + SELFIE = "selfie" + FILE = "file" + FILES = "files" + TRANSLATION_FILE = "translation_file" + TRANSLATION_FILES = "translation_files" + UNSPECIFIED = "unspecified" diff --git a/env/Lib/site-packages/aiogram/enums/poll_type.py b/env/Lib/site-packages/aiogram/enums/poll_type.py new file mode 100644 index 0000000..039d600 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/poll_type.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class PollType(str, Enum): + """ + This object represents poll type + + Source: https://core.telegram.org/bots/api#poll + """ + + REGULAR = "regular" + QUIZ = "quiz" diff --git a/env/Lib/site-packages/aiogram/enums/reaction_type_type.py b/env/Lib/site-packages/aiogram/enums/reaction_type_type.py new file mode 100644 index 0000000..5b0b880 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/reaction_type_type.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class ReactionTypeType(str, Enum): + """ + This object represents reaction type. + + Source: https://core.telegram.org/bots/api#reactiontype + """ + + EMOJI = "emoji" + CUSTOM_EMOJI = "custom_emoji" diff --git a/env/Lib/site-packages/aiogram/enums/revenue_withdrawal_state_type.py b/env/Lib/site-packages/aiogram/enums/revenue_withdrawal_state_type.py new file mode 100644 index 0000000..89a9a04 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/revenue_withdrawal_state_type.py @@ -0,0 +1,13 @@ +from enum import Enum + + +class RevenueWithdrawalStateType(str, Enum): + """ + This object represents a revenue withdrawal state type + + Source: https://core.telegram.org/bots/api#revenuewithdrawalstate + """ + + FAILED = "failed" + PENDING = "pending" + SUCCEEDED = "succeeded" diff --git a/env/Lib/site-packages/aiogram/enums/sticker_format.py b/env/Lib/site-packages/aiogram/enums/sticker_format.py new file mode 100644 index 0000000..6c9441d --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/sticker_format.py @@ -0,0 +1,13 @@ +from enum import Enum + + +class StickerFormat(str, Enum): + """ + Format of the sticker + + Source: https://core.telegram.org/bots/api#createnewstickerset + """ + + STATIC = "static" + ANIMATED = "animated" + VIDEO = "video" diff --git a/env/Lib/site-packages/aiogram/enums/sticker_type.py b/env/Lib/site-packages/aiogram/enums/sticker_type.py new file mode 100644 index 0000000..748f85e --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/sticker_type.py @@ -0,0 +1,13 @@ +from enum import Enum + + +class StickerType(str, Enum): + """ + The part of the face relative to which the mask should be placed. + + Source: https://core.telegram.org/bots/api#maskposition + """ + + REGULAR = "regular" + MASK = "mask" + CUSTOM_EMOJI = "custom_emoji" diff --git a/env/Lib/site-packages/aiogram/enums/topic_icon_color.py b/env/Lib/site-packages/aiogram/enums/topic_icon_color.py new file mode 100644 index 0000000..f40ee71 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/topic_icon_color.py @@ -0,0 +1,16 @@ +from enum import Enum + + +class TopicIconColor(int, Enum): + """ + Color of the topic icon in RGB format. + + Source: https://github.com/telegramdesktop/tdesktop/blob/991fe491c5ae62705d77aa8fdd44a79caf639c45/Telegram/SourceFiles/data/data_forum_topic.cpp#L51-L56 + """ + + BLUE = 0x6FB9F0 + YELLOW = 0xFFD67E + VIOLET = 0xCB86DB + GREEN = 0x8EEE98 + ROSE = 0xFF93B2 + RED = 0xFB6F5F diff --git a/env/Lib/site-packages/aiogram/enums/transaction_partner_type.py b/env/Lib/site-packages/aiogram/enums/transaction_partner_type.py new file mode 100644 index 0000000..b335ac0 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/transaction_partner_type.py @@ -0,0 +1,14 @@ +from enum import Enum + + +class TransactionPartnerType(str, Enum): + """ + This object represents a type of transaction partner. + + Source: https://core.telegram.org/bots/api#transactionpartner + """ + + FRAGMENT = "fragment" + OTHER = "other" + USER = "user" + TELEGRAM_ADS = "telegram_ads" diff --git a/env/Lib/site-packages/aiogram/enums/update_type.py b/env/Lib/site-packages/aiogram/enums/update_type.py new file mode 100644 index 0000000..16fe0e2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/enums/update_type.py @@ -0,0 +1,32 @@ +from enum import Enum + + +class UpdateType(str, Enum): + """ + This object represents the complete list of allowed update types + + Source: https://core.telegram.org/bots/api#update + """ + + MESSAGE = "message" + EDITED_MESSAGE = "edited_message" + CHANNEL_POST = "channel_post" + EDITED_CHANNEL_POST = "edited_channel_post" + BUSINESS_CONNECTION = "business_connection" + BUSINESS_MESSAGE = "business_message" + EDITED_BUSINESS_MESSAGE = "edited_business_message" + DELETED_BUSINESS_MESSAGES = "deleted_business_messages" + MESSAGE_REACTION = "message_reaction" + MESSAGE_REACTION_COUNT = "message_reaction_count" + INLINE_QUERY = "inline_query" + CHOSEN_INLINE_RESULT = "chosen_inline_result" + CALLBACK_QUERY = "callback_query" + SHIPPING_QUERY = "shipping_query" + PRE_CHECKOUT_QUERY = "pre_checkout_query" + POLL = "poll" + POLL_ANSWER = "poll_answer" + MY_CHAT_MEMBER = "my_chat_member" + CHAT_MEMBER = "chat_member" + CHAT_JOIN_REQUEST = "chat_join_request" + CHAT_BOOST = "chat_boost" + REMOVED_CHAT_BOOST = "removed_chat_boost" diff --git a/env/Lib/site-packages/aiogram/exceptions.py b/env/Lib/site-packages/aiogram/exceptions.py new file mode 100644 index 0000000..d195aa7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/exceptions.py @@ -0,0 +1,199 @@ +from typing import Any, Optional + +from aiogram.methods import TelegramMethod +from aiogram.methods.base import TelegramType +from aiogram.utils.link import docs_url + + +class AiogramError(Exception): + """ + Base exception for all aiogram errors. + """ + + +class DetailedAiogramError(AiogramError): + """ + Base exception for all aiogram errors with detailed message. + """ + + url: Optional[str] = None + + def __init__(self, message: str) -> None: + self.message = message + + def __str__(self) -> str: + message = self.message + if self.url: + message += f"\n(background on this error at: {self.url})" + return message + + def __repr__(self) -> str: + return f"{type(self).__name__}('{self}')" + + +class CallbackAnswerException(AiogramError): + """ + Exception for callback answer. + """ + + +class SceneException(AiogramError): + """ + Exception for scenes. + """ + + +class UnsupportedKeywordArgument(DetailedAiogramError): + """ + Exception raised when a keyword argument is passed as filter. + """ + + url = docs_url("migration_2_to_3.html", fragment_="filtering-events") + + +class TelegramAPIError(DetailedAiogramError): + """ + Base exception for all Telegram API errors. + """ + + label: str = "Telegram server says" + + def __init__( + self, + method: TelegramMethod[TelegramType], + message: str, + ) -> None: + super().__init__(message=message) + self.method = method + + def __str__(self) -> str: + original_message = super().__str__() + return f"{self.label} - {original_message}" + + +class TelegramNetworkError(TelegramAPIError): + """ + Base exception for all Telegram network errors. + """ + + label = "HTTP Client says" + + +class TelegramRetryAfter(TelegramAPIError): + """ + Exception raised when flood control exceeds. + """ + + url = "https://core.telegram.org/bots/faq#my-bot-is-hitting-limits-how-do-i-avoid-this" + + def __init__( + self, + method: TelegramMethod[TelegramType], + message: str, + retry_after: int, + ) -> None: + description = f"Flood control exceeded on method {type(method).__name__!r}" + if chat_id := getattr(method, "chat_id", None): + description += f" in chat {chat_id}" + description += f". Retry in {retry_after} seconds." + description += f"\nOriginal description: {message}" + + super().__init__(method=method, message=description) + self.retry_after = retry_after + + +class TelegramMigrateToChat(TelegramAPIError): + """ + Exception raised when chat has been migrated to a supergroup. + """ + + url = "https://core.telegram.org/bots/api#responseparameters" + + def __init__( + self, + method: TelegramMethod[TelegramType], + message: str, + migrate_to_chat_id: int, + ) -> None: + description = f"The group has been migrated to a supergroup with id {migrate_to_chat_id}" + if chat_id := getattr(method, "chat_id", None): + description += f" from {chat_id}" + description += f"\nOriginal description: {message}" + super().__init__(method=method, message=message) + self.migrate_to_chat_id = migrate_to_chat_id + + +class TelegramBadRequest(TelegramAPIError): + """ + Exception raised when request is malformed. + """ + + +class TelegramNotFound(TelegramAPIError): + """ + Exception raised when chat, message, user, etc. not found. + """ + + +class TelegramConflictError(TelegramAPIError): + """ + Exception raised when bot token is already used by another application in polling mode. + """ + + +class TelegramUnauthorizedError(TelegramAPIError): + """ + Exception raised when bot token is invalid. + """ + + +class TelegramForbiddenError(TelegramAPIError): + """ + Exception raised when bot is kicked from chat or etc. + """ + + +class TelegramServerError(TelegramAPIError): + """ + Exception raised when Telegram server returns 5xx error. + """ + + +class RestartingTelegram(TelegramServerError): + """ + Exception raised when Telegram server is restarting. + + It seems like this error is not used by Telegram anymore, + but it's still here for backward compatibility. + + Currently, you should expect that Telegram can raise RetryAfter (with timeout 5 seconds) + error instead of this one. + """ + + +class TelegramEntityTooLarge(TelegramNetworkError): + """ + Exception raised when you are trying to send a file that is too large. + """ + + url = "https://core.telegram.org/bots/api#sending-files" + + +class ClientDecodeError(AiogramError): + """ + Exception raised when client can't decode response. (Malformed response, etc.) + """ + + def __init__(self, message: str, original: Exception, data: Any) -> None: + self.message = message + self.original = original + self.data = data + + def __str__(self) -> str: + original_type = type(self.original) + return ( + f"{self.message}\n" + f"Caused from error: " + f"{original_type.__module__}.{original_type.__name__}: {self.original}\n" + f"Content: {self.data}" + ) diff --git a/env/Lib/site-packages/aiogram/filters/__init__.py b/env/Lib/site-packages/aiogram/filters/__init__.py new file mode 100644 index 0000000..bcadc17 --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/__init__.py @@ -0,0 +1,51 @@ +from .base import Filter +from .chat_member_updated import ( + ADMINISTRATOR, + CREATOR, + IS_ADMIN, + IS_MEMBER, + IS_NOT_MEMBER, + JOIN_TRANSITION, + KICKED, + LEAVE_TRANSITION, + LEFT, + MEMBER, + PROMOTED_TRANSITION, + RESTRICTED, + ChatMemberUpdatedFilter, +) +from .command import Command, CommandObject, CommandStart +from .exception import ExceptionMessageFilter, ExceptionTypeFilter +from .logic import and_f, invert_f, or_f +from .magic_data import MagicData +from .state import StateFilter + +BaseFilter = Filter + +__all__ = ( + "Filter", + "BaseFilter", + "Command", + "CommandObject", + "CommandStart", + "ExceptionMessageFilter", + "ExceptionTypeFilter", + "StateFilter", + "MagicData", + "ChatMemberUpdatedFilter", + "CREATOR", + "ADMINISTRATOR", + "MEMBER", + "RESTRICTED", + "LEFT", + "KICKED", + "IS_MEMBER", + "IS_ADMIN", + "PROMOTED_TRANSITION", + "IS_NOT_MEMBER", + "JOIN_TRANSITION", + "LEAVE_TRANSITION", + "and_f", + "or_f", + "invert_f", +) diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..ae5acd0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..b4feacc Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/callback_data.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/callback_data.cpython-311.pyc new file mode 100644 index 0000000..eb0cdb3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/callback_data.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/chat_member_updated.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/chat_member_updated.cpython-311.pyc new file mode 100644 index 0000000..26dc9ff Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/chat_member_updated.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/command.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/command.cpython-311.pyc new file mode 100644 index 0000000..45ed429 Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/command.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/exception.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/exception.cpython-311.pyc new file mode 100644 index 0000000..d3b9229 Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/exception.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/logic.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/logic.cpython-311.pyc new file mode 100644 index 0000000..381aa49 Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/logic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/magic_data.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/magic_data.cpython-311.pyc new file mode 100644 index 0000000..68a1915 Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/magic_data.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/__pycache__/state.cpython-311.pyc b/env/Lib/site-packages/aiogram/filters/__pycache__/state.cpython-311.pyc new file mode 100644 index 0000000..00fc235 Binary files /dev/null and b/env/Lib/site-packages/aiogram/filters/__pycache__/state.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/filters/base.py b/env/Lib/site-packages/aiogram/filters/base.py new file mode 100644 index 0000000..94f9b6d --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/base.py @@ -0,0 +1,55 @@ +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Union + +if TYPE_CHECKING: + from aiogram.filters.logic import _InvertFilter + + +class Filter(ABC): + """ + If you want to register own filters like builtin filters you will need to write subclass + of this class with overriding the :code:`__call__` + method and adding filter attributes. + """ + + if TYPE_CHECKING: + # This checking type-hint is needed because mypy checks validity of overrides and raises: + # error: Signature of "__call__" incompatible with supertype "BaseFilter" [override] + # https://mypy.readthedocs.io/en/latest/error_code_list.html#check-validity-of-overrides-override + __call__: Callable[..., Awaitable[Union[bool, Dict[str, Any]]]] + else: # pragma: no cover + + @abstractmethod + async def __call__(self, *args: Any, **kwargs: Any) -> Union[bool, Dict[str, Any]]: + """ + This method should be overridden. + + Accepts incoming event and should return boolean or dict. + + :return: :class:`bool` or :class:`Dict[str, Any]` + """ + pass + + def __invert__(self) -> "_InvertFilter": + from aiogram.filters.logic import invert_f + + return invert_f(self) + + def update_handler_flags(self, flags: Dict[str, Any]) -> None: + """ + Also if you want to extend handler flags with using this filter + you should implement this method + + :param flags: existing flags, can be updated directly + """ + pass + + def _signature_to_string(self, *args: Any, **kwargs: Any) -> str: + items = [repr(arg) for arg in args] + items.extend([f"{k}={v!r}" for k, v in kwargs.items() if v is not None]) + + return f"{type(self).__name__}({', '.join(items)})" + + def __await__(self): # type: ignore # pragma: no cover + # Is needed only for inspection and this method is never be called + return self.__call__ diff --git a/env/Lib/site-packages/aiogram/filters/callback_data.py b/env/Lib/site-packages/aiogram/filters/callback_data.py new file mode 100644 index 0000000..17ccffb --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/callback_data.py @@ -0,0 +1,207 @@ +from __future__ import annotations + +import sys +import types +import typing +from decimal import Decimal +from enum import Enum +from fractions import Fraction +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + Dict, + Literal, + Optional, + Type, + TypeVar, + Union, +) +from uuid import UUID + +from magic_filter import MagicFilter +from pydantic import BaseModel +from pydantic.fields import FieldInfo + +from aiogram.filters.base import Filter +from aiogram.types import CallbackQuery + +T = TypeVar("T", bound="CallbackData") + +MAX_CALLBACK_LENGTH: int = 64 + + +_UNION_TYPES = {typing.Union} +if sys.version_info >= (3, 10): # pragma: no cover + _UNION_TYPES.add(types.UnionType) + + +class CallbackDataException(Exception): + pass + + +class CallbackData(BaseModel): + """ + Base class for callback data wrapper + + This class should be used as super-class of user-defined callbacks. + + The class-keyword :code:`prefix` is required to define prefix + and also the argument :code:`sep` can be passed to define separator (default is :code:`:`). + """ + + if TYPE_CHECKING: + __separator__: ClassVar[str] + """Data separator (default is :code:`:`)""" + __prefix__: ClassVar[str] + """Callback prefix""" + + def __init_subclass__(cls, **kwargs: Any) -> None: + if "prefix" not in kwargs: + raise ValueError( + f"prefix required, usage example: " + f"`class {cls.__name__}(CallbackData, prefix='my_callback'): ...`" + ) + cls.__separator__ = kwargs.pop("sep", ":") + cls.__prefix__ = kwargs.pop("prefix") + if cls.__separator__ in cls.__prefix__: + raise ValueError( + f"Separator symbol {cls.__separator__!r} can not be used " + f"inside prefix {cls.__prefix__!r}" + ) + super().__init_subclass__(**kwargs) + + def _encode_value(self, key: str, value: Any) -> str: + if value is None: + return "" + if isinstance(value, Enum): + return str(value.value) + if isinstance(value, UUID): + return value.hex + if isinstance(value, bool): + return str(int(value)) + if isinstance(value, (int, str, float, Decimal, Fraction)): + return str(value) + raise ValueError( + f"Attribute {key}={value!r} of type {type(value).__name__!r}" + f" can not be packed to callback data" + ) + + def pack(self) -> str: + """ + Generate callback data string + + :return: valid callback data for Telegram Bot API + """ + result = [self.__prefix__] + for key, value in self.model_dump(mode="json").items(): + encoded = self._encode_value(key, value) + if self.__separator__ in encoded: + raise ValueError( + f"Separator symbol {self.__separator__!r} can not be used " + f"in value {key}={encoded!r}" + ) + result.append(encoded) + callback_data = self.__separator__.join(result) + if len(callback_data.encode()) > MAX_CALLBACK_LENGTH: + raise ValueError( + f"Resulted callback data is too long! " + f"len({callback_data!r}.encode()) > {MAX_CALLBACK_LENGTH}" + ) + return callback_data + + @classmethod + def unpack(cls: Type[T], value: str) -> T: + """ + Parse callback data string + + :param value: value from Telegram + :return: instance of CallbackData + """ + prefix, *parts = value.split(cls.__separator__) + names = cls.model_fields.keys() + if len(parts) != len(names): + raise TypeError( + f"Callback data {cls.__name__!r} takes {len(names)} arguments " + f"but {len(parts)} were given" + ) + if prefix != cls.__prefix__: + raise ValueError(f"Bad prefix ({prefix!r} != {cls.__prefix__!r})") + payload = {} + for k, v in zip(names, parts): # type: str, Optional[str] + if field := cls.model_fields.get(k): + if v == "" and _check_field_is_nullable(field): + v = None + payload[k] = v + return cls(**payload) + + @classmethod + def filter(cls, rule: Optional[MagicFilter] = None) -> CallbackQueryFilter: + """ + Generates a filter for callback query with rule + + :param rule: magic rule + :return: instance of filter + """ + return CallbackQueryFilter(callback_data=cls, rule=rule) + + +class CallbackQueryFilter(Filter): + """ + This filter helps to handle callback query. + + Should not be used directly, you should create the instance of this filter + via callback data instance + """ + + __slots__ = ( + "callback_data", + "rule", + ) + + def __init__( + self, + *, + callback_data: Type[CallbackData], + rule: Optional[MagicFilter] = None, + ): + """ + :param callback_data: Expected type of callback data + :param rule: Magic rule + """ + self.callback_data = callback_data + self.rule = rule + + def __str__(self) -> str: + return self._signature_to_string( + callback_data=self.callback_data, + rule=self.rule, + ) + + async def __call__(self, query: CallbackQuery) -> Union[Literal[False], Dict[str, Any]]: + if not isinstance(query, CallbackQuery) or not query.data: + return False + try: + callback_data = self.callback_data.unpack(query.data) + except (TypeError, ValueError): + return False + + if self.rule is None or self.rule.resolve(callback_data): + return {"callback_data": callback_data} + return False + + +def _check_field_is_nullable(field: FieldInfo) -> bool: + """ + Check if the given field is nullable. + + :param field: The FieldInfo object representing the field to check. + :return: True if the field is nullable, False otherwise. + + """ + if not field.is_required(): + return True + + return typing.get_origin(field.annotation) in _UNION_TYPES and type(None) in typing.get_args( + field.annotation + ) diff --git a/env/Lib/site-packages/aiogram/filters/chat_member_updated.py b/env/Lib/site-packages/aiogram/filters/chat_member_updated.py new file mode 100644 index 0000000..23cf0e9 --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/chat_member_updated.py @@ -0,0 +1,204 @@ +from typing import Any, Dict, Optional, TypeVar, Union + +from aiogram.filters.base import Filter +from aiogram.types import ChatMember, ChatMemberUpdated + +MarkerT = TypeVar("MarkerT", bound="_MemberStatusMarker") +MarkerGroupT = TypeVar("MarkerGroupT", bound="_MemberStatusGroupMarker") +TransitionT = TypeVar("TransitionT", bound="_MemberStatusTransition") + + +class _MemberStatusMarker: + __slots__ = ( + "name", + "is_member", + ) + + def __init__(self, name: str, *, is_member: Optional[bool] = None) -> None: + self.name = name + self.is_member = is_member + + def __str__(self) -> str: + result = self.name.upper() + if self.is_member is not None: + result = ("+" if self.is_member else "-") + result + return result # noqa: RET504 + + def __pos__(self: MarkerT) -> MarkerT: + return type(self)(name=self.name, is_member=True) + + def __neg__(self: MarkerT) -> MarkerT: + return type(self)(name=self.name, is_member=False) + + def __or__( + self, other: Union["_MemberStatusMarker", "_MemberStatusGroupMarker"] + ) -> "_MemberStatusGroupMarker": + if isinstance(other, _MemberStatusMarker): + return _MemberStatusGroupMarker(self, other) + if isinstance(other, _MemberStatusGroupMarker): + return other | self + raise TypeError( + f"unsupported operand type(s) for |: " + f"{type(self).__name__!r} and {type(other).__name__!r}" + ) + + __ror__ = __or__ + + def __rshift__( + self, other: Union["_MemberStatusMarker", "_MemberStatusGroupMarker"] + ) -> "_MemberStatusTransition": + old = _MemberStatusGroupMarker(self) + if isinstance(other, _MemberStatusMarker): + return _MemberStatusTransition(old=old, new=_MemberStatusGroupMarker(other)) + if isinstance(other, _MemberStatusGroupMarker): + return _MemberStatusTransition(old=old, new=other) + raise TypeError( + f"unsupported operand type(s) for >>: " + f"{type(self).__name__!r} and {type(other).__name__!r}" + ) + + def __lshift__( + self, other: Union["_MemberStatusMarker", "_MemberStatusGroupMarker"] + ) -> "_MemberStatusTransition": + new = _MemberStatusGroupMarker(self) + if isinstance(other, _MemberStatusMarker): + return _MemberStatusTransition(old=_MemberStatusGroupMarker(other), new=new) + if isinstance(other, _MemberStatusGroupMarker): + return _MemberStatusTransition(old=other, new=new) + raise TypeError( + f"unsupported operand type(s) for <<: " + f"{type(self).__name__!r} and {type(other).__name__!r}" + ) + + def __hash__(self) -> int: + return hash((self.name, self.is_member)) + + def check(self, *, member: ChatMember) -> bool: + # Not all member types have `is_member` attribute + is_member = getattr(member, "is_member", None) + status = getattr(member, "status", None) + if self.is_member is not None and is_member != self.is_member: + return False + return self.name == status + + +class _MemberStatusGroupMarker: + __slots__ = ("statuses",) + + def __init__(self, *statuses: _MemberStatusMarker) -> None: + if not statuses: + raise ValueError("Member status group should have at least one status included") + self.statuses = frozenset(statuses) + + def __or__( + self: MarkerGroupT, other: Union["_MemberStatusMarker", "_MemberStatusGroupMarker"] + ) -> MarkerGroupT: + if isinstance(other, _MemberStatusMarker): + return type(self)(*self.statuses, other) + if isinstance(other, _MemberStatusGroupMarker): + return type(self)(*self.statuses, *other.statuses) + raise TypeError( + f"unsupported operand type(s) for |: " + f"{type(self).__name__!r} and {type(other).__name__!r}" + ) + + def __rshift__( + self, other: Union["_MemberStatusMarker", "_MemberStatusGroupMarker"] + ) -> "_MemberStatusTransition": + if isinstance(other, _MemberStatusMarker): + return _MemberStatusTransition(old=self, new=_MemberStatusGroupMarker(other)) + if isinstance(other, _MemberStatusGroupMarker): + return _MemberStatusTransition(old=self, new=other) + raise TypeError( + f"unsupported operand type(s) for >>: " + f"{type(self).__name__!r} and {type(other).__name__!r}" + ) + + def __lshift__( + self, other: Union["_MemberStatusMarker", "_MemberStatusGroupMarker"] + ) -> "_MemberStatusTransition": + if isinstance(other, _MemberStatusMarker): + return _MemberStatusTransition(old=_MemberStatusGroupMarker(other), new=self) + if isinstance(other, _MemberStatusGroupMarker): + return _MemberStatusTransition(old=other, new=self) + raise TypeError( + f"unsupported operand type(s) for <<: " + f"{type(self).__name__!r} and {type(other).__name__!r}" + ) + + def __str__(self) -> str: + result = " | ".join(map(str, sorted(self.statuses, key=str))) + if len(self.statuses) != 1: + return f"({result})" + return result + + def check(self, *, member: ChatMember) -> bool: + return any(status.check(member=member) for status in self.statuses) + + +class _MemberStatusTransition: + __slots__ = ( + "old", + "new", + ) + + def __init__(self, *, old: _MemberStatusGroupMarker, new: _MemberStatusGroupMarker) -> None: + self.old = old + self.new = new + + def __str__(self) -> str: + return f"{self.old} >> {self.new}" + + def __invert__(self: TransitionT) -> TransitionT: + return type(self)(old=self.new, new=self.old) + + def check(self, *, old: ChatMember, new: ChatMember) -> bool: + return self.old.check(member=old) and self.new.check(member=new) + + +CREATOR = _MemberStatusMarker("creator") +ADMINISTRATOR = _MemberStatusMarker("administrator") +MEMBER = _MemberStatusMarker("member") +RESTRICTED = _MemberStatusMarker("restricted") +LEFT = _MemberStatusMarker("left") +KICKED = _MemberStatusMarker("kicked") + +IS_MEMBER = CREATOR | ADMINISTRATOR | MEMBER | +RESTRICTED +IS_ADMIN = CREATOR | ADMINISTRATOR +IS_NOT_MEMBER = LEFT | KICKED | -RESTRICTED + +JOIN_TRANSITION = IS_NOT_MEMBER >> IS_MEMBER +LEAVE_TRANSITION = ~JOIN_TRANSITION +PROMOTED_TRANSITION = (MEMBER | RESTRICTED | LEFT | KICKED) >> ADMINISTRATOR + + +class ChatMemberUpdatedFilter(Filter): + __slots__ = ("member_status_changed",) + + def __init__( + self, + member_status_changed: Union[ + _MemberStatusMarker, + _MemberStatusGroupMarker, + _MemberStatusTransition, + ], + ): + self.member_status_changed = member_status_changed + + def __str__(self) -> str: + return self._signature_to_string( + member_status_changed=self.member_status_changed, + ) + + async def __call__(self, member_updated: ChatMemberUpdated) -> Union[bool, Dict[str, Any]]: + old = member_updated.old_chat_member + new = member_updated.new_chat_member + rule = self.member_status_changed + + if isinstance(rule, (_MemberStatusMarker, _MemberStatusGroupMarker)): + return rule.check(member=new) + if isinstance(rule, _MemberStatusTransition): + return rule.check(old=old, new=new) + + # Impossible variant in due to pydantic validation + return False # pragma: no cover diff --git a/env/Lib/site-packages/aiogram/filters/command.py b/env/Lib/site-packages/aiogram/filters/command.py new file mode 100644 index 0000000..f52ac26 --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/command.py @@ -0,0 +1,298 @@ +from __future__ import annotations + +import re +from dataclasses import dataclass, field, replace +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterable, + Match, + Optional, + Pattern, + Sequence, + Union, + cast, +) + +from magic_filter import MagicFilter + +from aiogram.filters.base import Filter +from aiogram.types import BotCommand, Message +from aiogram.utils.deep_linking import decode_payload + +if TYPE_CHECKING: + from aiogram import Bot + +# TODO: rm type ignore after py3.8 support expiration or mypy bug fix +CommandPatternType = Union[str, re.Pattern, BotCommand] # type: ignore[type-arg] + + +class CommandException(Exception): + pass + + +class Command(Filter): + """ + This filter can be helpful for handling commands from the text messages. + + Works only with :class:`aiogram.types.message.Message` events which have the :code:`text`. + """ + + __slots__ = ( + "commands", + "prefix", + "ignore_case", + "ignore_mention", + "magic", + ) + + def __init__( + self, + *values: CommandPatternType, + commands: Optional[Union[Sequence[CommandPatternType], CommandPatternType]] = None, + prefix: str = "/", + ignore_case: bool = False, + ignore_mention: bool = False, + magic: Optional[MagicFilter] = None, + ): + """ + List of commands (string or compiled regexp patterns) + + :param prefix: Prefix for command. + Prefix is always a single char but here you can pass all of allowed prefixes, + for example: :code:`"/!"` will work with commands prefixed + by :code:`"/"` or :code:`"!"`. + :param ignore_case: Ignore case (Does not work with regexp, use flags instead) + :param ignore_mention: Ignore bot mention. By default, + bot can not handle commands intended for other bots + :param magic: Validate command object via Magic filter after all checks done + """ + if commands is None: + commands = [] + if isinstance(commands, (str, re.Pattern, BotCommand)): + commands = [commands] + + if not isinstance(commands, Iterable): + raise ValueError( + "Command filter only supports str, re.Pattern, BotCommand object" + " or their Iterable" + ) + + items = [] + for command in (*values, *commands): + if isinstance(command, BotCommand): + command = command.command + if not isinstance(command, (str, re.Pattern)): + raise ValueError( + "Command filter only supports str, re.Pattern, BotCommand object" + " or their Iterable" + ) + if ignore_case and isinstance(command, str): + command = command.casefold() + items.append(command) + + if not items: + raise ValueError("At least one command should be specified") + + self.commands = tuple(items) + self.prefix = prefix + self.ignore_case = ignore_case + self.ignore_mention = ignore_mention + self.magic = magic + + def __str__(self) -> str: + return self._signature_to_string( + *self.commands, + prefix=self.prefix, + ignore_case=self.ignore_case, + ignore_mention=self.ignore_mention, + magic=self.magic, + ) + + def update_handler_flags(self, flags: Dict[str, Any]) -> None: + commands = flags.setdefault("commands", []) + commands.append(self) + + async def __call__(self, message: Message, bot: Bot) -> Union[bool, Dict[str, Any]]: + if not isinstance(message, Message): + return False + + text = message.text or message.caption + if not text: + return False + + try: + command = await self.parse_command(text=text, bot=bot) + except CommandException: + return False + result = {"command": command} + if command.magic_result and isinstance(command.magic_result, dict): + result.update(command.magic_result) + return result + + def extract_command(self, text: str) -> CommandObject: + # First step: separate command with arguments + # "/command@mention arg1 arg2" -> "/command@mention", ["arg1 arg2"] + try: + full_command, *args = text.split(maxsplit=1) + except ValueError: + raise CommandException("not enough values to unpack") + + # Separate command into valuable parts + # "/command@mention" -> "/", ("command", "@", "mention") + prefix, (command, _, mention) = full_command[0], full_command[1:].partition("@") + return CommandObject( + prefix=prefix, + command=command, + mention=mention or None, + args=args[0] if args else None, + ) + + def validate_prefix(self, command: CommandObject) -> None: + if command.prefix not in self.prefix: + raise CommandException("Invalid command prefix") + + async def validate_mention(self, bot: Bot, command: CommandObject) -> None: + if command.mention and not self.ignore_mention: + me = await bot.me() + if me.username and command.mention.lower() != me.username.lower(): + raise CommandException("Mention did not match") + + def validate_command(self, command: CommandObject) -> CommandObject: + for allowed_command in cast(Sequence[CommandPatternType], self.commands): + # Command can be presented as regexp pattern or raw string + # then need to validate that in different ways + if isinstance(allowed_command, Pattern): # Regexp + result = allowed_command.match(command.command) + if result: + return replace(command, regexp_match=result) + + command_name = command.command + if self.ignore_case: + command_name = command_name.casefold() + + if command_name == allowed_command: # String + return command + raise CommandException("Command did not match pattern") + + async def parse_command(self, text: str, bot: Bot) -> CommandObject: + """ + Extract command from the text and validate + + :param text: + :param bot: + :return: + """ + command = self.extract_command(text) + self.validate_prefix(command=command) + await self.validate_mention(bot=bot, command=command) + command = self.validate_command(command) + command = self.do_magic(command=command) + return command # noqa: RET504 + + def do_magic(self, command: CommandObject) -> Any: + if self.magic is None: + return command + result = self.magic.resolve(command) + if not result: + raise CommandException("Rejected via magic filter") + return replace(command, magic_result=result) + + +@dataclass(frozen=True) +class CommandObject: + """ + Instance of this object is always has command and it prefix. + Can be passed as keyword argument **command** to the handler + """ + + prefix: str = "/" + """Command prefix""" + command: str = "" + """Command without prefix and mention""" + mention: Optional[str] = None + """Mention (if available)""" + args: Optional[str] = field(repr=False, default=None) + """Command argument""" + regexp_match: Optional[Match[str]] = field(repr=False, default=None) + """Will be presented match result if the command is presented as regexp in filter""" + magic_result: Optional[Any] = field(repr=False, default=None) + + @property + def mentioned(self) -> bool: + """ + This command has mention? + """ + return bool(self.mention) + + @property + def text(self) -> str: + """ + Generate original text from object + """ + line = self.prefix + self.command + if self.mention: + line += "@" + self.mention + if self.args: + line += " " + self.args + return line + + +class CommandStart(Command): + def __init__( + self, + deep_link: bool = False, + deep_link_encoded: bool = False, + ignore_case: bool = False, + ignore_mention: bool = False, + magic: Optional[MagicFilter] = None, + ): + super().__init__( + "start", + prefix="/", + ignore_case=ignore_case, + ignore_mention=ignore_mention, + magic=magic, + ) + self.deep_link = deep_link + self.deep_link_encoded = deep_link_encoded + + def __str__(self) -> str: + return self._signature_to_string( + ignore_case=self.ignore_case, + ignore_mention=self.ignore_mention, + magic=self.magic, + deep_link=self.deep_link, + deep_link_encoded=self.deep_link_encoded, + ) + + async def parse_command(self, text: str, bot: Bot) -> CommandObject: + """ + Extract command from the text and validate + + :param text: + :param bot: + :return: + """ + command = self.extract_command(text) + self.validate_prefix(command=command) + await self.validate_mention(bot=bot, command=command) + command = self.validate_command(command) + command = self.validate_deeplink(command=command) + command = self.do_magic(command=command) + return command # noqa: RET504 + + def validate_deeplink(self, command: CommandObject) -> CommandObject: + if not self.deep_link: + return command + if not command.args: + raise CommandException("Deep-link was missing") + args = command.args + if self.deep_link_encoded: + try: + args = decode_payload(args) + except UnicodeDecodeError as e: + raise CommandException(f"Failed to decode Base64: {e}") + return replace(command, args=args) + return command diff --git a/env/Lib/site-packages/aiogram/filters/exception.py b/env/Lib/site-packages/aiogram/filters/exception.py new file mode 100644 index 0000000..2530d75 --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/exception.py @@ -0,0 +1,55 @@ +import re +from typing import Any, Dict, Pattern, Type, Union, cast + +from aiogram.filters.base import Filter +from aiogram.types import TelegramObject +from aiogram.types.error_event import ErrorEvent + + +class ExceptionTypeFilter(Filter): + """ + Allows to match exception by type + """ + + __slots__ = ("exceptions",) + + def __init__(self, *exceptions: Type[Exception]): + """ + :param exceptions: Exception type(s) + """ + if not exceptions: + raise ValueError("At least one exception type is required") + self.exceptions = exceptions + + async def __call__(self, obj: TelegramObject) -> Union[bool, Dict[str, Any]]: + return isinstance(cast(ErrorEvent, obj).exception, self.exceptions) + + +class ExceptionMessageFilter(Filter): + """ + Allow to match exception by message + """ + + __slots__ = ("pattern",) + + def __init__(self, pattern: Union[str, Pattern[str]]): + """ + :param pattern: Regexp pattern + """ + if isinstance(pattern, str): + pattern = re.compile(pattern) + self.pattern = pattern + + def __str__(self) -> str: + return self._signature_to_string( + pattern=self.pattern, + ) + + async def __call__( + self, + obj: TelegramObject, + ) -> Union[bool, Dict[str, Any]]: + result = self.pattern.match(str(cast(ErrorEvent, obj).exception)) + if not result: + return False + return {"match_exception": result} diff --git a/env/Lib/site-packages/aiogram/filters/logic.py b/env/Lib/site-packages/aiogram/filters/logic.py new file mode 100644 index 0000000..7cd2503 --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/logic.py @@ -0,0 +1,77 @@ +from abc import ABC +from typing import TYPE_CHECKING, Any, Dict, Union + +from aiogram.filters import Filter + +if TYPE_CHECKING: + from aiogram.dispatcher.event.handler import CallbackType, FilterObject + + +class _LogicFilter(Filter, ABC): + pass + + +class _InvertFilter(_LogicFilter): + __slots__ = ("target",) + + def __init__(self, target: "FilterObject") -> None: + self.target = target + + async def __call__(self, *args: Any, **kwargs: Any) -> Union[bool, Dict[str, Any]]: + return not bool(await self.target.call(*args, **kwargs)) + + +class _AndFilter(_LogicFilter): + __slots__ = ("targets",) + + def __init__(self, *targets: "FilterObject") -> None: + self.targets = targets + + async def __call__(self, *args: Any, **kwargs: Any) -> Union[bool, Dict[str, Any]]: + final_result = {} + + for target in self.targets: + result = await target.call(*args, **kwargs) + if not result: + return False + if isinstance(result, dict): + final_result.update(result) + + if final_result: + return final_result + return True + + +class _OrFilter(_LogicFilter): + __slots__ = ("targets",) + + def __init__(self, *targets: "FilterObject") -> None: + self.targets = targets + + async def __call__(self, *args: Any, **kwargs: Any) -> Union[bool, Dict[str, Any]]: + for target in self.targets: + result = await target.call(*args, **kwargs) + if not result: + continue + if isinstance(result, dict): + return result + return bool(result) + return False + + +def and_f(*targets: "CallbackType") -> _AndFilter: + from aiogram.dispatcher.event.handler import FilterObject + + return _AndFilter(*(FilterObject(target) for target in targets)) + + +def or_f(*targets: "CallbackType") -> _OrFilter: + from aiogram.dispatcher.event.handler import FilterObject + + return _OrFilter(*(FilterObject(target) for target in targets)) + + +def invert_f(target: "CallbackType") -> _InvertFilter: + from aiogram.dispatcher.event.handler import FilterObject + + return _InvertFilter(FilterObject(target)) diff --git a/env/Lib/site-packages/aiogram/filters/magic_data.py b/env/Lib/site-packages/aiogram/filters/magic_data.py new file mode 100644 index 0000000..5c0d474 --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/magic_data.py @@ -0,0 +1,27 @@ +from typing import Any + +from magic_filter import AttrDict, MagicFilter + +from aiogram.filters.base import Filter +from aiogram.types import TelegramObject + + +class MagicData(Filter): + """ + This filter helps to filter event with contextual data + """ + + __slots__ = ("magic_data",) + + def __init__(self, magic_data: MagicFilter) -> None: + self.magic_data = magic_data + + async def __call__(self, event: TelegramObject, *args: Any, **kwargs: Any) -> Any: + return self.magic_data.resolve( + AttrDict({"event": event, **dict(enumerate(args)), **kwargs}) + ) + + def __str__(self) -> str: + return self._signature_to_string( + magic_data=self.magic_data, + ) diff --git a/env/Lib/site-packages/aiogram/filters/state.py b/env/Lib/site-packages/aiogram/filters/state.py new file mode 100644 index 0000000..82a141c --- /dev/null +++ b/env/Lib/site-packages/aiogram/filters/state.py @@ -0,0 +1,43 @@ +from inspect import isclass +from typing import Any, Dict, Optional, Sequence, Type, Union, cast + +from aiogram.filters.base import Filter +from aiogram.fsm.state import State, StatesGroup +from aiogram.types import TelegramObject + +StateType = Union[str, None, State, StatesGroup, Type[StatesGroup]] + + +class StateFilter(Filter): + """ + State filter + """ + + __slots__ = ("states",) + + def __init__(self, *states: StateType) -> None: + if not states: + raise ValueError("At least one state is required") + + self.states = states + + def __str__(self) -> str: + return self._signature_to_string( + *self.states, + ) + + async def __call__( + self, obj: TelegramObject, raw_state: Optional[str] = None + ) -> Union[bool, Dict[str, Any]]: + allowed_states = cast(Sequence[StateType], self.states) + for allowed_state in allowed_states: + if isinstance(allowed_state, str) or allowed_state is None: + if allowed_state == "*" or raw_state == allowed_state: + return True + elif isinstance(allowed_state, (State, StatesGroup)): + if allowed_state(event=obj, raw_state=raw_state): + return True + elif isclass(allowed_state) and issubclass(allowed_state, StatesGroup): + if allowed_state()(event=obj, raw_state=raw_state): + return True + return False diff --git a/env/Lib/site-packages/aiogram/fsm/__init__.py b/env/Lib/site-packages/aiogram/fsm/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/fsm/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..6550804 Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/__pycache__/context.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/__pycache__/context.cpython-311.pyc new file mode 100644 index 0000000..109c39e Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/__pycache__/context.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/__pycache__/middleware.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/__pycache__/middleware.cpython-311.pyc new file mode 100644 index 0000000..a4bc62b Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/__pycache__/middleware.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/__pycache__/scene.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/__pycache__/scene.cpython-311.pyc new file mode 100644 index 0000000..a55a4fb Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/__pycache__/scene.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/__pycache__/state.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/__pycache__/state.cpython-311.pyc new file mode 100644 index 0000000..a3f4cac Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/__pycache__/state.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/__pycache__/strategy.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/__pycache__/strategy.cpython-311.pyc new file mode 100644 index 0000000..0df1f7f Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/__pycache__/strategy.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/context.py b/env/Lib/site-packages/aiogram/fsm/context.py new file mode 100644 index 0000000..53a8ea4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/context.py @@ -0,0 +1,32 @@ +from typing import Any, Dict, Optional + +from aiogram.fsm.storage.base import BaseStorage, StateType, StorageKey + + +class FSMContext: + def __init__(self, storage: BaseStorage, key: StorageKey) -> None: + self.storage = storage + self.key = key + + async def set_state(self, state: StateType = None) -> None: + await self.storage.set_state(key=self.key, state=state) + + async def get_state(self) -> Optional[str]: + return await self.storage.get_state(key=self.key) + + async def set_data(self, data: Dict[str, Any]) -> None: + await self.storage.set_data(key=self.key, data=data) + + async def get_data(self) -> Dict[str, Any]: + return await self.storage.get_data(key=self.key) + + async def update_data( + self, data: Optional[Dict[str, Any]] = None, **kwargs: Any + ) -> Dict[str, Any]: + if data: + kwargs.update(data) + return await self.storage.update_data(key=self.key, data=kwargs) + + async def clear(self) -> None: + await self.set_state(state=None) + await self.set_data({}) diff --git a/env/Lib/site-packages/aiogram/fsm/middleware.py b/env/Lib/site-packages/aiogram/fsm/middleware.py new file mode 100644 index 0000000..de93457 --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/middleware.py @@ -0,0 +1,113 @@ +from typing import Any, Awaitable, Callable, Dict, Optional, cast + +from aiogram import Bot +from aiogram.dispatcher.middlewares.base import BaseMiddleware +from aiogram.dispatcher.middlewares.user_context import EVENT_CONTEXT_KEY, EventContext +from aiogram.fsm.context import FSMContext +from aiogram.fsm.storage.base import ( + DEFAULT_DESTINY, + BaseEventIsolation, + BaseStorage, + StorageKey, +) +from aiogram.fsm.strategy import FSMStrategy, apply_strategy +from aiogram.types import TelegramObject + + +class FSMContextMiddleware(BaseMiddleware): + def __init__( + self, + storage: BaseStorage, + events_isolation: BaseEventIsolation, + strategy: FSMStrategy = FSMStrategy.USER_IN_CHAT, + ) -> None: + self.storage = storage + self.strategy = strategy + self.events_isolation = events_isolation + + async def __call__( + self, + handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + bot: Bot = cast(Bot, data["bot"]) + context = self.resolve_event_context(bot, data) + data["fsm_storage"] = self.storage + if context: + # Bugfix: https://github.com/aiogram/aiogram/issues/1317 + # State should be loaded after lock is acquired + async with self.events_isolation.lock(key=context.key): + data.update({"state": context, "raw_state": await context.get_state()}) + return await handler(event, data) + return await handler(event, data) + + def resolve_event_context( + self, + bot: Bot, + data: Dict[str, Any], + destiny: str = DEFAULT_DESTINY, + ) -> Optional[FSMContext]: + event_context: EventContext = cast(EventContext, data.get(EVENT_CONTEXT_KEY)) + return self.resolve_context( + bot=bot, + chat_id=event_context.chat_id, + user_id=event_context.user_id, + thread_id=event_context.thread_id, + business_connection_id=event_context.business_connection_id, + destiny=destiny, + ) + + def resolve_context( + self, + bot: Bot, + chat_id: Optional[int], + user_id: Optional[int], + thread_id: Optional[int] = None, + business_connection_id: Optional[str] = None, + destiny: str = DEFAULT_DESTINY, + ) -> Optional[FSMContext]: + if chat_id is None: + chat_id = user_id + + if chat_id is not None and user_id is not None: + chat_id, user_id, thread_id = apply_strategy( + chat_id=chat_id, + user_id=user_id, + thread_id=thread_id, + strategy=self.strategy, + ) + return self.get_context( + bot=bot, + chat_id=chat_id, + user_id=user_id, + thread_id=thread_id, + business_connection_id=business_connection_id, + destiny=destiny, + ) + return None + + def get_context( + self, + bot: Bot, + chat_id: int, + user_id: int, + thread_id: Optional[int] = None, + business_connection_id: Optional[str] = None, + destiny: str = DEFAULT_DESTINY, + ) -> FSMContext: + return FSMContext( + storage=self.storage, + key=StorageKey( + user_id=user_id, + chat_id=chat_id, + bot_id=bot.id, + thread_id=thread_id, + business_connection_id=business_connection_id, + destiny=destiny, + ), + ) + + async def close(self) -> None: + await self.storage.close() + await self.events_isolation.close() diff --git a/env/Lib/site-packages/aiogram/fsm/scene.py b/env/Lib/site-packages/aiogram/fsm/scene.py new file mode 100644 index 0000000..fe4de5c --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/scene.py @@ -0,0 +1,912 @@ +from __future__ import annotations + +import inspect +from collections import defaultdict +from dataclasses import dataclass, replace +from enum import Enum, auto +from typing import Any, ClassVar, Dict, List, Optional, Tuple, Type, Union + +from typing_extensions import Self + +from aiogram import loggers +from aiogram.dispatcher.dispatcher import Dispatcher +from aiogram.dispatcher.event.bases import NextMiddlewareType +from aiogram.dispatcher.event.handler import CallableObject, CallbackType +from aiogram.dispatcher.flags import extract_flags_from_object +from aiogram.dispatcher.router import Router +from aiogram.exceptions import SceneException +from aiogram.filters import StateFilter +from aiogram.fsm.context import FSMContext +from aiogram.fsm.state import State +from aiogram.fsm.storage.memory import MemoryStorageRecord +from aiogram.types import TelegramObject, Update + + +class HistoryManager: + def __init__(self, state: FSMContext, destiny: str = "scenes_history", size: int = 10): + self._size = size + self._state = state + self._history_state = FSMContext( + storage=state.storage, key=replace(state.key, destiny=destiny) + ) + + async def push(self, state: Optional[str], data: Dict[str, Any]) -> None: + history_data = await self._history_state.get_data() + history = history_data.setdefault("history", []) + history.append({"state": state, "data": data}) + if len(history) > self._size: + history = history[-self._size :] + loggers.scene.debug("Push state=%s data=%s to history", state, data) + + await self._history_state.update_data(history=history) + + async def pop(self) -> Optional[MemoryStorageRecord]: + history_data = await self._history_state.get_data() + history = history_data.setdefault("history", []) + if not history: + return None + record = history.pop() + state = record["state"] + data = record["data"] + if not history: + await self._history_state.set_data({}) + else: + await self._history_state.update_data(history=history) + loggers.scene.debug("Pop state=%s data=%s from history", state, data) + return MemoryStorageRecord(state=state, data=data) + + async def get(self) -> Optional[MemoryStorageRecord]: + history_data = await self._history_state.get_data() + history = history_data.setdefault("history", []) + if not history: + return None + return MemoryStorageRecord(**history[-1]) + + async def all(self) -> List[MemoryStorageRecord]: + history_data = await self._history_state.get_data() + history = history_data.setdefault("history", []) + return [MemoryStorageRecord(**item) for item in history] + + async def clear(self) -> None: + loggers.scene.debug("Clear history") + await self._history_state.set_data({}) + + async def snapshot(self) -> None: + state = await self._state.get_state() + data = await self._state.get_data() + await self.push(state, data) + + async def _set_state(self, state: Optional[str], data: Dict[str, Any]) -> None: + await self._state.set_state(state) + await self._state.set_data(data) + + async def rollback(self) -> Optional[str]: + previous_state = await self.pop() + if not previous_state: + await self._set_state(None, {}) + return None + + loggers.scene.debug( + "Rollback to state=%s data=%s", + previous_state.state, + previous_state.data, + ) + await self._set_state(previous_state.state, previous_state.data) + return previous_state.state + + +class ObserverDecorator: + def __init__( + self, + name: str, + filters: tuple[CallbackType, ...], + action: SceneAction | None = None, + after: Optional[After] = None, + ) -> None: + self.name = name + self.filters = filters + self.action = action + self.after = after + + def _wrap_filter(self, target: Type[Scene] | CallbackType) -> None: + handlers = getattr(target, "__aiogram_handler__", None) + if not handlers: + handlers = [] + setattr(target, "__aiogram_handler__", handlers) + + handlers.append( + HandlerContainer( + name=self.name, + handler=target, + filters=self.filters, + after=self.after, + ) + ) + + def _wrap_action(self, target: CallbackType) -> None: + assert self.action is not None, "Scene action is not specified" + + action = getattr(target, "__aiogram_action__", None) + if action is None: + action = defaultdict(dict) + setattr(target, "__aiogram_action__", action) + action[self.action][self.name] = CallableObject(target) + + def __call__(self, target: CallbackType) -> CallbackType: + if inspect.isfunction(target): + if self.action is None: + self._wrap_filter(target) + else: + self._wrap_action(target) + else: + raise TypeError("Only function or method is allowed") + return target + + def leave(self) -> ActionContainer: + return ActionContainer(self.name, self.filters, SceneAction.leave) + + def enter(self, target: Type[Scene]) -> ActionContainer: + return ActionContainer(self.name, self.filters, SceneAction.enter, target) + + def exit(self) -> ActionContainer: + return ActionContainer(self.name, self.filters, SceneAction.exit) + + def back(self) -> ActionContainer: + return ActionContainer(self.name, self.filters, SceneAction.back) + + +class SceneAction(Enum): + enter = auto() + leave = auto() + exit = auto() + back = auto() + + +class ActionContainer: + def __init__( + self, + name: str, + filters: Tuple[CallbackType, ...], + action: SceneAction, + target: Optional[Union[Type[Scene], str]] = None, + ) -> None: + self.name = name + self.filters = filters + self.action = action + self.target = target + + async def execute(self, wizard: SceneWizard) -> None: + if self.action == SceneAction.enter and self.target is not None: + await wizard.goto(self.target) + elif self.action == SceneAction.leave: + await wizard.leave() + elif self.action == SceneAction.exit: + await wizard.exit() + elif self.action == SceneAction.back: + await wizard.back() + + +class HandlerContainer: + def __init__( + self, + name: str, + handler: CallbackType, + filters: Tuple[CallbackType, ...], + after: Optional[After] = None, + ) -> None: + self.name = name + self.handler = handler + self.filters = filters + self.after = after + + +@dataclass() +class SceneConfig: + state: Optional[str] + """Scene state""" + handlers: List[HandlerContainer] + """Scene handlers""" + actions: Dict[SceneAction, Dict[str, CallableObject]] + """Scene actions""" + reset_data_on_enter: Optional[bool] = None + """Reset scene data on enter""" + reset_history_on_enter: Optional[bool] = None + """Reset scene history on enter""" + callback_query_without_state: Optional[bool] = None + """Allow callback query without state""" + + +async def _empty_handler(*args: Any, **kwargs: Any) -> None: + pass + + +class SceneHandlerWrapper: + def __init__( + self, + scene: Type[Scene], + handler: CallbackType, + after: Optional[After] = None, + ) -> None: + self.scene = scene + self.handler = CallableObject(handler) + self.after = after + + async def __call__( + self, + event: TelegramObject, + **kwargs: Any, + ) -> Any: + state: FSMContext = kwargs["state"] + scenes: ScenesManager = kwargs["scenes"] + event_update: Update = kwargs["event_update"] + scene = self.scene( + wizard=SceneWizard( + scene_config=self.scene.__scene_config__, + manager=scenes, + state=state, + update_type=event_update.event_type, + event=event, + data=kwargs, + ) + ) + + result = await self.handler.call(scene, event, **kwargs) + + if self.after: + action_container = ActionContainer( + "after", + (), + self.after.action, + self.after.scene, + ) + await action_container.execute(scene.wizard) + return result + + def __await__(self) -> Self: + return self + + def __str__(self) -> str: + result = f"SceneHandlerWrapper({self.scene}, {self.handler.callback}" + if self.after: + result += f", after={self.after}" + result += ")" + return result + + +class Scene: + """ + Represents a scene in a conversation flow. + + A scene is a specific state in a conversation where certain actions can take place. + + Each scene has a set of filters that determine when it should be triggered, + and a set of handlers that define the actions to be executed when the scene is active. + + .. note:: + This class is not meant to be used directly. Instead, it should be subclassed + to define custom scenes. + """ + + __scene_config__: ClassVar[SceneConfig] + """Scene configuration.""" + + def __init__( + self, + wizard: SceneWizard, + ) -> None: + self.wizard = wizard + self.wizard.scene = self + + def __init_subclass__(cls, **kwargs: Any) -> None: + state_name = kwargs.pop("state", None) + reset_data_on_enter = kwargs.pop("reset_data_on_enter", None) + reset_history_on_enter = kwargs.pop("reset_history_on_enter", None) + callback_query_without_state = kwargs.pop("callback_query_without_state", None) + + super().__init_subclass__(**kwargs) + + handlers: list[HandlerContainer] = [] + actions: defaultdict[SceneAction, Dict[str, CallableObject]] = defaultdict(dict) + + for base in cls.__bases__: + if not issubclass(base, Scene): + continue + + parent_scene_config = getattr(base, "__scene_config__", None) + if not parent_scene_config: + continue + + handlers.extend(parent_scene_config.handlers) + for action, action_handlers in parent_scene_config.actions.items(): + actions[action].update(action_handlers) + + if reset_data_on_enter is None: + reset_data_on_enter = parent_scene_config.reset_data_on_enter + if reset_history_on_enter is None: + reset_history_on_enter = parent_scene_config.reset_history_on_enter + if callback_query_without_state is None: + callback_query_without_state = parent_scene_config.callback_query_without_state + + for name in vars(cls): + value = getattr(cls, name) + + if scene_handlers := getattr(value, "__aiogram_handler__", None): + handlers.extend(scene_handlers) + if isinstance(value, ObserverDecorator): + handlers.append( + HandlerContainer( + value.name, + _empty_handler, + value.filters, + after=value.after, + ) + ) + if hasattr(value, "__aiogram_action__"): + for action, action_handlers in value.__aiogram_action__.items(): + actions[action].update(action_handlers) + + cls.__scene_config__ = SceneConfig( + state=state_name, + handlers=handlers, + actions=dict(actions), + reset_data_on_enter=reset_data_on_enter, + reset_history_on_enter=reset_history_on_enter, + callback_query_without_state=callback_query_without_state, + ) + + @classmethod + def add_to_router(cls, router: Router) -> None: + """ + Adds the scene to the given router. + + :param router: + :return: + """ + scene_config = cls.__scene_config__ + used_observers = set() + + for handler in scene_config.handlers: + router.observers[handler.name].register( + SceneHandlerWrapper( + cls, + handler.handler, + after=handler.after, + ), + *handler.filters, + flags=extract_flags_from_object(handler.handler), + ) + used_observers.add(handler.name) + + for observer_name in used_observers: + if scene_config.callback_query_without_state and observer_name == "callback_query": + continue + router.observers[observer_name].filter(StateFilter(scene_config.state)) + + @classmethod + def as_router(cls, name: Optional[str] = None) -> Router: + """ + Returns the scene as a router. + + :return: new router + """ + if name is None: + name = ( + f"Scene '{cls.__module__}.{cls.__qualname__}' " + f"for state {cls.__scene_config__.state!r}" + ) + router = Router(name=name) + cls.add_to_router(router) + return router + + @classmethod + def as_handler(cls, **kwargs: Any) -> CallbackType: + """ + Create an entry point handler for the scene, can be used to simplify the handler + that starts the scene. + + >>> router.message.register(MyScene.as_handler(), Command("start")) + """ + + async def enter_to_scene_handler(event: TelegramObject, scenes: ScenesManager) -> None: + await scenes.enter(cls, **kwargs) + + return enter_to_scene_handler + + +class SceneWizard: + """ + A class that represents a wizard for managing scenes in a Telegram bot. + + Instance of this class is passed to each scene as a parameter. + So, you can use it to transition between scenes, get and set data, etc. + + .. note:: + + This class is not meant to be used directly. Instead, it should be used + as a parameter in the scene constructor. + + """ + + def __init__( + self, + scene_config: SceneConfig, + manager: ScenesManager, + state: FSMContext, + update_type: str, + event: TelegramObject, + data: Dict[str, Any], + ): + """ + A class that represents a wizard for managing scenes in a Telegram bot. + + :param scene_config: The configuration of the scene. + :param manager: The scene manager. + :param state: The FSMContext object for storing the state of the scene. + :param update_type: The type of the update event. + :param event: The TelegramObject represents the event. + :param data: Additional data for the scene. + """ + self.scene_config = scene_config + self.manager = manager + self.state = state + self.update_type = update_type + self.event = event + self.data = data + + self.scene: Optional[Scene] = None + + async def enter(self, **kwargs: Any) -> None: + """ + Enter method is used to transition into a scene in the SceneWizard class. + It sets the state, clears data and history if specified, + and triggers entering event of the scene. + + :param kwargs: Additional keyword arguments. + :return: None + """ + loggers.scene.debug("Entering scene %r", self.scene_config.state) + if self.scene_config.reset_data_on_enter: + await self.state.set_data({}) + if self.scene_config.reset_history_on_enter: + await self.manager.history.clear() + await self.state.set_state(self.scene_config.state) + await self._on_action(SceneAction.enter, **kwargs) + + async def leave(self, _with_history: bool = True, **kwargs: Any) -> None: + """ + Leaves the current scene. + This method is used to exit a scene and transition to the next scene. + + :param _with_history: Whether to include history in the snapshot. Defaults to True. + :param kwargs: Additional keyword arguments. + :return: None + + """ + loggers.scene.debug("Leaving scene %r", self.scene_config.state) + if _with_history: + await self.manager.history.snapshot() + await self._on_action(SceneAction.leave, **kwargs) + + async def exit(self, **kwargs: Any) -> None: + """ + Exit the current scene and enter the default scene/state. + + :param kwargs: Additional keyword arguments. + :return: None + """ + loggers.scene.debug("Exiting scene %r", self.scene_config.state) + await self.manager.history.clear() + await self._on_action(SceneAction.exit, **kwargs) + await self.manager.enter(None, _check_active=False, **kwargs) + + async def back(self, **kwargs: Any) -> None: + """ + This method is used to go back to the previous scene. + + :param kwargs: Keyword arguments that can be passed to the method. + :return: None + """ + loggers.scene.debug("Back to previous scene from scene %s", self.scene_config.state) + await self.leave(_with_history=False, **kwargs) + new_scene = await self.manager.history.rollback() + await self.manager.enter(new_scene, _check_active=False, **kwargs) + + async def retake(self, **kwargs: Any) -> None: + """ + This method allows to re-enter the current scene. + + :param kwargs: Additional keyword arguments to pass to the scene. + :return: None + """ + assert self.scene_config.state is not None, "Scene state is not specified" + await self.goto(self.scene_config.state, **kwargs) + + async def goto(self, scene: Union[Type[Scene], str], **kwargs: Any) -> None: + """ + The `goto` method transitions to a new scene. + It first calls the `leave` method to perform any necessary cleanup + in the current scene, then calls the `enter` event to enter the specified scene. + + :param scene: The scene to transition to. Can be either a `Scene` instance + or a string representing the scene. + :param kwargs: Additional keyword arguments to pass to the `enter` + method of the scene manager. + :return: None + """ + await self.leave(**kwargs) + await self.manager.enter(scene, _check_active=False, **kwargs) + + async def _on_action(self, action: SceneAction, **kwargs: Any) -> bool: + if not self.scene: + raise SceneException("Scene is not initialized") + + loggers.scene.debug("Call action %r in scene %r", action.name, self.scene_config.state) + action_config = self.scene_config.actions.get(action, {}) + if not action_config: + loggers.scene.debug( + "Action %r not found in scene %r", action.name, self.scene_config.state + ) + return False + + event_type = self.update_type + if event_type not in action_config: + loggers.scene.debug( + "Action %r for event %r not found in scene %r", + action.name, + event_type, + self.scene_config.state, + ) + return False + + await action_config[event_type].call(self.scene, self.event, **{**self.data, **kwargs}) + return True + + async def set_data(self, data: Dict[str, Any]) -> None: + """ + Sets custom data in the current state. + + :param data: A dictionary containing the custom data to be set in the current state. + :return: None + """ + await self.state.set_data(data=data) + + async def get_data(self) -> Dict[str, Any]: + """ + This method returns the data stored in the current state. + + :return: A dictionary containing the data stored in the scene state. + """ + return await self.state.get_data() + + async def update_data( + self, data: Optional[Dict[str, Any]] = None, **kwargs: Any + ) -> Dict[str, Any]: + """ + This method updates the data stored in the current state + + :param data: Optional dictionary of data to update. + :param kwargs: Additional key-value pairs of data to update. + :return: Dictionary of updated data + """ + if data: + kwargs.update(data) + return await self.state.update_data(data=kwargs) + + async def clear_data(self) -> None: + """ + Clears the data. + + :return: None + """ + await self.set_data({}) + + +class ScenesManager: + """ + The ScenesManager class is responsible for managing scenes in an application. + It provides methods for entering and exiting scenes, as well as retrieving the active scene. + """ + + def __init__( + self, + registry: SceneRegistry, + update_type: str, + event: TelegramObject, + state: FSMContext, + data: Dict[str, Any], + ) -> None: + self.registry = registry + self.update_type = update_type + self.event = event + self.state = state + self.data = data + + self.history = HistoryManager(self.state) + + async def _get_scene(self, scene_type: Optional[Union[Type[Scene], str]]) -> Scene: + scene_type = self.registry.get(scene_type) + return scene_type( + wizard=SceneWizard( + scene_config=scene_type.__scene_config__, + manager=self, + state=self.state, + update_type=self.update_type, + event=self.event, + data=self.data, + ), + ) + + async def _get_active_scene(self) -> Optional[Scene]: + state = await self.state.get_state() + try: + return await self._get_scene(state) + except SceneException: + return None + + async def enter( + self, + scene_type: Optional[Union[Type[Scene], str]], + _check_active: bool = True, + **kwargs: Any, + ) -> None: + """ + Enters the specified scene. + + :param scene_type: Optional Type[Scene] or str representing the scene type to enter. + :param _check_active: Optional bool indicating whether to check if + there is an active scene to exit before entering the new scene. Defaults to True. + :param kwargs: Additional keyword arguments to pass to the scene's wizard.enter() method. + :return: None + """ + if _check_active: + active_scene = await self._get_active_scene() + if active_scene is not None: + await active_scene.wizard.exit(**kwargs) + + try: + scene = await self._get_scene(scene_type) + except SceneException: + if scene_type is not None: + raise + await self.state.set_state(None) + else: + await scene.wizard.enter(**kwargs) + + async def close(self, **kwargs: Any) -> None: + """ + Close method is used to exit the currently active scene in the ScenesManager. + + :param kwargs: Additional keyword arguments passed to the scene's exit method. + :return: None + """ + scene = await self._get_active_scene() + if not scene: + return + await scene.wizard.exit(**kwargs) + + +class SceneRegistry: + """ + A class that represents a registry for scenes in a Telegram bot. + """ + + def __init__(self, router: Router, register_on_add: bool = True) -> None: + """ + Initialize a new instance of the SceneRegistry class. + + :param router: The router instance used for scene registration. + :param register_on_add: Whether to register the scenes to the router when they are added. + """ + self.router = router + self.register_on_add = register_on_add + + self._scenes: Dict[Optional[str], Type[Scene]] = {} + self._setup_middleware(router) + + def _setup_middleware(self, router: Router) -> None: + if isinstance(router, Dispatcher): + # Small optimization for Dispatcher + # - we don't need to set up middleware for all observers + router.update.outer_middleware(self._update_middleware) + return + + for observer in router.observers.values(): + if observer.event_name in {"update", "error"}: + continue + observer.outer_middleware(self._middleware) + + async def _update_middleware( + self, + handler: NextMiddlewareType[TelegramObject], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + assert isinstance(event, Update), "Event must be an Update instance" + + data["scenes"] = ScenesManager( + registry=self, + update_type=event.event_type, + event=event.event, + state=data["state"], + data=data, + ) + return await handler(event, data) + + async def _middleware( + self, + handler: NextMiddlewareType[TelegramObject], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + update: Update = data["event_update"] + data["scenes"] = ScenesManager( + registry=self, + update_type=update.event_type, + event=event, + state=data["state"], + data=data, + ) + return await handler(event, data) + + def add(self, *scenes: Type[Scene], router: Optional[Router] = None) -> None: + """ + This method adds the specified scenes to the registry + and optionally registers it to the router. + + If a scene with the same state already exists in the registry, a SceneException is raised. + + .. warning:: + + If the router is not specified, the scenes will not be registered to the router. + You will need to include the scenes manually to the router or use the register method. + + :param scenes: A variable length parameter that accepts one or more types of scenes. + These scenes are instances of the Scene class. + :param router: An optional parameter that specifies the router + to which the scenes should be added. + :return: None + """ + if not scenes: + raise ValueError("At least one scene must be specified") + + for scene in scenes: + if scene.__scene_config__.state in self._scenes: + raise SceneException( + f"Scene with state {scene.__scene_config__.state!r} already exists" + ) + + self._scenes[scene.__scene_config__.state] = scene + + if router: + router.include_router(scene.as_router()) + elif self.register_on_add: + self.router.include_router(scene.as_router()) + + def register(self, *scenes: Type[Scene]) -> None: + """ + Registers one or more scenes to the SceneRegistry. + + :param scenes: One or more scene classes to register. + :return: None + """ + self.add(*scenes, router=self.router) + + def get(self, scene: Optional[Union[Type[Scene], str]]) -> Type[Scene]: + """ + This method returns the registered Scene object for the specified scene. + The scene parameter can be either a Scene object or a string representing + the name of the scene. If a Scene object is provided, the state attribute + of the SceneConfig object associated with the Scene object will be used as the scene name. + If None or an invalid type is provided, a SceneException will be raised. + + If the specified scene is not registered in the SceneRegistry object, + a SceneException will be raised. + + :param scene: A Scene object or a string representing the name of the scene. + :return: The registered Scene object corresponding to the given scene parameter. + + """ + if inspect.isclass(scene) and issubclass(scene, Scene): + scene = scene.__scene_config__.state + if isinstance(scene, State): + scene = scene.state + if scene is not None and not isinstance(scene, str): + raise SceneException("Scene must be a subclass of Scene or a string") + + try: + return self._scenes[scene] + except KeyError: + raise SceneException(f"Scene {scene!r} is not registered") + + +@dataclass +class After: + action: SceneAction + scene: Optional[Union[Type[Scene], str]] = None + + @classmethod + def exit(cls) -> After: + return cls(action=SceneAction.exit) + + @classmethod + def back(cls) -> After: + return cls(action=SceneAction.back) + + @classmethod + def goto(cls, scene: Optional[Union[Type[Scene], str]]) -> After: + return cls(action=SceneAction.enter, scene=scene) + + +class ObserverMarker: + def __init__(self, name: str) -> None: + self.name = name + + def __call__( + self, + *filters: CallbackType, + after: Optional[After] = None, + ) -> ObserverDecorator: + return ObserverDecorator( + self.name, + filters, + after=after, + ) + + def enter(self, *filters: CallbackType) -> ObserverDecorator: + return ObserverDecorator(self.name, filters, action=SceneAction.enter) + + def leave(self) -> ObserverDecorator: + return ObserverDecorator(self.name, (), action=SceneAction.leave) + + def exit(self) -> ObserverDecorator: + return ObserverDecorator(self.name, (), action=SceneAction.exit) + + def back(self) -> ObserverDecorator: + return ObserverDecorator(self.name, (), action=SceneAction.back) + + +class OnMarker: + """ + The `OnMarker` class is used as a marker class to define different + types of events in the Scenes. + + Attributes: + + - :code:`message`: Event marker for handling `Message` events. + - :code:`edited_message`: Event marker for handling edited `Message` events. + - :code:`channel_post`: Event marker for handling channel `Post` events. + - :code:`edited_channel_post`: Event marker for handling edited channel `Post` events. + - :code:`inline_query`: Event marker for handling `InlineQuery` events. + - :code:`chosen_inline_result`: Event marker for handling chosen `InlineResult` events. + - :code:`callback_query`: Event marker for handling `CallbackQuery` events. + - :code:`shipping_query`: Event marker for handling `ShippingQuery` events. + - :code:`pre_checkout_query`: Event marker for handling `PreCheckoutQuery` events. + - :code:`poll`: Event marker for handling `Poll` events. + - :code:`poll_answer`: Event marker for handling `PollAnswer` events. + - :code:`my_chat_member`: Event marker for handling my chat `Member` events. + - :code:`chat_member`: Event marker for handling chat `Member` events. + - :code:`chat_join_request`: Event marker for handling chat `JoinRequest` events. + - :code:`error`: Event marker for handling `Error` events. + + .. note:: + + This is a marker class and does not contain any methods or implementation logic. + """ + + message = ObserverMarker("message") + edited_message = ObserverMarker("edited_message") + channel_post = ObserverMarker("channel_post") + edited_channel_post = ObserverMarker("edited_channel_post") + inline_query = ObserverMarker("inline_query") + chosen_inline_result = ObserverMarker("chosen_inline_result") + callback_query = ObserverMarker("callback_query") + shipping_query = ObserverMarker("shipping_query") + pre_checkout_query = ObserverMarker("pre_checkout_query") + poll = ObserverMarker("poll") + poll_answer = ObserverMarker("poll_answer") + my_chat_member = ObserverMarker("my_chat_member") + chat_member = ObserverMarker("chat_member") + chat_join_request = ObserverMarker("chat_join_request") + + +on = OnMarker() diff --git a/env/Lib/site-packages/aiogram/fsm/state.py b/env/Lib/site-packages/aiogram/fsm/state.py new file mode 100644 index 0000000..6b8c737 --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/state.py @@ -0,0 +1,172 @@ +import inspect +from typing import Any, Iterator, Optional, Tuple, Type, no_type_check + +from aiogram.types import TelegramObject + + +class State: + """ + State object + """ + + def __init__(self, state: Optional[str] = None, group_name: Optional[str] = None) -> None: + self._state = state + self._group_name = group_name + self._group: Optional[Type[StatesGroup]] = None + + @property + def group(self) -> "Type[StatesGroup]": + if not self._group: + raise RuntimeError("This state is not in any group.") + return self._group + + @property + def state(self) -> Optional[str]: + if self._state is None or self._state == "*": + return self._state + + if self._group_name is None and self._group: + group = self._group.__full_group_name__ + elif self._group_name: + group = self._group_name + else: + group = "@" + + return f"{group}:{self._state}" + + def set_parent(self, group: "Type[StatesGroup]") -> None: + if not issubclass(group, StatesGroup): + raise ValueError("Group must be subclass of StatesGroup") + self._group = group + + def __set_name__(self, owner: "Type[StatesGroup]", name: str) -> None: + if self._state is None: + self._state = name + self.set_parent(owner) + + def __str__(self) -> str: + return f"" + + __repr__ = __str__ + + def __call__(self, event: TelegramObject, raw_state: Optional[str] = None) -> bool: + if self.state == "*": + return True + return raw_state == self.state + + def __eq__(self, other: Any) -> bool: + if isinstance(other, self.__class__): + return self.state == other.state + if isinstance(other, str): + return self.state == other + return NotImplemented + + def __hash__(self) -> int: + return hash(self.state) + + +class StatesGroupMeta(type): + __parent__: "Optional[Type[StatesGroup]]" + __childs__: "Tuple[Type[StatesGroup], ...]" + __states__: Tuple[State, ...] + __state_names__: Tuple[str, ...] + __all_childs__: Tuple[Type["StatesGroup"], ...] + __all_states__: Tuple[State, ...] + __all_states_names__: Tuple[str, ...] + + @no_type_check + def __new__(mcs, name, bases, namespace, **kwargs): + cls = super().__new__(mcs, name, bases, namespace) + + states = [] + childs = [] + + for name, arg in namespace.items(): + if isinstance(arg, State): + states.append(arg) + elif inspect.isclass(arg) and issubclass(arg, StatesGroup): + child = cls._prepare_child(arg) + childs.append(child) + + cls.__parent__ = None + cls.__childs__ = tuple(childs) + cls.__states__ = tuple(states) + cls.__state_names__ = tuple(state.state for state in states) + + cls.__all_childs__ = cls._get_all_childs() + cls.__all_states__ = cls._get_all_states() + + # In order to ensure performance, we calculate this parameter + # in advance already during the production of the class. + # Depending on the relationship, it should be recalculated + cls.__all_states_names__ = cls._get_all_states_names() + + return cls + + @property + def __full_group_name__(cls) -> str: + if cls.__parent__: + return ".".join((cls.__parent__.__full_group_name__, cls.__name__)) + return cls.__name__ + + def _prepare_child(cls, child: Type["StatesGroup"]) -> Type["StatesGroup"]: + """Prepare child. + + While adding `cls` for its children, we also need to recalculate + the parameter `__all_states_names__` for each child + `StatesGroup`. Since the child class appears before the + parent, at the time of adding the parent, the child's + `__all_states_names__` is already recorded without taking into + account the name of current parent. + """ + child.__parent__ = cls # type: ignore[assignment] + child.__all_states_names__ = child._get_all_states_names() + return child + + def _get_all_childs(cls) -> Tuple[Type["StatesGroup"], ...]: + result = cls.__childs__ + for child in cls.__childs__: + result += child.__childs__ + return result + + def _get_all_states(cls) -> Tuple[State, ...]: + result = cls.__states__ + for group in cls.__childs__: + result += group.__all_states__ + return result + + def _get_all_states_names(cls) -> Tuple[str, ...]: + return tuple(state.state for state in cls.__all_states__ if state.state) + + def __contains__(cls, item: Any) -> bool: + if isinstance(item, str): + return item in cls.__all_states_names__ + if isinstance(item, State): + return item in cls.__all_states__ + if isinstance(item, StatesGroupMeta): + return item in cls.__all_childs__ + return False + + def __str__(self) -> str: + return f"" + + def __iter__(self) -> Iterator[State]: + return iter(self.__all_states__) + + +class StatesGroup(metaclass=StatesGroupMeta): + @classmethod + def get_root(cls) -> Type["StatesGroup"]: + if cls.__parent__ is None: + return cls + return cls.__parent__.get_root() + + def __call__(self, event: TelegramObject, raw_state: Optional[str] = None) -> bool: + return raw_state in type(self).__all_states_names__ + + def __str__(self) -> str: + return f"StatesGroup {type(self).__full_group_name__}" + + +default_state = State() +any_state = State(state="*") diff --git a/env/Lib/site-packages/aiogram/fsm/storage/__init__.py b/env/Lib/site-packages/aiogram/fsm/storage/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..accd518 Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..0f9c3aa Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/memory.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/memory.cpython-311.pyc new file mode 100644 index 0000000..c23eb64 Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/memory.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/mongo.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/mongo.cpython-311.pyc new file mode 100644 index 0000000..8d41982 Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/mongo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/redis.cpython-311.pyc b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/redis.cpython-311.pyc new file mode 100644 index 0000000..0b86cfe Binary files /dev/null and b/env/Lib/site-packages/aiogram/fsm/storage/__pycache__/redis.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/fsm/storage/base.py b/env/Lib/site-packages/aiogram/fsm/storage/base.py new file mode 100644 index 0000000..8e1b206 --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/storage/base.py @@ -0,0 +1,183 @@ +from abc import ABC, abstractmethod +from contextlib import asynccontextmanager +from dataclasses import dataclass +from typing import Any, AsyncGenerator, Dict, Literal, Optional, Union + +from aiogram.fsm.state import State + +StateType = Optional[Union[str, State]] + +DEFAULT_DESTINY = "default" + + +@dataclass(frozen=True) +class StorageKey: + bot_id: int + chat_id: int + user_id: int + thread_id: Optional[int] = None + business_connection_id: Optional[str] = None + destiny: str = DEFAULT_DESTINY + + +class KeyBuilder(ABC): + """Base class for key builder.""" + + @abstractmethod + def build( + self, + key: StorageKey, + part: Optional[Literal["data", "state", "lock"]] = None, + ) -> str: + """ + Build key to be used in storage's db queries + + :param key: contextual key + :param part: part of the record + :return: key to be used in storage's db queries + """ + pass + + +class DefaultKeyBuilder(KeyBuilder): + """ + Simple key builder with default prefix. + + Generates a colon-joined string with prefix, chat_id, user_id, + optional bot_id, business_connection_id, destiny and field. + + Format: + :code:`::::::` + """ + + def __init__( + self, + *, + prefix: str = "fsm", + separator: str = ":", + with_bot_id: bool = False, + with_business_connection_id: bool = False, + with_destiny: bool = False, + ) -> None: + """ + :param prefix: prefix for all records + :param separator: separator + :param with_bot_id: include Bot id in the key + :param with_business_connection_id: include business connection id + :param with_destiny: include destiny key + """ + self.prefix = prefix + self.separator = separator + self.with_bot_id = with_bot_id + self.with_business_connection_id = with_business_connection_id + self.with_destiny = with_destiny + + def build( + self, + key: StorageKey, + part: Optional[Literal["data", "state", "lock"]] = None, + ) -> str: + parts = [self.prefix] + if self.with_bot_id: + parts.append(str(key.bot_id)) + if self.with_business_connection_id and key.business_connection_id: + parts.append(str(key.business_connection_id)) + parts.append(str(key.chat_id)) + if key.thread_id: + parts.append(str(key.thread_id)) + parts.append(str(key.user_id)) + if self.with_destiny: + parts.append(key.destiny) + elif key.destiny != DEFAULT_DESTINY: + error_message = ( + "Default key builder is not configured to use key destiny other than the default." + "\n\nProbably, you should set `with_destiny=True` in for DefaultKeyBuilder." + ) + raise ValueError(error_message) + if part: + parts.append(part) + return self.separator.join(parts) + + +class BaseStorage(ABC): + """ + Base class for all FSM storages + """ + + @abstractmethod + async def set_state(self, key: StorageKey, state: StateType = None) -> None: + """ + Set state for specified key + + :param key: storage key + :param state: new state + """ + pass + + @abstractmethod + async def get_state(self, key: StorageKey) -> Optional[str]: + """ + Get key state + + :param key: storage key + :return: current state + """ + pass + + @abstractmethod + async def set_data(self, key: StorageKey, data: Dict[str, Any]) -> None: + """ + Write data (replace) + + :param key: storage key + :param data: new data + """ + pass + + @abstractmethod + async def get_data(self, key: StorageKey) -> Dict[str, Any]: + """ + Get current data for key + + :param key: storage key + :return: current data + """ + pass + + async def update_data(self, key: StorageKey, data: Dict[str, Any]) -> Dict[str, Any]: + """ + Update date in the storage for key (like dict.update) + + :param key: storage key + :param data: partial data + :return: new data + """ + current_data = await self.get_data(key=key) + current_data.update(data) + await self.set_data(key=key, data=current_data) + return current_data.copy() + + @abstractmethod + async def close(self) -> None: # pragma: no cover + """ + Close storage (database connection, file or etc.) + """ + pass + + +class BaseEventIsolation(ABC): + @abstractmethod + @asynccontextmanager + async def lock(self, key: StorageKey) -> AsyncGenerator[None, None]: + """ + Isolate events with lock. + Will be used as context manager + + :param key: storage key + :return: An async generator + """ + yield None + + @abstractmethod + async def close(self) -> None: + pass diff --git a/env/Lib/site-packages/aiogram/fsm/storage/memory.py b/env/Lib/site-packages/aiogram/fsm/storage/memory.py new file mode 100644 index 0000000..d80a9ff --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/storage/memory.py @@ -0,0 +1,74 @@ +from asyncio import Lock +from collections import defaultdict +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from typing import Any, AsyncGenerator, DefaultDict, Dict, Hashable, Optional + +from aiogram.fsm.state import State +from aiogram.fsm.storage.base import ( + BaseEventIsolation, + BaseStorage, + StateType, + StorageKey, +) + + +@dataclass +class MemoryStorageRecord: + data: Dict[str, Any] = field(default_factory=dict) + state: Optional[str] = None + + +class MemoryStorage(BaseStorage): + """ + Default FSM storage, stores all data in :class:`dict` and loss everything on shutdown + + .. warning:: + + Is not recommended using in production in due to you will lose all data + when your bot restarts + """ + + def __init__(self) -> None: + self.storage: DefaultDict[StorageKey, MemoryStorageRecord] = defaultdict( + MemoryStorageRecord + ) + + async def close(self) -> None: + pass + + async def set_state(self, key: StorageKey, state: StateType = None) -> None: + self.storage[key].state = state.state if isinstance(state, State) else state + + async def get_state(self, key: StorageKey) -> Optional[str]: + return self.storage[key].state + + async def set_data(self, key: StorageKey, data: Dict[str, Any]) -> None: + self.storage[key].data = data.copy() + + async def get_data(self, key: StorageKey) -> Dict[str, Any]: + return self.storage[key].data.copy() + + +class DisabledEventIsolation(BaseEventIsolation): + @asynccontextmanager + async def lock(self, key: StorageKey) -> AsyncGenerator[None, None]: + yield + + async def close(self) -> None: + pass + + +class SimpleEventIsolation(BaseEventIsolation): + def __init__(self) -> None: + # TODO: Unused locks cleaner is needed + self._locks: DefaultDict[Hashable, Lock] = defaultdict(Lock) + + @asynccontextmanager + async def lock(self, key: StorageKey) -> AsyncGenerator[None, None]: + lock = self._locks[key] + async with lock: + yield + + async def close(self) -> None: + self._locks.clear() diff --git a/env/Lib/site-packages/aiogram/fsm/storage/mongo.py b/env/Lib/site-packages/aiogram/fsm/storage/mongo.py new file mode 100644 index 0000000..b4b1eea --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/storage/mongo.py @@ -0,0 +1,130 @@ +from typing import Any, Dict, Optional, cast + +from motor.motor_asyncio import AsyncIOMotorClient + +from aiogram.fsm.state import State +from aiogram.fsm.storage.base import ( + BaseStorage, + DefaultKeyBuilder, + KeyBuilder, + StateType, + StorageKey, +) + + +class MongoStorage(BaseStorage): + """ + MongoDB storage required :code:`motor` package installed (:code:`pip install motor`) + """ + + def __init__( + self, + client: AsyncIOMotorClient, + key_builder: Optional[KeyBuilder] = None, + db_name: str = "aiogram_fsm", + collection_name: str = "states_and_data", + ) -> None: + """ + :param client: Instance of AsyncIOMotorClient + :param key_builder: builder that helps to convert contextual key to string + :param db_name: name of the MongoDB database for FSM + :param collection_name: name of the collection for storing FSM states and data + """ + if key_builder is None: + key_builder = DefaultKeyBuilder() + self._client = client + self._database = self._client[db_name] + self._collection = self._database[collection_name] + self._key_builder = key_builder + + @classmethod + def from_url( + cls, url: str, connection_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any + ) -> "MongoStorage": + """ + Create an instance of :class:`MongoStorage` with specifying the connection string + + :param url: for example :code:`mongodb://user:password@host:port` + :param connection_kwargs: see :code:`motor` docs + :param kwargs: arguments to be passed to :class:`MongoStorage` + :return: an instance of :class:`MongoStorage` + """ + if connection_kwargs is None: + connection_kwargs = {} + client = AsyncIOMotorClient(url, **connection_kwargs) + return cls(client=client, **kwargs) + + async def close(self) -> None: + """Cleanup client resources and disconnect from MongoDB.""" + self._client.close() + + def resolve_state(self, value: StateType) -> Optional[str]: + if value is None: + return None + if isinstance(value, State): + return value.state + return str(value) + + async def set_state(self, key: StorageKey, state: StateType = None) -> None: + document_id = self._key_builder.build(key) + if state is None: + updated = await self._collection.find_one_and_update( + filter={"_id": document_id}, + update={"$unset": {"state": 1}}, + projection={"_id": 0}, + return_document=True, + ) + if updated == {}: + await self._collection.delete_one({"_id": document_id}) + else: + await self._collection.update_one( + filter={"_id": document_id}, + update={"$set": {"state": self.resolve_state(state)}}, + upsert=True, + ) + + async def get_state(self, key: StorageKey) -> Optional[str]: + document_id = self._key_builder.build(key) + document = await self._collection.find_one({"_id": document_id}) + if document is None: + return None + return document.get("state") + + async def set_data(self, key: StorageKey, data: Dict[str, Any]) -> None: + document_id = self._key_builder.build(key) + if not data: + updated = await self._collection.find_one_and_update( + filter={"_id": document_id}, + update={"$unset": {"data": 1}}, + projection={"_id": 0}, + return_document=True, + ) + if updated == {}: + await self._collection.delete_one({"_id": document_id}) + else: + await self._collection.update_one( + filter={"_id": document_id}, + update={"$set": {"data": data}}, + upsert=True, + ) + + async def get_data(self, key: StorageKey) -> Dict[str, Any]: + document_id = self._key_builder.build(key) + document = await self._collection.find_one({"_id": document_id}) + if document is None or not document.get("data"): + return {} + return cast(Dict[str, Any], document["data"]) + + async def update_data(self, key: StorageKey, data: Dict[str, Any]) -> Dict[str, Any]: + document_id = self._key_builder.build(key) + update_with = {f"data.{key}": value for key, value in data.items()} + update_result = await self._collection.find_one_and_update( + filter={"_id": document_id}, + update={"$set": update_with}, + upsert=True, + return_document=True, + projection={"_id": 0}, + ) + if not update_result: + await self._collection.delete_one({"_id": document_id}) + return update_result.get("data", {}) diff --git a/env/Lib/site-packages/aiogram/fsm/storage/redis.py b/env/Lib/site-packages/aiogram/fsm/storage/redis.py new file mode 100644 index 0000000..edcf9d6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/storage/redis.py @@ -0,0 +1,169 @@ +import json +from contextlib import asynccontextmanager +from typing import Any, AsyncGenerator, Callable, Dict, Optional, cast + +from redis.asyncio.client import Redis +from redis.asyncio.connection import ConnectionPool +from redis.asyncio.lock import Lock +from redis.typing import ExpiryT + +from aiogram.fsm.state import State +from aiogram.fsm.storage.base import ( + BaseEventIsolation, + BaseStorage, + DefaultKeyBuilder, + KeyBuilder, + StateType, + StorageKey, +) + +DEFAULT_REDIS_LOCK_KWARGS = {"timeout": 60} +_JsonLoads = Callable[..., Any] +_JsonDumps = Callable[..., str] + + +class RedisStorage(BaseStorage): + """ + Redis storage required :code:`redis` package installed (:code:`pip install redis`) + """ + + def __init__( + self, + redis: Redis, + key_builder: Optional[KeyBuilder] = None, + state_ttl: Optional[ExpiryT] = None, + data_ttl: Optional[ExpiryT] = None, + json_loads: _JsonLoads = json.loads, + json_dumps: _JsonDumps = json.dumps, + ) -> None: + """ + :param redis: Instance of Redis connection + :param key_builder: builder that helps to convert contextual key to string + :param state_ttl: TTL for state records + :param data_ttl: TTL for data records + """ + if key_builder is None: + key_builder = DefaultKeyBuilder() + self.redis = redis + self.key_builder = key_builder + self.state_ttl = state_ttl + self.data_ttl = data_ttl + self.json_loads = json_loads + self.json_dumps = json_dumps + + @classmethod + def from_url( + cls, url: str, connection_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any + ) -> "RedisStorage": + """ + Create an instance of :class:`RedisStorage` with specifying the connection string + + :param url: for example :code:`redis://user:password@host:port/db` + :param connection_kwargs: see :code:`redis` docs + :param kwargs: arguments to be passed to :class:`RedisStorage` + :return: an instance of :class:`RedisStorage` + """ + if connection_kwargs is None: + connection_kwargs = {} + pool = ConnectionPool.from_url(url, **connection_kwargs) + redis = Redis(connection_pool=pool) + return cls(redis=redis, **kwargs) + + def create_isolation(self, **kwargs: Any) -> "RedisEventIsolation": + return RedisEventIsolation(redis=self.redis, key_builder=self.key_builder, **kwargs) + + async def close(self) -> None: + await self.redis.aclose(close_connection_pool=True) + + async def set_state( + self, + key: StorageKey, + state: StateType = None, + ) -> None: + redis_key = self.key_builder.build(key, "state") + if state is None: + await self.redis.delete(redis_key) + else: + await self.redis.set( + redis_key, + cast(str, state.state if isinstance(state, State) else state), + ex=self.state_ttl, + ) + + async def get_state( + self, + key: StorageKey, + ) -> Optional[str]: + redis_key = self.key_builder.build(key, "state") + value = await self.redis.get(redis_key) + if isinstance(value, bytes): + return value.decode("utf-8") + return cast(Optional[str], value) + + async def set_data( + self, + key: StorageKey, + data: Dict[str, Any], + ) -> None: + redis_key = self.key_builder.build(key, "data") + if not data: + await self.redis.delete(redis_key) + return + await self.redis.set( + redis_key, + self.json_dumps(data), + ex=self.data_ttl, + ) + + async def get_data( + self, + key: StorageKey, + ) -> Dict[str, Any]: + redis_key = self.key_builder.build(key, "data") + value = await self.redis.get(redis_key) + if value is None: + return {} + if isinstance(value, bytes): + value = value.decode("utf-8") + return cast(Dict[str, Any], self.json_loads(value)) + + +class RedisEventIsolation(BaseEventIsolation): + def __init__( + self, + redis: Redis, + key_builder: Optional[KeyBuilder] = None, + lock_kwargs: Optional[Dict[str, Any]] = None, + ) -> None: + if key_builder is None: + key_builder = DefaultKeyBuilder() + if lock_kwargs is None: + lock_kwargs = DEFAULT_REDIS_LOCK_KWARGS + self.redis = redis + self.key_builder = key_builder + self.lock_kwargs = lock_kwargs + + @classmethod + def from_url( + cls, + url: str, + connection_kwargs: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> "RedisEventIsolation": + if connection_kwargs is None: + connection_kwargs = {} + pool = ConnectionPool.from_url(url, **connection_kwargs) + redis = Redis(connection_pool=pool) + return cls(redis=redis, **kwargs) + + @asynccontextmanager + async def lock( + self, + key: StorageKey, + ) -> AsyncGenerator[None, None]: + redis_key = self.key_builder.build(key, "lock") + async with self.redis.lock(name=redis_key, **self.lock_kwargs, lock_class=Lock): + yield None + + async def close(self) -> None: + pass diff --git a/env/Lib/site-packages/aiogram/fsm/strategy.py b/env/Lib/site-packages/aiogram/fsm/strategy.py new file mode 100644 index 0000000..da2d94e --- /dev/null +++ b/env/Lib/site-packages/aiogram/fsm/strategy.py @@ -0,0 +1,37 @@ +from enum import Enum, auto +from typing import Optional, Tuple + + +class FSMStrategy(Enum): + """ + FSM strategy for storage key generation. + """ + + USER_IN_CHAT = auto() + """State will be stored for each user in chat.""" + CHAT = auto() + """State will be stored for each chat globally without separating by users.""" + GLOBAL_USER = auto() + """State will be stored globally for each user globally.""" + USER_IN_TOPIC = auto() + """State will be stored for each user in chat and topic.""" + CHAT_TOPIC = auto() + """State will be stored for each chat and topic, but not separated by users.""" + + +def apply_strategy( + strategy: FSMStrategy, + chat_id: int, + user_id: int, + thread_id: Optional[int] = None, +) -> Tuple[int, int, Optional[int]]: + if strategy == FSMStrategy.CHAT: + return chat_id, chat_id, None + if strategy == FSMStrategy.GLOBAL_USER: + return user_id, user_id, None + if strategy == FSMStrategy.USER_IN_TOPIC: + return chat_id, user_id, thread_id + if strategy == FSMStrategy.CHAT_TOPIC: + return chat_id, chat_id, thread_id + + return chat_id, user_id, None diff --git a/env/Lib/site-packages/aiogram/handlers/__init__.py b/env/Lib/site-packages/aiogram/handlers/__init__.py new file mode 100644 index 0000000..5483788 --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/__init__.py @@ -0,0 +1,25 @@ +from .base import BaseHandler, BaseHandlerMixin +from .callback_query import CallbackQueryHandler +from .chat_member import ChatMemberHandler +from .chosen_inline_result import ChosenInlineResultHandler +from .error import ErrorHandler +from .inline_query import InlineQueryHandler +from .message import MessageHandler, MessageHandlerCommandMixin +from .poll import PollHandler +from .pre_checkout_query import PreCheckoutQueryHandler +from .shipping_query import ShippingQueryHandler + +__all__ = ( + "BaseHandler", + "BaseHandlerMixin", + "CallbackQueryHandler", + "ChatMemberHandler", + "ChosenInlineResultHandler", + "ErrorHandler", + "InlineQueryHandler", + "MessageHandler", + "MessageHandlerCommandMixin", + "PollHandler", + "PreCheckoutQueryHandler", + "ShippingQueryHandler", +) diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..829da16 Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..f4e3835 Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/callback_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/callback_query.cpython-311.pyc new file mode 100644 index 0000000..e737c9c Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/callback_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/chat_member.cpython-311.pyc new file mode 100644 index 0000000..809e513 Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/chosen_inline_result.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/chosen_inline_result.cpython-311.pyc new file mode 100644 index 0000000..dc6b51b Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/chosen_inline_result.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/error.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/error.cpython-311.pyc new file mode 100644 index 0000000..6cd5dbc Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/error.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/inline_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/inline_query.cpython-311.pyc new file mode 100644 index 0000000..eb7fb19 Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/inline_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/message.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/message.cpython-311.pyc new file mode 100644 index 0000000..cea5141 Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/poll.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/poll.cpython-311.pyc new file mode 100644 index 0000000..dc98312 Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/poll.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/pre_checkout_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/pre_checkout_query.cpython-311.pyc new file mode 100644 index 0000000..8a913f4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/pre_checkout_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/__pycache__/shipping_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/handlers/__pycache__/shipping_query.cpython-311.pyc new file mode 100644 index 0000000..3e03ae1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/handlers/__pycache__/shipping_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/handlers/base.py b/env/Lib/site-packages/aiogram/handlers/base.py new file mode 100644 index 0000000..0eb1b42 --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/base.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, Dict, Generic, TypeVar, cast + +from aiogram.types import Update + +if TYPE_CHECKING: + from aiogram import Bot + +T = TypeVar("T") + + +class BaseHandlerMixin(Generic[T]): + if TYPE_CHECKING: + event: T + data: Dict[str, Any] + + +class BaseHandler(BaseHandlerMixin[T], ABC): + """ + Base class for all class-based handlers + """ + + def __init__(self, event: T, **kwargs: Any) -> None: + self.event: T = event + self.data: Dict[str, Any] = kwargs + + @property + def bot(self) -> Bot: + from aiogram import Bot + + if "bot" in self.data: + return cast(Bot, self.data["bot"]) + raise RuntimeError("Bot instance not found in the context") + + @property + def update(self) -> Update: + return cast(Update, self.data.get("update", self.data.get("event_update"))) + + @abstractmethod + async def handle(self) -> Any: # pragma: no cover + pass + + def __await__(self) -> Any: + return self.handle().__await__() diff --git a/env/Lib/site-packages/aiogram/handlers/callback_query.py b/env/Lib/site-packages/aiogram/handlers/callback_query.py new file mode 100644 index 0000000..342b11b --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/callback_query.py @@ -0,0 +1,43 @@ +from abc import ABC +from typing import Optional + +from aiogram.handlers import BaseHandler +from aiogram.types import CallbackQuery, MaybeInaccessibleMessage, Message, User + + +class CallbackQueryHandler(BaseHandler[CallbackQuery], ABC): + """ + There is base class for callback query handlers. + + Example: + .. code-block:: python + + from aiogram.handlers import CallbackQueryHandler + + ... + + @router.callback_query() + class MyHandler(CallbackQueryHandler): + async def handle(self) -> Any: ... + """ + + @property + def from_user(self) -> User: + """ + Is alias for `event.from_user` + """ + return self.event.from_user + + @property + def message(self) -> Optional[MaybeInaccessibleMessage]: + """ + Is alias for `event.message` + """ + return self.event.message + + @property + def callback_data(self) -> Optional[str]: + """ + Is alias for `event.data` + """ + return self.event.data diff --git a/env/Lib/site-packages/aiogram/handlers/chat_member.py b/env/Lib/site-packages/aiogram/handlers/chat_member.py new file mode 100644 index 0000000..bf668ac --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/chat_member.py @@ -0,0 +1,14 @@ +from abc import ABC + +from aiogram.handlers import BaseHandler +from aiogram.types import ChatMemberUpdated, User + + +class ChatMemberHandler(BaseHandler[ChatMemberUpdated], ABC): + """ + Base class for chat member updated events + """ + + @property + def from_user(self) -> User: + return self.event.from_user diff --git a/env/Lib/site-packages/aiogram/handlers/chosen_inline_result.py b/env/Lib/site-packages/aiogram/handlers/chosen_inline_result.py new file mode 100644 index 0000000..d6b66c5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/chosen_inline_result.py @@ -0,0 +1,18 @@ +from abc import ABC + +from aiogram.handlers import BaseHandler +from aiogram.types import ChosenInlineResult, User + + +class ChosenInlineResultHandler(BaseHandler[ChosenInlineResult], ABC): + """ + Base class for chosen inline result handlers + """ + + @property + def from_user(self) -> User: + return self.event.from_user + + @property + def query(self) -> str: + return self.event.query diff --git a/env/Lib/site-packages/aiogram/handlers/error.py b/env/Lib/site-packages/aiogram/handlers/error.py new file mode 100644 index 0000000..51ccf07 --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/error.py @@ -0,0 +1,17 @@ +from abc import ABC + +from aiogram.handlers.base import BaseHandler + + +class ErrorHandler(BaseHandler[Exception], ABC): + """ + Base class for errors handlers + """ + + @property + def exception_name(self) -> str: + return self.event.__class__.__name__ + + @property + def exception_message(self) -> str: + return str(self.event) diff --git a/env/Lib/site-packages/aiogram/handlers/inline_query.py b/env/Lib/site-packages/aiogram/handlers/inline_query.py new file mode 100644 index 0000000..022d8f2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/inline_query.py @@ -0,0 +1,18 @@ +from abc import ABC + +from aiogram.handlers import BaseHandler +from aiogram.types import InlineQuery, User + + +class InlineQueryHandler(BaseHandler[InlineQuery], ABC): + """ + Base class for inline query handlers + """ + + @property + def from_user(self) -> User: + return self.event.from_user + + @property + def query(self) -> str: + return self.event.query diff --git a/env/Lib/site-packages/aiogram/handlers/message.py b/env/Lib/site-packages/aiogram/handlers/message.py new file mode 100644 index 0000000..4fbecec --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/message.py @@ -0,0 +1,28 @@ +from abc import ABC +from typing import Optional, cast + +from aiogram.filters import CommandObject +from aiogram.handlers.base import BaseHandler, BaseHandlerMixin +from aiogram.types import Chat, Message, User + + +class MessageHandler(BaseHandler[Message], ABC): + """ + Base class for message handlers + """ + + @property + def from_user(self) -> Optional[User]: + return self.event.from_user + + @property + def chat(self) -> Chat: + return self.event.chat + + +class MessageHandlerCommandMixin(BaseHandlerMixin[Message]): + @property + def command(self) -> Optional[CommandObject]: + if "command" in self.data: + return cast(CommandObject, self.data["command"]) + return None diff --git a/env/Lib/site-packages/aiogram/handlers/poll.py b/env/Lib/site-packages/aiogram/handlers/poll.py new file mode 100644 index 0000000..2183d84 --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/poll.py @@ -0,0 +1,19 @@ +from abc import ABC +from typing import List + +from aiogram.handlers import BaseHandler +from aiogram.types import Poll, PollOption + + +class PollHandler(BaseHandler[Poll], ABC): + """ + Base class for poll handlers + """ + + @property + def question(self) -> str: + return self.event.question + + @property + def options(self) -> List[PollOption]: + return self.event.options diff --git a/env/Lib/site-packages/aiogram/handlers/pre_checkout_query.py b/env/Lib/site-packages/aiogram/handlers/pre_checkout_query.py new file mode 100644 index 0000000..34290f2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/pre_checkout_query.py @@ -0,0 +1,14 @@ +from abc import ABC + +from aiogram.handlers import BaseHandler +from aiogram.types import PreCheckoutQuery, User + + +class PreCheckoutQueryHandler(BaseHandler[PreCheckoutQuery], ABC): + """ + Base class for pre-checkout handlers + """ + + @property + def from_user(self) -> User: + return self.event.from_user diff --git a/env/Lib/site-packages/aiogram/handlers/shipping_query.py b/env/Lib/site-packages/aiogram/handlers/shipping_query.py new file mode 100644 index 0000000..64a5645 --- /dev/null +++ b/env/Lib/site-packages/aiogram/handlers/shipping_query.py @@ -0,0 +1,14 @@ +from abc import ABC + +from aiogram.handlers import BaseHandler +from aiogram.types import ShippingQuery, User + + +class ShippingQueryHandler(BaseHandler[ShippingQuery], ABC): + """ + Base class for shipping query handlers + """ + + @property + def from_user(self) -> User: + return self.event.from_user diff --git a/env/Lib/site-packages/aiogram/loggers.py b/env/Lib/site-packages/aiogram/loggers.py new file mode 100644 index 0000000..942c124 --- /dev/null +++ b/env/Lib/site-packages/aiogram/loggers.py @@ -0,0 +1,7 @@ +import logging + +dispatcher = logging.getLogger("aiogram.dispatcher") +event = logging.getLogger("aiogram.event") +middlewares = logging.getLogger("aiogram.middlewares") +webhook = logging.getLogger("aiogram.webhook") +scene = logging.getLogger("aiogram.scene") diff --git a/env/Lib/site-packages/aiogram/methods/__init__.py b/env/Lib/site-packages/aiogram/methods/__init__.py new file mode 100644 index 0000000..66214ac --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/__init__.py @@ -0,0 +1,259 @@ +from .add_sticker_to_set import AddStickerToSet +from .answer_callback_query import AnswerCallbackQuery +from .answer_inline_query import AnswerInlineQuery +from .answer_pre_checkout_query import AnswerPreCheckoutQuery +from .answer_shipping_query import AnswerShippingQuery +from .answer_web_app_query import AnswerWebAppQuery +from .approve_chat_join_request import ApproveChatJoinRequest +from .ban_chat_member import BanChatMember +from .ban_chat_sender_chat import BanChatSenderChat +from .base import Request, Response, TelegramMethod +from .close import Close +from .close_forum_topic import CloseForumTopic +from .close_general_forum_topic import CloseGeneralForumTopic +from .copy_message import CopyMessage +from .copy_messages import CopyMessages +from .create_chat_invite_link import CreateChatInviteLink +from .create_chat_subscription_invite_link import CreateChatSubscriptionInviteLink +from .create_forum_topic import CreateForumTopic +from .create_invoice_link import CreateInvoiceLink +from .create_new_sticker_set import CreateNewStickerSet +from .decline_chat_join_request import DeclineChatJoinRequest +from .delete_chat_photo import DeleteChatPhoto +from .delete_chat_sticker_set import DeleteChatStickerSet +from .delete_forum_topic import DeleteForumTopic +from .delete_message import DeleteMessage +from .delete_messages import DeleteMessages +from .delete_my_commands import DeleteMyCommands +from .delete_sticker_from_set import DeleteStickerFromSet +from .delete_sticker_set import DeleteStickerSet +from .delete_webhook import DeleteWebhook +from .edit_chat_invite_link import EditChatInviteLink +from .edit_chat_subscription_invite_link import EditChatSubscriptionInviteLink +from .edit_forum_topic import EditForumTopic +from .edit_general_forum_topic import EditGeneralForumTopic +from .edit_message_caption import EditMessageCaption +from .edit_message_live_location import EditMessageLiveLocation +from .edit_message_media import EditMessageMedia +from .edit_message_reply_markup import EditMessageReplyMarkup +from .edit_message_text import EditMessageText +from .export_chat_invite_link import ExportChatInviteLink +from .forward_message import ForwardMessage +from .forward_messages import ForwardMessages +from .get_business_connection import GetBusinessConnection +from .get_chat import GetChat +from .get_chat_administrators import GetChatAdministrators +from .get_chat_member import GetChatMember +from .get_chat_member_count import GetChatMemberCount +from .get_chat_menu_button import GetChatMenuButton +from .get_custom_emoji_stickers import GetCustomEmojiStickers +from .get_file import GetFile +from .get_forum_topic_icon_stickers import GetForumTopicIconStickers +from .get_game_high_scores import GetGameHighScores +from .get_me import GetMe +from .get_my_commands import GetMyCommands +from .get_my_default_administrator_rights import GetMyDefaultAdministratorRights +from .get_my_description import GetMyDescription +from .get_my_name import GetMyName +from .get_my_short_description import GetMyShortDescription +from .get_star_transactions import GetStarTransactions +from .get_sticker_set import GetStickerSet +from .get_updates import GetUpdates +from .get_user_chat_boosts import GetUserChatBoosts +from .get_user_profile_photos import GetUserProfilePhotos +from .get_webhook_info import GetWebhookInfo +from .hide_general_forum_topic import HideGeneralForumTopic +from .leave_chat import LeaveChat +from .log_out import LogOut +from .pin_chat_message import PinChatMessage +from .promote_chat_member import PromoteChatMember +from .refund_star_payment import RefundStarPayment +from .reopen_forum_topic import ReopenForumTopic +from .reopen_general_forum_topic import ReopenGeneralForumTopic +from .replace_sticker_in_set import ReplaceStickerInSet +from .restrict_chat_member import RestrictChatMember +from .revoke_chat_invite_link import RevokeChatInviteLink +from .send_animation import SendAnimation +from .send_audio import SendAudio +from .send_chat_action import SendChatAction +from .send_contact import SendContact +from .send_dice import SendDice +from .send_document import SendDocument +from .send_game import SendGame +from .send_invoice import SendInvoice +from .send_location import SendLocation +from .send_media_group import SendMediaGroup +from .send_message import SendMessage +from .send_paid_media import SendPaidMedia +from .send_photo import SendPhoto +from .send_poll import SendPoll +from .send_sticker import SendSticker +from .send_venue import SendVenue +from .send_video import SendVideo +from .send_video_note import SendVideoNote +from .send_voice import SendVoice +from .set_chat_administrator_custom_title import SetChatAdministratorCustomTitle +from .set_chat_description import SetChatDescription +from .set_chat_menu_button import SetChatMenuButton +from .set_chat_permissions import SetChatPermissions +from .set_chat_photo import SetChatPhoto +from .set_chat_sticker_set import SetChatStickerSet +from .set_chat_title import SetChatTitle +from .set_custom_emoji_sticker_set_thumbnail import SetCustomEmojiStickerSetThumbnail +from .set_game_score import SetGameScore +from .set_message_reaction import SetMessageReaction +from .set_my_commands import SetMyCommands +from .set_my_default_administrator_rights import SetMyDefaultAdministratorRights +from .set_my_description import SetMyDescription +from .set_my_name import SetMyName +from .set_my_short_description import SetMyShortDescription +from .set_passport_data_errors import SetPassportDataErrors +from .set_sticker_emoji_list import SetStickerEmojiList +from .set_sticker_keywords import SetStickerKeywords +from .set_sticker_mask_position import SetStickerMaskPosition +from .set_sticker_position_in_set import SetStickerPositionInSet +from .set_sticker_set_thumbnail import SetStickerSetThumbnail +from .set_sticker_set_title import SetStickerSetTitle +from .set_webhook import SetWebhook +from .stop_message_live_location import StopMessageLiveLocation +from .stop_poll import StopPoll +from .unban_chat_member import UnbanChatMember +from .unban_chat_sender_chat import UnbanChatSenderChat +from .unhide_general_forum_topic import UnhideGeneralForumTopic +from .unpin_all_chat_messages import UnpinAllChatMessages +from .unpin_all_forum_topic_messages import UnpinAllForumTopicMessages +from .unpin_all_general_forum_topic_messages import UnpinAllGeneralForumTopicMessages +from .unpin_chat_message import UnpinChatMessage +from .upload_sticker_file import UploadStickerFile + +__all__ = ( + "AddStickerToSet", + "AnswerCallbackQuery", + "AnswerInlineQuery", + "AnswerPreCheckoutQuery", + "AnswerShippingQuery", + "AnswerWebAppQuery", + "ApproveChatJoinRequest", + "BanChatMember", + "BanChatSenderChat", + "Close", + "CloseForumTopic", + "CloseGeneralForumTopic", + "CopyMessage", + "CopyMessages", + "CreateChatInviteLink", + "CreateChatSubscriptionInviteLink", + "CreateForumTopic", + "CreateInvoiceLink", + "CreateNewStickerSet", + "DeclineChatJoinRequest", + "DeleteChatPhoto", + "DeleteChatStickerSet", + "DeleteForumTopic", + "DeleteMessage", + "DeleteMessages", + "DeleteMyCommands", + "DeleteStickerFromSet", + "DeleteStickerSet", + "DeleteWebhook", + "EditChatInviteLink", + "EditChatSubscriptionInviteLink", + "EditForumTopic", + "EditGeneralForumTopic", + "EditMessageCaption", + "EditMessageLiveLocation", + "EditMessageMedia", + "EditMessageReplyMarkup", + "EditMessageText", + "ExportChatInviteLink", + "ForwardMessage", + "ForwardMessages", + "GetBusinessConnection", + "GetChat", + "GetChatAdministrators", + "GetChatMember", + "GetChatMemberCount", + "GetChatMenuButton", + "GetCustomEmojiStickers", + "GetFile", + "GetForumTopicIconStickers", + "GetGameHighScores", + "GetMe", + "GetMyCommands", + "GetMyDefaultAdministratorRights", + "GetMyDescription", + "GetMyName", + "GetMyShortDescription", + "GetStarTransactions", + "GetStickerSet", + "GetUpdates", + "GetUserChatBoosts", + "GetUserProfilePhotos", + "GetWebhookInfo", + "HideGeneralForumTopic", + "LeaveChat", + "LogOut", + "PinChatMessage", + "PromoteChatMember", + "RefundStarPayment", + "ReopenForumTopic", + "ReopenGeneralForumTopic", + "ReplaceStickerInSet", + "Request", + "Response", + "RestrictChatMember", + "RevokeChatInviteLink", + "SendAnimation", + "SendAudio", + "SendChatAction", + "SendContact", + "SendDice", + "SendDocument", + "SendGame", + "SendInvoice", + "SendLocation", + "SendMediaGroup", + "SendMessage", + "SendPaidMedia", + "SendPhoto", + "SendPoll", + "SendSticker", + "SendVenue", + "SendVideo", + "SendVideoNote", + "SendVoice", + "SetChatAdministratorCustomTitle", + "SetChatDescription", + "SetChatMenuButton", + "SetChatPermissions", + "SetChatPhoto", + "SetChatStickerSet", + "SetChatTitle", + "SetCustomEmojiStickerSetThumbnail", + "SetGameScore", + "SetMessageReaction", + "SetMyCommands", + "SetMyDefaultAdministratorRights", + "SetMyDescription", + "SetMyName", + "SetMyShortDescription", + "SetPassportDataErrors", + "SetStickerEmojiList", + "SetStickerKeywords", + "SetStickerMaskPosition", + "SetStickerPositionInSet", + "SetStickerSetThumbnail", + "SetStickerSetTitle", + "SetWebhook", + "StopMessageLiveLocation", + "StopPoll", + "TelegramMethod", + "UnbanChatMember", + "UnbanChatSenderChat", + "UnhideGeneralForumTopic", + "UnpinAllChatMessages", + "UnpinAllForumTopicMessages", + "UnpinAllGeneralForumTopicMessages", + "UnpinChatMessage", + "UploadStickerFile", +) diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..82ae6e7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/add_sticker_to_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/add_sticker_to_set.cpython-311.pyc new file mode 100644 index 0000000..b8758a7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/add_sticker_to_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/answer_callback_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_callback_query.cpython-311.pyc new file mode 100644 index 0000000..45e044c Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_callback_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/answer_inline_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_inline_query.cpython-311.pyc new file mode 100644 index 0000000..f1152a3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_inline_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/answer_pre_checkout_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_pre_checkout_query.cpython-311.pyc new file mode 100644 index 0000000..c6280d4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_pre_checkout_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/answer_shipping_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_shipping_query.cpython-311.pyc new file mode 100644 index 0000000..517a91b Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_shipping_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/answer_web_app_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_web_app_query.cpython-311.pyc new file mode 100644 index 0000000..9cc458d Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/answer_web_app_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/approve_chat_join_request.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/approve_chat_join_request.cpython-311.pyc new file mode 100644 index 0000000..392a3cb Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/approve_chat_join_request.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/ban_chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/ban_chat_member.cpython-311.pyc new file mode 100644 index 0000000..00fb582 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/ban_chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/ban_chat_sender_chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/ban_chat_sender_chat.cpython-311.pyc new file mode 100644 index 0000000..63700c6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/ban_chat_sender_chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..8496a2d Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/close.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/close.cpython-311.pyc new file mode 100644 index 0000000..c15575a Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/close.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/close_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/close_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..23b904b Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/close_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/close_general_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/close_general_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..1361dcf Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/close_general_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/copy_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/copy_message.cpython-311.pyc new file mode 100644 index 0000000..add1a79 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/copy_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/copy_messages.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/copy_messages.cpython-311.pyc new file mode 100644 index 0000000..bd95073 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/copy_messages.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/create_chat_invite_link.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/create_chat_invite_link.cpython-311.pyc new file mode 100644 index 0000000..ca8a069 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/create_chat_invite_link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/create_chat_subscription_invite_link.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/create_chat_subscription_invite_link.cpython-311.pyc new file mode 100644 index 0000000..5424dac Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/create_chat_subscription_invite_link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/create_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/create_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..58e8227 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/create_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/create_invoice_link.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/create_invoice_link.cpython-311.pyc new file mode 100644 index 0000000..c8e06b4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/create_invoice_link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/create_new_sticker_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/create_new_sticker_set.cpython-311.pyc new file mode 100644 index 0000000..d13b111 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/create_new_sticker_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/decline_chat_join_request.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/decline_chat_join_request.cpython-311.pyc new file mode 100644 index 0000000..e113237 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/decline_chat_join_request.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_chat_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_chat_photo.cpython-311.pyc new file mode 100644 index 0000000..ef77708 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_chat_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_chat_sticker_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_chat_sticker_set.cpython-311.pyc new file mode 100644 index 0000000..962556d Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_chat_sticker_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..fe9c022 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_message.cpython-311.pyc new file mode 100644 index 0000000..4d313b8 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_messages.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_messages.cpython-311.pyc new file mode 100644 index 0000000..ae95e3e Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_messages.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_my_commands.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_my_commands.cpython-311.pyc new file mode 100644 index 0000000..9519683 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_my_commands.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_sticker_from_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_sticker_from_set.cpython-311.pyc new file mode 100644 index 0000000..eddd32b Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_sticker_from_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_sticker_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_sticker_set.cpython-311.pyc new file mode 100644 index 0000000..1fa96ea Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_sticker_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/delete_webhook.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_webhook.cpython-311.pyc new file mode 100644 index 0000000..038dddc Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/delete_webhook.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_chat_invite_link.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_chat_invite_link.cpython-311.pyc new file mode 100644 index 0000000..e514bc2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_chat_invite_link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_chat_subscription_invite_link.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_chat_subscription_invite_link.cpython-311.pyc new file mode 100644 index 0000000..130c845 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_chat_subscription_invite_link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..f393ab9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_general_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_general_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..997b017 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_general_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_caption.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_caption.cpython-311.pyc new file mode 100644 index 0000000..e4195ca Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_caption.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_live_location.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_live_location.cpython-311.pyc new file mode 100644 index 0000000..687ffb3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_live_location.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_media.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_media.cpython-311.pyc new file mode 100644 index 0000000..d5142c6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_media.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_reply_markup.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_reply_markup.cpython-311.pyc new file mode 100644 index 0000000..edfa056 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_reply_markup.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_text.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_text.cpython-311.pyc new file mode 100644 index 0000000..058f326 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/edit_message_text.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/export_chat_invite_link.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/export_chat_invite_link.cpython-311.pyc new file mode 100644 index 0000000..66c47df Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/export_chat_invite_link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/forward_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/forward_message.cpython-311.pyc new file mode 100644 index 0000000..da4a2a5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/forward_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/forward_messages.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/forward_messages.cpython-311.pyc new file mode 100644 index 0000000..3358a8a Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/forward_messages.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_business_connection.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_business_connection.cpython-311.pyc new file mode 100644 index 0000000..43a163f Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_business_connection.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat.cpython-311.pyc new file mode 100644 index 0000000..e5e8b04 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_administrators.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_administrators.cpython-311.pyc new file mode 100644 index 0000000..834aa56 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_administrators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_member.cpython-311.pyc new file mode 100644 index 0000000..a196474 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_member_count.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_member_count.cpython-311.pyc new file mode 100644 index 0000000..6cb54b1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_member_count.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_menu_button.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_menu_button.cpython-311.pyc new file mode 100644 index 0000000..3307b67 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_chat_menu_button.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_custom_emoji_stickers.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_custom_emoji_stickers.cpython-311.pyc new file mode 100644 index 0000000..32a662e Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_custom_emoji_stickers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_file.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_file.cpython-311.pyc new file mode 100644 index 0000000..c1318d5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_file.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_forum_topic_icon_stickers.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_forum_topic_icon_stickers.cpython-311.pyc new file mode 100644 index 0000000..1740ab9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_forum_topic_icon_stickers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_game_high_scores.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_game_high_scores.cpython-311.pyc new file mode 100644 index 0000000..cb99480 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_game_high_scores.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_me.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_me.cpython-311.pyc new file mode 100644 index 0000000..818ef8e Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_me.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_commands.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_commands.cpython-311.pyc new file mode 100644 index 0000000..ac6a534 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_commands.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_default_administrator_rights.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_default_administrator_rights.cpython-311.pyc new file mode 100644 index 0000000..dc47504 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_default_administrator_rights.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_description.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_description.cpython-311.pyc new file mode 100644 index 0000000..42ed125 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_description.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_name.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_name.cpython-311.pyc new file mode 100644 index 0000000..579097f Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_name.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_short_description.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_short_description.cpython-311.pyc new file mode 100644 index 0000000..88844bf Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_my_short_description.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_star_transactions.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_star_transactions.cpython-311.pyc new file mode 100644 index 0000000..5ad40b6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_star_transactions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_sticker_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_sticker_set.cpython-311.pyc new file mode 100644 index 0000000..de2401a Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_sticker_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_updates.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_updates.cpython-311.pyc new file mode 100644 index 0000000..71c3412 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_updates.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_user_chat_boosts.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_user_chat_boosts.cpython-311.pyc new file mode 100644 index 0000000..d5e2b5f Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_user_chat_boosts.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_user_profile_photos.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_user_profile_photos.cpython-311.pyc new file mode 100644 index 0000000..8f83768 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_user_profile_photos.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/get_webhook_info.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/get_webhook_info.cpython-311.pyc new file mode 100644 index 0000000..bcad955 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/get_webhook_info.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/hide_general_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/hide_general_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..1eff922 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/hide_general_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/leave_chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/leave_chat.cpython-311.pyc new file mode 100644 index 0000000..8c4ad6a Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/leave_chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/log_out.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/log_out.cpython-311.pyc new file mode 100644 index 0000000..b3a3405 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/log_out.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/pin_chat_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/pin_chat_message.cpython-311.pyc new file mode 100644 index 0000000..da1eada Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/pin_chat_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/promote_chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/promote_chat_member.cpython-311.pyc new file mode 100644 index 0000000..e9331f9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/promote_chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/refund_star_payment.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/refund_star_payment.cpython-311.pyc new file mode 100644 index 0000000..9d31f7e Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/refund_star_payment.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/reopen_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/reopen_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..437e3c6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/reopen_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/reopen_general_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/reopen_general_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..c013133 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/reopen_general_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/replace_sticker_in_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/replace_sticker_in_set.cpython-311.pyc new file mode 100644 index 0000000..ee763ca Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/replace_sticker_in_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/restrict_chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/restrict_chat_member.cpython-311.pyc new file mode 100644 index 0000000..71aa06a Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/restrict_chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/revoke_chat_invite_link.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/revoke_chat_invite_link.cpython-311.pyc new file mode 100644 index 0000000..a24d8d8 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/revoke_chat_invite_link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_animation.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_animation.cpython-311.pyc new file mode 100644 index 0000000..54aff8f Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_animation.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_audio.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_audio.cpython-311.pyc new file mode 100644 index 0000000..7162c25 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_audio.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_chat_action.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_chat_action.cpython-311.pyc new file mode 100644 index 0000000..7997f09 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_chat_action.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_contact.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_contact.cpython-311.pyc new file mode 100644 index 0000000..6f1126c Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_contact.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_dice.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_dice.cpython-311.pyc new file mode 100644 index 0000000..fd297ad Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_dice.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_document.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_document.cpython-311.pyc new file mode 100644 index 0000000..c99a437 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_document.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_game.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_game.cpython-311.pyc new file mode 100644 index 0000000..6119721 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_game.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_invoice.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_invoice.cpython-311.pyc new file mode 100644 index 0000000..a1ce63e Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_invoice.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_location.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_location.cpython-311.pyc new file mode 100644 index 0000000..effb9fa Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_location.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_media_group.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_media_group.cpython-311.pyc new file mode 100644 index 0000000..43e30be Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_media_group.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_message.cpython-311.pyc new file mode 100644 index 0000000..3f2860f Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_paid_media.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_paid_media.cpython-311.pyc new file mode 100644 index 0000000..656e2e6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_paid_media.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_photo.cpython-311.pyc new file mode 100644 index 0000000..7779dcb Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_poll.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_poll.cpython-311.pyc new file mode 100644 index 0000000..15ce756 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_poll.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_sticker.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_sticker.cpython-311.pyc new file mode 100644 index 0000000..b586954 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_sticker.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_venue.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_venue.cpython-311.pyc new file mode 100644 index 0000000..2548f39 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_venue.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_video.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_video.cpython-311.pyc new file mode 100644 index 0000000..ae4324b Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_video.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_video_note.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_video_note.cpython-311.pyc new file mode 100644 index 0000000..b783f96 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_video_note.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/send_voice.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/send_voice.cpython-311.pyc new file mode 100644 index 0000000..14a3fb7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/send_voice.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_administrator_custom_title.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_administrator_custom_title.cpython-311.pyc new file mode 100644 index 0000000..3d08c86 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_administrator_custom_title.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_description.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_description.cpython-311.pyc new file mode 100644 index 0000000..c007e9a Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_description.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_menu_button.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_menu_button.cpython-311.pyc new file mode 100644 index 0000000..895f3b7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_menu_button.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_permissions.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_permissions.cpython-311.pyc new file mode 100644 index 0000000..72408ce Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_permissions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_photo.cpython-311.pyc new file mode 100644 index 0000000..0ce412e Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_sticker_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_sticker_set.cpython-311.pyc new file mode 100644 index 0000000..9fe2e2a Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_sticker_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_title.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_title.cpython-311.pyc new file mode 100644 index 0000000..66668e4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_chat_title.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_custom_emoji_sticker_set_thumbnail.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_custom_emoji_sticker_set_thumbnail.cpython-311.pyc new file mode 100644 index 0000000..c87dcf2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_custom_emoji_sticker_set_thumbnail.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_game_score.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_game_score.cpython-311.pyc new file mode 100644 index 0000000..eba6dc4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_game_score.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_message_reaction.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_message_reaction.cpython-311.pyc new file mode 100644 index 0000000..1a9d887 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_message_reaction.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_commands.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_commands.cpython-311.pyc new file mode 100644 index 0000000..2306134 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_commands.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_default_administrator_rights.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_default_administrator_rights.cpython-311.pyc new file mode 100644 index 0000000..24499eb Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_default_administrator_rights.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_description.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_description.cpython-311.pyc new file mode 100644 index 0000000..7dbdbcd Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_description.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_name.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_name.cpython-311.pyc new file mode 100644 index 0000000..751a9db Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_name.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_short_description.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_short_description.cpython-311.pyc new file mode 100644 index 0000000..402fadd Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_my_short_description.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_passport_data_errors.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_passport_data_errors.cpython-311.pyc new file mode 100644 index 0000000..2654323 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_passport_data_errors.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_emoji_list.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_emoji_list.cpython-311.pyc new file mode 100644 index 0000000..eb9bdc5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_emoji_list.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_keywords.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_keywords.cpython-311.pyc new file mode 100644 index 0000000..00b0d15 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_keywords.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_mask_position.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_mask_position.cpython-311.pyc new file mode 100644 index 0000000..7b4df04 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_mask_position.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_position_in_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_position_in_set.cpython-311.pyc new file mode 100644 index 0000000..06fa42a Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_position_in_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_set_thumbnail.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_set_thumbnail.cpython-311.pyc new file mode 100644 index 0000000..0a1b7c8 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_set_thumbnail.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_set_title.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_set_title.cpython-311.pyc new file mode 100644 index 0000000..5963ae6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_sticker_set_title.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/set_webhook.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/set_webhook.cpython-311.pyc new file mode 100644 index 0000000..2de1839 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/set_webhook.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/stop_message_live_location.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/stop_message_live_location.cpython-311.pyc new file mode 100644 index 0000000..da8a6df Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/stop_message_live_location.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/stop_poll.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/stop_poll.cpython-311.pyc new file mode 100644 index 0000000..334f1ee Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/stop_poll.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/unban_chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/unban_chat_member.cpython-311.pyc new file mode 100644 index 0000000..4bd8025 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/unban_chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/unban_chat_sender_chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/unban_chat_sender_chat.cpython-311.pyc new file mode 100644 index 0000000..a67b3aa Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/unban_chat_sender_chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/unhide_general_forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/unhide_general_forum_topic.cpython-311.pyc new file mode 100644 index 0000000..4e2719d Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/unhide_general_forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_chat_messages.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_chat_messages.cpython-311.pyc new file mode 100644 index 0000000..69b8a37 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_chat_messages.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_forum_topic_messages.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_forum_topic_messages.cpython-311.pyc new file mode 100644 index 0000000..3e00676 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_forum_topic_messages.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_general_forum_topic_messages.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_general_forum_topic_messages.cpython-311.pyc new file mode 100644 index 0000000..cf9df6d Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_all_general_forum_topic_messages.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_chat_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_chat_message.cpython-311.pyc new file mode 100644 index 0000000..6f01b48 Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/unpin_chat_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/__pycache__/upload_sticker_file.cpython-311.pyc b/env/Lib/site-packages/aiogram/methods/__pycache__/upload_sticker_file.cpython-311.pyc new file mode 100644 index 0000000..7f4fb5c Binary files /dev/null and b/env/Lib/site-packages/aiogram/methods/__pycache__/upload_sticker_file.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/methods/add_sticker_to_set.py b/env/Lib/site-packages/aiogram/methods/add_sticker_to_set.py new file mode 100644 index 0000000..cc2e31d --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/add_sticker_to_set.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ..types import InputSticker +from .base import TelegramMethod + + +class AddStickerToSet(TelegramMethod[bool]): + """ + Use this method to add a new sticker to a set created by the bot. Emoji sticker sets can have up to 200 stickers. Other sticker sets can have up to 120 stickers. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#addstickertoset + """ + + __returning__ = bool + __api_method__ = "addStickerToSet" + + user_id: int + """User identifier of sticker set owner""" + name: str + """Sticker set name""" + sticker: InputSticker + """A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set isn't changed.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + name: str, + sticker: InputSticker, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(user_id=user_id, name=name, sticker=sticker, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/answer_callback_query.py b/env/Lib/site-packages/aiogram/methods/answer_callback_query.py new file mode 100644 index 0000000..15ed1bf --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/answer_callback_query.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramMethod + + +class AnswerCallbackQuery(TelegramMethod[bool]): + """ + Use this method to send answers to callback queries sent from `inline keyboards `_. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, :code:`True` is returned. + + Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via `@BotFather `_ and accept the terms. Otherwise, you may use links like :code:`t.me/your_bot?start=XXXX` that open your bot with a parameter. + + Source: https://core.telegram.org/bots/api#answercallbackquery + """ + + __returning__ = bool + __api_method__ = "answerCallbackQuery" + + callback_query_id: str + """Unique identifier for the query to be answered""" + text: Optional[str] = None + """Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters""" + show_alert: Optional[bool] = None + """If :code:`True`, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to *false*.""" + url: Optional[str] = None + """URL that will be opened by the user's client. If you have created a :class:`aiogram.types.game.Game` and accepted the conditions via `@BotFather `_, specify the URL that opens your game - note that this will only work if the query comes from a `https://core.telegram.org/bots/api#inlinekeyboardbutton `_ *callback_game* button.""" + cache_time: Optional[int] = None + """The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + callback_query_id: str, + text: Optional[str] = None, + show_alert: Optional[bool] = None, + url: Optional[str] = None, + cache_time: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + callback_query_id=callback_query_id, + text=text, + show_alert=show_alert, + url=url, + cache_time=cache_time, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/answer_inline_query.py b/env/Lib/site-packages/aiogram/methods/answer_inline_query.py new file mode 100644 index 0000000..acfb80a --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/answer_inline_query.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..types import ( + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultContact, + InlineQueryResultDocument, + InlineQueryResultGame, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultsButton, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, +) +from .base import TelegramMethod + + +class AnswerInlineQuery(TelegramMethod[bool]): + """ + Use this method to send answers to an inline query. On success, :code:`True` is returned. + + No more than **50** results per query are allowed. + + Source: https://core.telegram.org/bots/api#answerinlinequery + """ + + __returning__ = bool + __api_method__ = "answerInlineQuery" + + inline_query_id: str + """Unique identifier for the answered query""" + results: List[ + Union[ + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultContact, + InlineQueryResultGame, + InlineQueryResultDocument, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + ] + ] + """A JSON-serialized array of results for the inline query""" + cache_time: Optional[int] = None + """The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300.""" + is_personal: Optional[bool] = None + """Pass :code:`True` if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query.""" + next_offset: Optional[str] = None + """Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes.""" + button: Optional[InlineQueryResultsButton] = None + """A JSON-serialized object describing a button to be shown above inline query results""" + switch_pm_parameter: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """`Deep-linking `_ parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only :code:`A-Z`, :code:`a-z`, :code:`0-9`, :code:`_` and :code:`-` are allowed. + +.. deprecated:: API:6.7 + https://core.telegram.org/bots/api-changelog#april-21-2023""" + switch_pm_text: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter *switch_pm_parameter* + +.. deprecated:: API:6.7 + https://core.telegram.org/bots/api-changelog#april-21-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + inline_query_id: str, + results: List[ + Union[ + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultContact, + InlineQueryResultGame, + InlineQueryResultDocument, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + ] + ], + cache_time: Optional[int] = None, + is_personal: Optional[bool] = None, + next_offset: Optional[str] = None, + button: Optional[InlineQueryResultsButton] = None, + switch_pm_parameter: Optional[str] = None, + switch_pm_text: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + inline_query_id=inline_query_id, + results=results, + cache_time=cache_time, + is_personal=is_personal, + next_offset=next_offset, + button=button, + switch_pm_parameter=switch_pm_parameter, + switch_pm_text=switch_pm_text, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/answer_pre_checkout_query.py b/env/Lib/site-packages/aiogram/methods/answer_pre_checkout_query.py new file mode 100644 index 0000000..479d76c --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/answer_pre_checkout_query.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramMethod + + +class AnswerPreCheckoutQuery(TelegramMethod[bool]): + """ + Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an :class:`aiogram.types.update.Update` with the field *pre_checkout_query*. Use this method to respond to such pre-checkout queries. On success, :code:`True` is returned. **Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. + + Source: https://core.telegram.org/bots/api#answerprecheckoutquery + """ + + __returning__ = bool + __api_method__ = "answerPreCheckoutQuery" + + pre_checkout_query_id: str + """Unique identifier for the query to be answered""" + ok: bool + """Specify :code:`True` if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use :code:`False` if there are any problems.""" + error_message: Optional[str] = None + """Required if *ok* is :code:`False`. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + pre_checkout_query_id: str, + ok: bool, + error_message: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + pre_checkout_query_id=pre_checkout_query_id, + ok=ok, + error_message=error_message, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/answer_shipping_query.py b/env/Lib/site-packages/aiogram/methods/answer_shipping_query.py new file mode 100644 index 0000000..ad0e9dc --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/answer_shipping_query.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from ..types import ShippingOption +from .base import TelegramMethod + + +class AnswerShippingQuery(TelegramMethod[bool]): + """ + If you sent an invoice requesting a shipping address and the parameter *is_flexible* was specified, the Bot API will send an :class:`aiogram.types.update.Update` with a *shipping_query* field to the bot. Use this method to reply to shipping queries. On success, :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#answershippingquery + """ + + __returning__ = bool + __api_method__ = "answerShippingQuery" + + shipping_query_id: str + """Unique identifier for the query to be answered""" + ok: bool + """Pass :code:`True` if delivery to the specified address is possible and :code:`False` if there are any problems (for example, if delivery to the specified address is not possible)""" + shipping_options: Optional[List[ShippingOption]] = None + """Required if *ok* is :code:`True`. A JSON-serialized array of available shipping options.""" + error_message: Optional[str] = None + """Required if *ok* is :code:`False`. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + shipping_query_id: str, + ok: bool, + shipping_options: Optional[List[ShippingOption]] = None, + error_message: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + shipping_query_id=shipping_query_id, + ok=ok, + shipping_options=shipping_options, + error_message=error_message, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/answer_web_app_query.py b/env/Lib/site-packages/aiogram/methods/answer_web_app_query.py new file mode 100644 index 0000000..4dc87eb --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/answer_web_app_query.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from ..types import ( + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultContact, + InlineQueryResultDocument, + InlineQueryResultGame, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + SentWebAppMessage, +) +from .base import TelegramMethod + + +class AnswerWebAppQuery(TelegramMethod[SentWebAppMessage]): + """ + Use this method to set the result of an interaction with a `Web App `_ and send a corresponding message on behalf of the user to the chat from which the query originated. On success, a :class:`aiogram.types.sent_web_app_message.SentWebAppMessage` object is returned. + + Source: https://core.telegram.org/bots/api#answerwebappquery + """ + + __returning__ = SentWebAppMessage + __api_method__ = "answerWebAppQuery" + + web_app_query_id: str + """Unique identifier for the query to be answered""" + result: Union[ + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultContact, + InlineQueryResultGame, + InlineQueryResultDocument, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + ] + """A JSON-serialized object describing the message to be sent""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + web_app_query_id: str, + result: Union[ + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultContact, + InlineQueryResultGame, + InlineQueryResultDocument, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + ], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(web_app_query_id=web_app_query_id, result=result, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/approve_chat_join_request.py b/env/Lib/site-packages/aiogram/methods/approve_chat_join_request.py new file mode 100644 index 0000000..2f4995b --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/approve_chat_join_request.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class ApproveChatJoinRequest(TelegramMethod[bool]): + """ + Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the *can_invite_users* administrator right. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#approvechatjoinrequest + """ + + __returning__ = bool + __api_method__ = "approveChatJoinRequest" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + user_id: int + """Unique identifier of the target user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], user_id: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, user_id=user_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/ban_chat_member.py b/env/Lib/site-packages/aiogram/methods/ban_chat_member.py new file mode 100644 index 0000000..947fcca --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/ban_chat_member.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramMethod + + +class BanChatMember(TelegramMethod[bool]): + """ + Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless `unbanned `_ first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#banchatmember + """ + + __returning__ = bool + __api_method__ = "banChatMember" + + chat_id: Union[int, str] + """Unique identifier for the target group or username of the target supergroup or channel (in the format :code:`@channelusername`)""" + user_id: int + """Unique identifier of the target user""" + until_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None + """Date when the user will be unbanned; Unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only.""" + revoke_messages: Optional[bool] = None + """Pass :code:`True` to delete all messages from the chat for the user that is being removed. If :code:`False`, the user will be able to see messages in the group that were sent before the user was removed. Always :code:`True` for supergroups and channels.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + user_id: int, + until_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + revoke_messages: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + user_id=user_id, + until_date=until_date, + revoke_messages=revoke_messages, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/ban_chat_sender_chat.py b/env/Lib/site-packages/aiogram/methods/ban_chat_sender_chat.py new file mode 100644 index 0000000..cbe6194 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/ban_chat_sender_chat.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class BanChatSenderChat(TelegramMethod[bool]): + """ + Use this method to ban a channel chat in a supergroup or a channel. Until the chat is `unbanned `_, the owner of the banned chat won't be able to send messages on behalf of **any of their channels**. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#banchatsenderchat + """ + + __returning__ = bool + __api_method__ = "banChatSenderChat" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + sender_chat_id: int + """Unique identifier of the target sender chat""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + sender_chat_id: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, sender_chat_id=sender_chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/base.py b/env/Lib/site-packages/aiogram/methods/base.py new file mode 100644 index 0000000..b2d35be --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/base.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + Dict, + Generator, + Generic, + Optional, + TypeVar, +) + +from pydantic import BaseModel, ConfigDict +from pydantic.functional_validators import model_validator + +from aiogram.client.context_controller import BotContextController + +from ..types import InputFile, ResponseParameters +from ..types.base import UNSET_TYPE + +if TYPE_CHECKING: + from ..client.bot import Bot + +TelegramType = TypeVar("TelegramType", bound=Any) + + +class Request(BaseModel): + model_config = ConfigDict(arbitrary_types_allowed=True) + + method: str + + data: Dict[str, Optional[Any]] + files: Optional[Dict[str, InputFile]] + + +class Response(BaseModel, Generic[TelegramType]): + ok: bool + result: Optional[TelegramType] = None + description: Optional[str] = None + error_code: Optional[int] = None + parameters: Optional[ResponseParameters] = None + + +class TelegramMethod(BotContextController, BaseModel, Generic[TelegramType], ABC): + model_config = ConfigDict( + extra="allow", + populate_by_name=True, + arbitrary_types_allowed=True, + ) + + @model_validator(mode="before") + @classmethod + def remove_unset(cls, values: Dict[str, Any]) -> Dict[str, Any]: + """ + Remove UNSET before fields validation. + + We use UNSET as a sentinel value for `parse_mode` and replace it to real value later. + It isn't a problem when it's just default value for a model field, + but UNSET might be passing to a model initialization from `Bot.method_name`, + so we must take care of it and remove it before fields validation. + """ + if not isinstance(values, dict): + return values + return {k: v for k, v in values.items() if not isinstance(v, UNSET_TYPE)} + + if TYPE_CHECKING: + __returning__: ClassVar[type] + __api_method__: ClassVar[str] + else: + + @property + @abstractmethod + def __returning__(self) -> type: + pass + + @property + @abstractmethod + def __api_method__(self) -> str: + pass + + async def emit(self, bot: Bot) -> TelegramType: + return await bot(self) + + def __await__(self) -> Generator[Any, None, TelegramType]: + bot = self._bot + if not bot: + raise RuntimeError( + "This method is not mounted to a any bot instance, please call it explicilty " + "with bot instance `await bot(method)`\n" + "or mount method to a bot instance `method.as_(bot)` " + "and then call it `await method()`" + ) + return self.emit(bot).__await__() diff --git a/env/Lib/site-packages/aiogram/methods/close.py b/env/Lib/site-packages/aiogram/methods/close.py new file mode 100644 index 0000000..7c33eca --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/close.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from .base import TelegramMethod + + +class Close(TelegramMethod[bool]): + """ + Use this method to close the bot instance before moving it from one local server to another. You need to delete the webhook before calling this method to ensure that the bot isn't launched again after server restart. The method will return error 429 in the first 10 minutes after the bot is launched. Returns :code:`True` on success. Requires no parameters. + + Source: https://core.telegram.org/bots/api#close + """ + + __returning__ = bool + __api_method__ = "close" diff --git a/env/Lib/site-packages/aiogram/methods/close_forum_topic.py b/env/Lib/site-packages/aiogram/methods/close_forum_topic.py new file mode 100644 index 0000000..110fbce --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/close_forum_topic.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class CloseForumTopic(TelegramMethod[bool]): + """ + Use this method to close an open topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#closeforumtopic + """ + + __returning__ = bool + __api_method__ = "closeForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + message_thread_id: int + """Unique identifier for the target message thread of the forum topic""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_thread_id: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, message_thread_id=message_thread_id, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/close_general_forum_topic.py b/env/Lib/site-packages/aiogram/methods/close_general_forum_topic.py new file mode 100644 index 0000000..3f1a633 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/close_general_forum_topic.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class CloseGeneralForumTopic(TelegramMethod[bool]): + """ + Use this method to close an open 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#closegeneralforumtopic + """ + + __returning__ = bool + __api_method__ = "closeGeneralForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/copy_message.py b/env/Lib/site-packages/aiogram/methods/copy_message.py new file mode 100644 index 0000000..ca44f93 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/copy_message.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + MessageEntity, + MessageId, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class CopyMessage(TelegramMethod[MessageId]): + """ + Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz :class:`aiogram.methods.poll.Poll` can be copied only if the value of the field *correct_option_id* is known to the bot. The method is analogous to the method :class:`aiogram.methods.forward_message.ForwardMessage`, but the copied message doesn't have a link to the original message. Returns the :class:`aiogram.types.message_id.MessageId` of the sent message on success. + + Source: https://core.telegram.org/bots/api#copymessage + """ + + __returning__ = MessageId + __api_method__ = "copyMessage" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + from_chat_id: Union[int, str] + """Unique identifier for the chat where the original message was sent (or channel username in the format :code:`@channelusername`)""" + message_id: int + """Message identifier in the chat specified in *from_chat_id*""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + caption: Optional[str] = None + """New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the new caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """Pass :code:`True`, if the caption must be shown above the message media. Ignored if a new caption isn't specified.""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_id: int, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + from_chat_id=from_chat_id, + message_id=message_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + disable_notification=disable_notification, + protect_content=protect_content, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/copy_messages.py b/env/Lib/site-packages/aiogram/methods/copy_messages.py new file mode 100644 index 0000000..c734d0a --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/copy_messages.py @@ -0,0 +1,61 @@ +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..types import MessageId +from .base import TelegramMethod + + +class CopyMessages(TelegramMethod[List[MessageId]]): + """ + Use this method to copy messages of any kind. If some of the specified messages can't be found or copied, they are skipped. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz :class:`aiogram.methods.poll.Poll` can be copied only if the value of the field *correct_option_id* is known to the bot. The method is analogous to the method :class:`aiogram.methods.forward_messages.ForwardMessages`, but the copied messages don't have a link to the original message. Album grouping is kept for copied messages. On success, an array of :class:`aiogram.types.message_id.MessageId` of the sent messages is returned. + + Source: https://core.telegram.org/bots/api#copymessages + """ + + __returning__ = List[MessageId] + __api_method__ = "copyMessages" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + from_chat_id: Union[int, str] + """Unique identifier for the chat where the original messages were sent (or channel username in the format :code:`@channelusername`)""" + message_ids: List[int] + """A JSON-serialized list of 1-100 identifiers of messages in the chat *from_chat_id* to copy. The identifiers must be specified in a strictly increasing order.""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + disable_notification: Optional[bool] = None + """Sends the messages `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[bool] = None + """Protects the contents of the sent messages from forwarding and saving""" + remove_caption: Optional[bool] = None + """Pass :code:`True` to copy the messages without their captions""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_ids: List[int], + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[bool] = None, + remove_caption: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + from_chat_id=from_chat_id, + message_ids=message_ids, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + remove_caption=remove_caption, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/create_chat_invite_link.py b/env/Lib/site-packages/aiogram/methods/create_chat_invite_link.py new file mode 100644 index 0000000..ff0b386 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/create_chat_invite_link.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ChatInviteLink +from .base import TelegramMethod + + +class CreateChatInviteLink(TelegramMethod[ChatInviteLink]): + """ + Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method :class:`aiogram.methods.revoke_chat_invite_link.RevokeChatInviteLink`. Returns the new invite link as :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#createchatinvitelink + """ + + __returning__ = ChatInviteLink + __api_method__ = "createChatInviteLink" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + name: Optional[str] = None + """Invite link name; 0-32 characters""" + expire_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None + """Point in time (Unix timestamp) when the link will expire""" + member_limit: Optional[int] = None + """The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999""" + creates_join_request: Optional[bool] = None + """:code:`True`, if users joining the chat via the link need to be approved by chat administrators. If :code:`True`, *member_limit* can't be specified""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + name: Optional[str] = None, + expire_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + member_limit: Optional[int] = None, + creates_join_request: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + name=name, + expire_date=expire_date, + member_limit=member_limit, + creates_join_request=creates_join_request, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/create_chat_subscription_invite_link.py b/env/Lib/site-packages/aiogram/methods/create_chat_subscription_invite_link.py new file mode 100644 index 0000000..1301eb2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/create_chat_subscription_invite_link.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ChatInviteLink +from .base import TelegramMethod + + +class CreateChatSubscriptionInviteLink(TelegramMethod[ChatInviteLink]): + """ + Use this method to create a `subscription invite link `_ for a channel chat. The bot must have the *can_invite_users* administrator rights. The link can be edited using the method :class:`aiogram.methods.edit_chat_subscription_invite_link.EditChatSubscriptionInviteLink` or revoked using the method :class:`aiogram.methods.revoke_chat_invite_link.RevokeChatInviteLink`. Returns the new invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#createchatsubscriptioninvitelink + """ + + __returning__ = ChatInviteLink + __api_method__ = "createChatSubscriptionInviteLink" + + chat_id: Union[int, str] + """Unique identifier for the target channel chat or username of the target channel (in the format :code:`@channelusername`)""" + subscription_period: Union[datetime.datetime, datetime.timedelta, int] + """The number of seconds the subscription will be active for before the next payment. Currently, it must always be 2592000 (30 days).""" + subscription_price: int + """The amount of Telegram Stars a user must pay initially and after each subsequent subscription period to be a member of the chat; 1-2500""" + name: Optional[str] = None + """Invite link name; 0-32 characters""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + subscription_period: Union[datetime.datetime, datetime.timedelta, int], + subscription_price: int, + name: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + subscription_period=subscription_period, + subscription_price=subscription_price, + name=name, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/create_forum_topic.py b/env/Lib/site-packages/aiogram/methods/create_forum_topic.py new file mode 100644 index 0000000..8b0f692 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/create_forum_topic.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ForumTopic +from .base import TelegramMethod + + +class CreateForumTopic(TelegramMethod[ForumTopic]): + """ + Use this method to create a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns information about the created topic as a :class:`aiogram.types.forum_topic.ForumTopic` object. + + Source: https://core.telegram.org/bots/api#createforumtopic + """ + + __returning__ = ForumTopic + __api_method__ = "createForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + name: str + """Topic name, 1-128 characters""" + icon_color: Optional[int] = None + """Color of the topic icon in RGB format. Currently, must be one of 7322096 (0x6FB9F0), 16766590 (0xFFD67E), 13338331 (0xCB86DB), 9367192 (0x8EEE98), 16749490 (0xFF93B2), or 16478047 (0xFB6F5F)""" + icon_custom_emoji_id: Optional[str] = None + """Unique identifier of the custom emoji shown as the topic icon. Use :class:`aiogram.methods.get_forum_topic_icon_stickers.GetForumTopicIconStickers` to get all allowed custom emoji identifiers.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + name: str, + icon_color: Optional[int] = None, + icon_custom_emoji_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + name=name, + icon_color=icon_color, + icon_custom_emoji_id=icon_custom_emoji_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/create_invoice_link.py b/env/Lib/site-packages/aiogram/methods/create_invoice_link.py new file mode 100644 index 0000000..2068f75 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/create_invoice_link.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from ..types import LabeledPrice +from .base import TelegramMethod + + +class CreateInvoiceLink(TelegramMethod[str]): + """ + Use this method to create a link for an invoice. Returns the created invoice link as *String* on success. + + Source: https://core.telegram.org/bots/api#createinvoicelink + """ + + __returning__ = str + __api_method__ = "createInvoiceLink" + + title: str + """Product name, 1-32 characters""" + description: str + """Product description, 1-255 characters""" + payload: str + """Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.""" + currency: str + """Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_.""" + prices: List[LabeledPrice] + """Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_.""" + provider_token: Optional[str] = None + """Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_.""" + max_tip_amount: Optional[int] = None + """The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_.""" + suggested_tip_amounts: Optional[List[int]] = None + """A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*.""" + provider_data: Optional[str] = None + """JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.""" + photo_url: Optional[str] = None + """URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service.""" + photo_size: Optional[int] = None + """Photo size in bytes""" + photo_width: Optional[int] = None + """Photo width""" + photo_height: Optional[int] = None + """Photo height""" + need_name: Optional[bool] = None + """Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_phone_number: Optional[bool] = None + """Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_email: Optional[bool] = None + """Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_shipping_address: Optional[bool] = None + """Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_.""" + send_phone_number_to_provider: Optional[bool] = None + """Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_.""" + send_email_to_provider: Optional[bool] = None + """Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_.""" + is_flexible: Optional[bool] = None + """Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/create_new_sticker_set.py b/env/Lib/site-packages/aiogram/methods/create_new_sticker_set.py new file mode 100644 index 0000000..c304d85 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/create_new_sticker_set.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from pydantic import Field + +from ..types import InputSticker +from .base import TelegramMethod + + +class CreateNewStickerSet(TelegramMethod[bool]): + """ + Use this method to create a new sticker set owned by a user. The bot will be able to edit the sticker set thus created. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#createnewstickerset + """ + + __returning__ = bool + __api_method__ = "createNewStickerSet" + + user_id: int + """User identifier of created sticker set owner""" + name: str + """Short name of sticker set, to be used in :code:`t.me/addstickers/` URLs (e.g., *animals*). Can contain only English letters, digits and underscores. Must begin with a letter, can't contain consecutive underscores and must end in :code:`"_by_"`. :code:`` is case insensitive. 1-64 characters.""" + title: str + """Sticker set title, 1-64 characters""" + stickers: List[InputSticker] + """A JSON-serialized list of 1-50 initial stickers to be added to the sticker set""" + sticker_type: Optional[str] = None + """Type of stickers in the set, pass 'regular', 'mask', or 'custom_emoji'. By default, a regular sticker set is created.""" + needs_repainting: Optional[bool] = None + """Pass :code:`True` if stickers in the sticker set must be repainted to the color of text when used in messages, the accent color if used as emoji status, white on chat photos, or another appropriate color based on context; for custom emoji sticker sets only""" + sticker_format: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """Format of stickers in the set, must be one of 'static', 'animated', 'video' + +.. deprecated:: API:7.2 + https://core.telegram.org/bots/api-changelog#march-31-2024""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + name: str, + title: str, + stickers: List[InputSticker], + sticker_type: Optional[str] = None, + needs_repainting: Optional[bool] = None, + sticker_format: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + user_id=user_id, + name=name, + title=title, + stickers=stickers, + sticker_type=sticker_type, + needs_repainting=needs_repainting, + sticker_format=sticker_format, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/decline_chat_join_request.py b/env/Lib/site-packages/aiogram/methods/decline_chat_join_request.py new file mode 100644 index 0000000..b0fa2c3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/decline_chat_join_request.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class DeclineChatJoinRequest(TelegramMethod[bool]): + """ + Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the *can_invite_users* administrator right. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#declinechatjoinrequest + """ + + __returning__ = bool + __api_method__ = "declineChatJoinRequest" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + user_id: int + """Unique identifier of the target user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], user_id: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, user_id=user_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/delete_chat_photo.py b/env/Lib/site-packages/aiogram/methods/delete_chat_photo.py new file mode 100644 index 0000000..503ace2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_chat_photo.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class DeleteChatPhoto(TelegramMethod[bool]): + """ + Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletechatphoto + """ + + __returning__ = bool + __api_method__ = "deleteChatPhoto" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/delete_chat_sticker_set.py b/env/Lib/site-packages/aiogram/methods/delete_chat_sticker_set.py new file mode 100644 index 0000000..50d705f --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_chat_sticker_set.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class DeleteChatStickerSet(TelegramMethod[bool]): + """ + Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field *can_set_sticker_set* optionally returned in :class:`aiogram.methods.get_chat.GetChat` requests to check if the bot can use this method. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletechatstickerset + """ + + __returning__ = bool + __api_method__ = "deleteChatStickerSet" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/delete_forum_topic.py b/env/Lib/site-packages/aiogram/methods/delete_forum_topic.py new file mode 100644 index 0000000..7d23856 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_forum_topic.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class DeleteForumTopic(TelegramMethod[bool]): + """ + Use this method to delete a forum topic along with all its messages in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_delete_messages* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deleteforumtopic + """ + + __returning__ = bool + __api_method__ = "deleteForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + message_thread_id: int + """Unique identifier for the target message thread of the forum topic""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_thread_id: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, message_thread_id=message_thread_id, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/delete_message.py b/env/Lib/site-packages/aiogram/methods/delete_message.py new file mode 100644 index 0000000..59aee04 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_message.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class DeleteMessage(TelegramMethod[bool]): + """ + Use this method to delete a message, including service messages, with the following limitations: + + - A message can only be deleted if it was sent less than 48 hours ago. + + - Service messages about a supergroup, channel, or forum topic creation can't be deleted. + + - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. + + - Bots can delete outgoing messages in private chats, groups, and supergroups. + + - Bots can delete incoming messages in private chats. + + - Bots granted *can_post_messages* permissions can delete outgoing messages in channels. + + - If the bot is an administrator of a group, it can delete any message there. + + - If the bot has *can_delete_messages* permission in a supergroup or a channel, it can delete any message there. + + Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletemessage + """ + + __returning__ = bool + __api_method__ = "deleteMessage" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: int + """Identifier of the message to delete""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_id: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, message_id=message_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/delete_messages.py b/env/Lib/site-packages/aiogram/methods/delete_messages.py new file mode 100644 index 0000000..061d12b --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_messages.py @@ -0,0 +1,36 @@ +from typing import TYPE_CHECKING, Any, List, Union + +from .base import TelegramMethod + + +class DeleteMessages(TelegramMethod[bool]): + """ + Use this method to delete multiple messages simultaneously. If some of the specified messages can't be found, they are skipped. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletemessages + """ + + __returning__ = bool + __api_method__ = "deleteMessages" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_ids: List[int] + """A JSON-serialized list of 1-100 identifiers of messages to delete. See :class:`aiogram.methods.delete_message.DeleteMessage` for limitations on which messages can be deleted""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_ids: List[int], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, message_ids=message_ids, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/delete_my_commands.py b/env/Lib/site-packages/aiogram/methods/delete_my_commands.py new file mode 100644 index 0000000..e35ef67 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_my_commands.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ( + BotCommandScopeAllChatAdministrators, + BotCommandScopeAllGroupChats, + BotCommandScopeAllPrivateChats, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + BotCommandScopeDefault, +) +from .base import TelegramMethod + + +class DeleteMyCommands(TelegramMethod[bool]): + """ + Use this method to delete the list of the bot's commands for the given scope and user language. After deletion, `higher level commands `_ will be shown to affected users. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletemycommands + """ + + __returning__ = bool + __api_method__ = "deleteMyCommands" + + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None + """A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to :class:`aiogram.types.bot_command_scope_default.BotCommandScopeDefault`.""" + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None, + language_code: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(scope=scope, language_code=language_code, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/delete_sticker_from_set.py b/env/Lib/site-packages/aiogram/methods/delete_sticker_from_set.py new file mode 100644 index 0000000..6aae72b --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_sticker_from_set.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramMethod + + +class DeleteStickerFromSet(TelegramMethod[bool]): + """ + Use this method to delete a sticker from a set created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletestickerfromset + """ + + __returning__ = bool + __api_method__ = "deleteStickerFromSet" + + sticker: str + """File identifier of the sticker""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, sticker: str, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(sticker=sticker, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/delete_sticker_set.py b/env/Lib/site-packages/aiogram/methods/delete_sticker_set.py new file mode 100644 index 0000000..519c5db --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_sticker_set.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramMethod + + +class DeleteStickerSet(TelegramMethod[bool]): + """ + Use this method to delete a sticker set that was created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletestickerset + """ + + __returning__ = bool + __api_method__ = "deleteStickerSet" + + name: str + """Sticker set name""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, name: str, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(name=name, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/delete_webhook.py b/env/Lib/site-packages/aiogram/methods/delete_webhook.py new file mode 100644 index 0000000..05c39f4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/delete_webhook.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramMethod + + +class DeleteWebhook(TelegramMethod[bool]): + """ + Use this method to remove webhook integration if you decide to switch back to :class:`aiogram.methods.get_updates.GetUpdates`. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletewebhook + """ + + __returning__ = bool + __api_method__ = "deleteWebhook" + + drop_pending_updates: Optional[bool] = None + """Pass :code:`True` to drop all pending updates""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + drop_pending_updates: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(drop_pending_updates=drop_pending_updates, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/edit_chat_invite_link.py b/env/Lib/site-packages/aiogram/methods/edit_chat_invite_link.py new file mode 100644 index 0000000..8ec86ca --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_chat_invite_link.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ChatInviteLink +from .base import TelegramMethod + + +class EditChatInviteLink(TelegramMethod[ChatInviteLink]): + """ + Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#editchatinvitelink + """ + + __returning__ = ChatInviteLink + __api_method__ = "editChatInviteLink" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + invite_link: str + """The invite link to edit""" + name: Optional[str] = None + """Invite link name; 0-32 characters""" + expire_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None + """Point in time (Unix timestamp) when the link will expire""" + member_limit: Optional[int] = None + """The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999""" + creates_join_request: Optional[bool] = None + """:code:`True`, if users joining the chat via the link need to be approved by chat administrators. If :code:`True`, *member_limit* can't be specified""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + invite_link: str, + name: Optional[str] = None, + expire_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + member_limit: Optional[int] = None, + creates_join_request: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + invite_link=invite_link, + name=name, + expire_date=expire_date, + member_limit=member_limit, + creates_join_request=creates_join_request, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/edit_chat_subscription_invite_link.py b/env/Lib/site-packages/aiogram/methods/edit_chat_subscription_invite_link.py new file mode 100644 index 0000000..ffb37d8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_chat_subscription_invite_link.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ChatInviteLink +from .base import TelegramMethod + + +class EditChatSubscriptionInviteLink(TelegramMethod[ChatInviteLink]): + """ + Use this method to edit a subscription invite link created by the bot. The bot must have the *can_invite_users* administrator rights. Returns the edited invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#editchatsubscriptioninvitelink + """ + + __returning__ = ChatInviteLink + __api_method__ = "editChatSubscriptionInviteLink" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + invite_link: str + """The invite link to edit""" + name: Optional[str] = None + """Invite link name; 0-32 characters""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + invite_link: str, + name: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, invite_link=invite_link, name=name, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/edit_forum_topic.py b/env/Lib/site-packages/aiogram/methods/edit_forum_topic.py new file mode 100644 index 0000000..233e9cb --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_forum_topic.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramMethod + + +class EditForumTopic(TelegramMethod[bool]): + """ + Use this method to edit name and icon of a topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#editforumtopic + """ + + __returning__ = bool + __api_method__ = "editForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + message_thread_id: int + """Unique identifier for the target message thread of the forum topic""" + name: Optional[str] = None + """New topic name, 0-128 characters. If not specified or empty, the current name of the topic will be kept""" + icon_custom_emoji_id: Optional[str] = None + """New unique identifier of the custom emoji shown as the topic icon. Use :class:`aiogram.methods.get_forum_topic_icon_stickers.GetForumTopicIconStickers` to get all allowed custom emoji identifiers. Pass an empty string to remove the icon. If not specified, the current icon will be kept""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_thread_id: int, + name: Optional[str] = None, + icon_custom_emoji_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + message_thread_id=message_thread_id, + name=name, + icon_custom_emoji_id=icon_custom_emoji_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/edit_general_forum_topic.py b/env/Lib/site-packages/aiogram/methods/edit_general_forum_topic.py new file mode 100644 index 0000000..f0be56e --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_general_forum_topic.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class EditGeneralForumTopic(TelegramMethod[bool]): + """ + Use this method to edit the name of the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#editgeneralforumtopic + """ + + __returning__ = bool + __api_method__ = "editGeneralForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + name: str + """New topic name, 1-128 characters""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], name: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, name=name, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/edit_message_caption.py b/env/Lib/site-packages/aiogram/methods/edit_message_caption.py new file mode 100644 index 0000000..8a759d4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_message_caption.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..client.default import Default +from ..types import UNSET_PARSE_MODE, InlineKeyboardMarkup, Message, MessageEntity +from .base import TelegramMethod + + +class EditMessageCaption(TelegramMethod[Union[Message, bool]]): + """ + Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagecaption + """ + + __returning__ = Union[Message, bool] + __api_method__ = "editMessageCaption" + + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message to be edited was sent""" + chat_id: Optional[Union[int, str]] = None + """Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Identifier of the message to edit""" + inline_message_id: Optional[str] = None + """Required if *chat_id* and *message_id* are not specified. Identifier of the inline message""" + caption: Optional[str] = None + """New caption of the message, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the message caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """Pass :code:`True`, if the caption must be shown above the message media. Supported only for animation, photo and video messages.""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for an `inline keyboard `_.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/edit_message_live_location.py b/env/Lib/site-packages/aiogram/methods/edit_message_live_location.py new file mode 100644 index 0000000..6bc5569 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_message_live_location.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import InlineKeyboardMarkup, Message +from .base import TelegramMethod + + +class EditMessageLiveLocation(TelegramMethod[Union[Message, bool]]): + """ + Use this method to edit live location messages. A location can be edited until its *live_period* expires or editing is explicitly disabled by a call to :class:`aiogram.methods.stop_message_live_location.StopMessageLiveLocation`. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#editmessagelivelocation + """ + + __returning__ = Union[Message, bool] + __api_method__ = "editMessageLiveLocation" + + latitude: float + """Latitude of new location""" + longitude: float + """Longitude of new location""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message to be edited was sent""" + chat_id: Optional[Union[int, str]] = None + """Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Identifier of the message to edit""" + inline_message_id: Optional[str] = None + """Required if *chat_id* and *message_id* are not specified. Identifier of the inline message""" + live_period: Optional[int] = None + """New period in seconds during which the location can be updated, starting from the message send date. If 0x7FFFFFFF is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current *live_period* by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then *live_period* remains unchanged""" + horizontal_accuracy: Optional[float] = None + """The radius of uncertainty for the location, measured in meters; 0-1500""" + heading: Optional[int] = None + """Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.""" + proximity_alert_radius: Optional[int] = None + """The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for a new `inline keyboard `_.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + latitude: float, + longitude: float, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + live_period: Optional[int] = None, + horizontal_accuracy: Optional[float] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + latitude=latitude, + longitude=longitude, + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + live_period=live_period, + horizontal_accuracy=horizontal_accuracy, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + reply_markup=reply_markup, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/edit_message_media.py b/env/Lib/site-packages/aiogram/methods/edit_message_media.py new file mode 100644 index 0000000..b898be7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_message_media.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ( + InlineKeyboardMarkup, + InputMediaAnimation, + InputMediaAudio, + InputMediaDocument, + InputMediaPhoto, + InputMediaVideo, + Message, +) +from .base import TelegramMethod + + +class EditMessageMedia(TelegramMethod[Union[Message, bool]]): + """ + Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagemedia + """ + + __returning__ = Union[Message, bool] + __api_method__ = "editMessageMedia" + + media: Union[ + InputMediaAnimation, InputMediaDocument, InputMediaAudio, InputMediaPhoto, InputMediaVideo + ] + """A JSON-serialized object for a new media content of the message""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message to be edited was sent""" + chat_id: Optional[Union[int, str]] = None + """Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Identifier of the message to edit""" + inline_message_id: Optional[str] = None + """Required if *chat_id* and *message_id* are not specified. Identifier of the inline message""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for a new `inline keyboard `_.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + media: Union[ + InputMediaAnimation, + InputMediaDocument, + InputMediaAudio, + InputMediaPhoto, + InputMediaVideo, + ], + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + media=media, + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/edit_message_reply_markup.py b/env/Lib/site-packages/aiogram/methods/edit_message_reply_markup.py new file mode 100644 index 0000000..49052f3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_message_reply_markup.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import InlineKeyboardMarkup, Message +from .base import TelegramMethod + + +class EditMessageReplyMarkup(TelegramMethod[Union[Message, bool]]): + """ + Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagereplymarkup + """ + + __returning__ = Union[Message, bool] + __api_method__ = "editMessageReplyMarkup" + + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message to be edited was sent""" + chat_id: Optional[Union[int, str]] = None + """Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Identifier of the message to edit""" + inline_message_id: Optional[str] = None + """Required if *chat_id* and *message_id* are not specified. Identifier of the inline message""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for an `inline keyboard `_.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/edit_message_text.py b/env/Lib/site-packages/aiogram/methods/edit_message_text.py new file mode 100644 index 0000000..cfaaa94 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/edit_message_text.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + UNSET_PARSE_MODE, + InlineKeyboardMarkup, + LinkPreviewOptions, + Message, + MessageEntity, +) +from .base import TelegramMethod + + +class EditMessageText(TelegramMethod[Union[Message, bool]]): + """ + Use this method to edit text and `game `_ messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagetext + """ + + __returning__ = Union[Message, bool] + __api_method__ = "editMessageText" + + text: str + """New text of the message, 1-4096 characters after entities parsing""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message to be edited was sent""" + chat_id: Optional[Union[int, str]] = None + """Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Identifier of the message to edit""" + inline_message_id: Optional[str] = None + """Required if *chat_id* and *message_id* are not specified. Identifier of the inline message""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the message text. See `formatting options `_ for more details.""" + entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode*""" + link_preview_options: Optional[LinkPreviewOptions] = None + """Link preview generation options for the message""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for an `inline keyboard `_.""" + disable_web_page_preview: Optional[Union[bool, Default]] = Field( + Default("link_preview_is_disabled"), json_schema_extra={"deprecated": True} + ) + """Disables link previews for links in this message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + text: str, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[LinkPreviewOptions] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + text=text, + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + reply_markup=reply_markup, + disable_web_page_preview=disable_web_page_preview, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/export_chat_invite_link.py b/env/Lib/site-packages/aiogram/methods/export_chat_invite_link.py new file mode 100644 index 0000000..271e35d --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/export_chat_invite_link.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class ExportChatInviteLink(TelegramMethod[str]): + """ + Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as *String* on success. + + Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` or by calling the :class:`aiogram.methods.get_chat.GetChat` method. If your bot needs to generate a new primary invite link replacing its previous one, use :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` again. + + Source: https://core.telegram.org/bots/api#exportchatinvitelink + """ + + __returning__ = str + __api_method__ = "exportChatInviteLink" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/forward_message.py b/env/Lib/site-packages/aiogram/methods/forward_message.py new file mode 100644 index 0000000..01d764a --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/forward_message.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..client.default import Default +from ..types import Message +from ..types.base import UNSET_PROTECT_CONTENT +from .base import TelegramMethod + + +class ForwardMessage(TelegramMethod[Message]): + """ + Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#forwardmessage + """ + + __returning__ = Message + __api_method__ = "forwardMessage" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + from_chat_id: Union[int, str] + """Unique identifier for the chat where the original message was sent (or channel username in the format :code:`@channelusername`)""" + message_id: int + """Message identifier in the chat specified in *from_chat_id*""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the forwarded message from forwarding and saving""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_id: int, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + from_chat_id=from_chat_id, + message_id=message_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/forward_messages.py b/env/Lib/site-packages/aiogram/methods/forward_messages.py new file mode 100644 index 0000000..829545f --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/forward_messages.py @@ -0,0 +1,57 @@ +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..types import MessageId +from .base import TelegramMethod + + +class ForwardMessages(TelegramMethod[List[MessageId]]): + """ + Use this method to forward multiple messages of any kind. If some of the specified messages can't be found or forwarded, they are skipped. Service messages and messages with protected content can't be forwarded. Album grouping is kept for forwarded messages. On success, an array of :class:`aiogram.types.message_id.MessageId` of the sent messages is returned. + + Source: https://core.telegram.org/bots/api#forwardmessages + """ + + __returning__ = List[MessageId] + __api_method__ = "forwardMessages" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + from_chat_id: Union[int, str] + """Unique identifier for the chat where the original messages were sent (or channel username in the format :code:`@channelusername`)""" + message_ids: List[int] + """A JSON-serialized list of 1-100 identifiers of messages in the chat *from_chat_id* to forward. The identifiers must be specified in a strictly increasing order.""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + disable_notification: Optional[bool] = None + """Sends the messages `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[bool] = None + """Protects the contents of the forwarded messages from forwarding and saving""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + from_chat_id: Union[int, str], + message_ids: List[int], + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + from_chat_id=from_chat_id, + message_ids=message_ids, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/get_business_connection.py b/env/Lib/site-packages/aiogram/methods/get_business_connection.py new file mode 100644 index 0000000..97cb9ca --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_business_connection.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from aiogram.types import BusinessConnection + +from .base import TelegramMethod + + +class GetBusinessConnection(TelegramMethod[BusinessConnection]): + """ + Use this method to get information about the connection of the bot with a business account. Returns a :class:`aiogram.types.business_connection.BusinessConnection` object on success. + + Source: https://core.telegram.org/bots/api#getbusinessconnection + """ + + __returning__ = BusinessConnection + __api_method__ = "getBusinessConnection" + + business_connection_id: str + """Unique identifier of the business connection""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, business_connection_id: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(business_connection_id=business_connection_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_chat.py b/env/Lib/site-packages/aiogram/methods/get_chat.py new file mode 100644 index 0000000..6b6b977 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_chat.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from ..types import ChatFullInfo +from .base import TelegramMethod + + +class GetChat(TelegramMethod[ChatFullInfo]): + """ + Use this method to get up-to-date information about the chat. Returns a :class:`aiogram.types.chat_full_info.ChatFullInfo` object on success. + + Source: https://core.telegram.org/bots/api#getchat + """ + + __returning__ = ChatFullInfo + __api_method__ = "getChat" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_chat_administrators.py b/env/Lib/site-packages/aiogram/methods/get_chat_administrators.py new file mode 100644 index 0000000..99e403e --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_chat_administrators.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Union + +from ..types import ( + ChatMemberAdministrator, + ChatMemberBanned, + ChatMemberLeft, + ChatMemberMember, + ChatMemberOwner, + ChatMemberRestricted, +) +from .base import TelegramMethod + + +class GetChatAdministrators( + TelegramMethod[ + List[ + Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ] + ] + ] +): + """ + Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of :class:`aiogram.types.chat_member.ChatMember` objects. + + Source: https://core.telegram.org/bots/api#getchatadministrators + """ + + __returning__ = List[ + Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ] + ] + __api_method__ = "getChatAdministrators" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_chat_member.py b/env/Lib/site-packages/aiogram/methods/get_chat_member.py new file mode 100644 index 0000000..495f628 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_chat_member.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from ..types import ( + ChatMemberAdministrator, + ChatMemberBanned, + ChatMemberLeft, + ChatMemberMember, + ChatMemberOwner, + ChatMemberRestricted, +) +from .base import TelegramMethod + + +class GetChatMember( + TelegramMethod[ + Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ] + ] +): + """ + Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a :class:`aiogram.types.chat_member.ChatMember` object on success. + + Source: https://core.telegram.org/bots/api#getchatmember + """ + + __returning__ = Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ] + __api_method__ = "getChatMember" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`)""" + user_id: int + """Unique identifier of the target user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], user_id: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, user_id=user_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_chat_member_count.py b/env/Lib/site-packages/aiogram/methods/get_chat_member_count.py new file mode 100644 index 0000000..fc33c23 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_chat_member_count.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class GetChatMemberCount(TelegramMethod[int]): + """ + Use this method to get the number of members in a chat. Returns *Int* on success. + + Source: https://core.telegram.org/bots/api#getchatmembercount + """ + + __returning__ = int + __api_method__ = "getChatMemberCount" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_chat_menu_button.py b/env/Lib/site-packages/aiogram/methods/get_chat_menu_button.py new file mode 100644 index 0000000..ee1248d --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_chat_menu_button.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import MenuButtonCommands, MenuButtonDefault, MenuButtonWebApp +from .base import TelegramMethod + + +class GetChatMenuButton( + TelegramMethod[Union[MenuButtonDefault, MenuButtonWebApp, MenuButtonCommands]] +): + """ + Use this method to get the current value of the bot's menu button in a private chat, or the default menu button. Returns :class:`aiogram.types.menu_button.MenuButton` on success. + + Source: https://core.telegram.org/bots/api#getchatmenubutton + """ + + __returning__ = Union[MenuButtonDefault, MenuButtonWebApp, MenuButtonCommands] + __api_method__ = "getChatMenuButton" + + chat_id: Optional[int] = None + """Unique identifier for the target private chat. If not specified, default bot's menu button will be returned""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Optional[int] = None, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_custom_emoji_stickers.py b/env/Lib/site-packages/aiogram/methods/get_custom_emoji_stickers.py new file mode 100644 index 0000000..3235d97 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_custom_emoji_stickers.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from ..types import Sticker +from .base import TelegramMethod + + +class GetCustomEmojiStickers(TelegramMethod[List[Sticker]]): + """ + Use this method to get information about custom emoji stickers by their identifiers. Returns an Array of :class:`aiogram.types.sticker.Sticker` objects. + + Source: https://core.telegram.org/bots/api#getcustomemojistickers + """ + + __returning__ = List[Sticker] + __api_method__ = "getCustomEmojiStickers" + + custom_emoji_ids: List[str] + """A JSON-serialized list of custom emoji identifiers. At most 200 custom emoji identifiers can be specified.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, custom_emoji_ids: List[str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(custom_emoji_ids=custom_emoji_ids, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_file.py b/env/Lib/site-packages/aiogram/methods/get_file.py new file mode 100644 index 0000000..c96ff31 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_file.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ..types import File +from .base import TelegramMethod + + +class GetFile(TelegramMethod[File]): + """ + Use this method to get basic information about a file and prepare it for downloading. For the moment, bots can download files of up to 20MB in size. On success, a :class:`aiogram.types.file.File` object is returned. The file can then be downloaded via the link :code:`https://api.telegram.org/file/bot/`, where :code:`` is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling :class:`aiogram.methods.get_file.GetFile` again. + **Note:** This function may not preserve the original file name and MIME type. You should save the file's MIME type and name (if available) when the File object is received. + + Source: https://core.telegram.org/bots/api#getfile + """ + + __returning__ = File + __api_method__ = "getFile" + + file_id: str + """File identifier to get information about""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, file_id: str, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(file_id=file_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_forum_topic_icon_stickers.py b/env/Lib/site-packages/aiogram/methods/get_forum_topic_icon_stickers.py new file mode 100644 index 0000000..5c23321 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_forum_topic_icon_stickers.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from typing import List + +from ..types import Sticker +from .base import TelegramMethod + + +class GetForumTopicIconStickers(TelegramMethod[List[Sticker]]): + """ + Use this method to get custom emoji stickers, which can be used as a forum topic icon by any user. Requires no parameters. Returns an Array of :class:`aiogram.types.sticker.Sticker` objects. + + Source: https://core.telegram.org/bots/api#getforumtopiciconstickers + """ + + __returning__ = List[Sticker] + __api_method__ = "getForumTopicIconStickers" diff --git a/env/Lib/site-packages/aiogram/methods/get_game_high_scores.py b/env/Lib/site-packages/aiogram/methods/get_game_high_scores.py new file mode 100644 index 0000000..cac9d61 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_game_high_scores.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from ..types import GameHighScore +from .base import TelegramMethod + + +class GetGameHighScores(TelegramMethod[List[GameHighScore]]): + """ + Use this method to get data for high score tables. Will return the score of the specified user and several of their neighbors in a game. Returns an Array of :class:`aiogram.types.game_high_score.GameHighScore` objects. + + This method will currently return scores for the target user, plus two of their closest neighbors on each side. Will also return the top three users if the user and their neighbors are not among them. Please note that this behavior is subject to change. + + Source: https://core.telegram.org/bots/api#getgamehighscores + """ + + __returning__ = List[GameHighScore] + __api_method__ = "getGameHighScores" + + user_id: int + """Target user id""" + chat_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Unique identifier for the target chat""" + message_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Identifier of the sent message""" + inline_message_id: Optional[str] = None + """Required if *chat_id* and *message_id* are not specified. Identifier of the inline message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + chat_id: Optional[int] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + user_id=user_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/get_me.py b/env/Lib/site-packages/aiogram/methods/get_me.py new file mode 100644 index 0000000..c2cc52f --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_me.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from ..types import User +from .base import TelegramMethod + + +class GetMe(TelegramMethod[User]): + """ + A simple method for testing your bot's authentication token. Requires no parameters. Returns basic information about the bot in form of a :class:`aiogram.types.user.User` object. + + Source: https://core.telegram.org/bots/api#getme + """ + + __returning__ = User + __api_method__ = "getMe" diff --git a/env/Lib/site-packages/aiogram/methods/get_my_commands.py b/env/Lib/site-packages/aiogram/methods/get_my_commands.py new file mode 100644 index 0000000..b3386b6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_my_commands.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..types import ( + BotCommand, + BotCommandScopeAllChatAdministrators, + BotCommandScopeAllGroupChats, + BotCommandScopeAllPrivateChats, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + BotCommandScopeDefault, +) +from .base import TelegramMethod + + +class GetMyCommands(TelegramMethod[List[BotCommand]]): + """ + Use this method to get the current list of the bot's commands for the given scope and user language. Returns an Array of :class:`aiogram.types.bot_command.BotCommand` objects. If commands aren't set, an empty list is returned. + + Source: https://core.telegram.org/bots/api#getmycommands + """ + + __returning__ = List[BotCommand] + __api_method__ = "getMyCommands" + + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None + """A JSON-serialized object, describing scope of users. Defaults to :class:`aiogram.types.bot_command_scope_default.BotCommandScopeDefault`.""" + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code or an empty string""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None, + language_code: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(scope=scope, language_code=language_code, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_my_default_administrator_rights.py b/env/Lib/site-packages/aiogram/methods/get_my_default_administrator_rights.py new file mode 100644 index 0000000..4f9ad9a --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_my_default_administrator_rights.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..types import ChatAdministratorRights +from .base import TelegramMethod + + +class GetMyDefaultAdministratorRights(TelegramMethod[ChatAdministratorRights]): + """ + Use this method to get the current default administrator rights of the bot. Returns :class:`aiogram.types.chat_administrator_rights.ChatAdministratorRights` on success. + + Source: https://core.telegram.org/bots/api#getmydefaultadministratorrights + """ + + __returning__ = ChatAdministratorRights + __api_method__ = "getMyDefaultAdministratorRights" + + for_channels: Optional[bool] = None + """Pass :code:`True` to get default administrator rights of the bot in channels. Otherwise, default administrator rights of the bot for groups and supergroups will be returned.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, for_channels: Optional[bool] = None, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(for_channels=for_channels, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_my_description.py b/env/Lib/site-packages/aiogram/methods/get_my_description.py new file mode 100644 index 0000000..f967faf --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_my_description.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..types import BotDescription +from .base import TelegramMethod + + +class GetMyDescription(TelegramMethod[BotDescription]): + """ + Use this method to get the current bot description for the given user language. Returns :class:`aiogram.types.bot_description.BotDescription` on success. + + Source: https://core.telegram.org/bots/api#getmydescription + """ + + __returning__ = BotDescription + __api_method__ = "getMyDescription" + + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code or an empty string""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, language_code: Optional[str] = None, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(language_code=language_code, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_my_name.py b/env/Lib/site-packages/aiogram/methods/get_my_name.py new file mode 100644 index 0000000..909ac3f --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_my_name.py @@ -0,0 +1,31 @@ +from typing import TYPE_CHECKING, Any, Optional + +from ..types import BotName +from .base import TelegramMethod + + +class GetMyName(TelegramMethod[BotName]): + """ + Use this method to get the current bot name for the given user language. Returns :class:`aiogram.types.bot_name.BotName` on success. + + Source: https://core.telegram.org/bots/api#getmyname + """ + + __returning__ = BotName + __api_method__ = "getMyName" + + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code or an empty string""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, language_code: Optional[str] = None, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(language_code=language_code, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_my_short_description.py b/env/Lib/site-packages/aiogram/methods/get_my_short_description.py new file mode 100644 index 0000000..a9a5666 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_my_short_description.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..types import BotShortDescription +from .base import TelegramMethod + + +class GetMyShortDescription(TelegramMethod[BotShortDescription]): + """ + Use this method to get the current bot short description for the given user language. Returns :class:`aiogram.types.bot_short_description.BotShortDescription` on success. + + Source: https://core.telegram.org/bots/api#getmyshortdescription + """ + + __returning__ = BotShortDescription + __api_method__ = "getMyShortDescription" + + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code or an empty string""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, language_code: Optional[str] = None, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(language_code=language_code, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_star_transactions.py b/env/Lib/site-packages/aiogram/methods/get_star_transactions.py new file mode 100644 index 0000000..ee0ea2e --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_star_transactions.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..types import StarTransactions +from .base import TelegramMethod + + +class GetStarTransactions(TelegramMethod[StarTransactions]): + """ + Returns the bot's Telegram Star transactions in chronological order. On success, returns a :class:`aiogram.types.star_transactions.StarTransactions` object. + + Source: https://core.telegram.org/bots/api#getstartransactions + """ + + __returning__ = StarTransactions + __api_method__ = "getStarTransactions" + + offset: Optional[int] = None + """Number of transactions to skip in the response""" + limit: Optional[int] = None + """The maximum number of transactions to be retrieved. Values between 1-100 are accepted. Defaults to 100.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + offset: Optional[int] = None, + limit: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(offset=offset, limit=limit, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_sticker_set.py b/env/Lib/site-packages/aiogram/methods/get_sticker_set.py new file mode 100644 index 0000000..2700e17 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_sticker_set.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ..types import StickerSet +from .base import TelegramMethod + + +class GetStickerSet(TelegramMethod[StickerSet]): + """ + Use this method to get a sticker set. On success, a :class:`aiogram.types.sticker_set.StickerSet` object is returned. + + Source: https://core.telegram.org/bots/api#getstickerset + """ + + __returning__ = StickerSet + __api_method__ = "getStickerSet" + + name: str + """Name of the sticker set""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, name: str, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(name=name, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_updates.py b/env/Lib/site-packages/aiogram/methods/get_updates.py new file mode 100644 index 0000000..d1f6371 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_updates.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from ..types import Update +from .base import TelegramMethod + + +class GetUpdates(TelegramMethod[List[Update]]): + """ + Use this method to receive incoming updates using long polling (`wiki `_). Returns an Array of :class:`aiogram.types.update.Update` objects. + + **Notes** + + **1.** This method will not work if an outgoing webhook is set up. + + **2.** In order to avoid getting duplicate updates, recalculate *offset* after each server response. + + Source: https://core.telegram.org/bots/api#getupdates + """ + + __returning__ = List[Update] + __api_method__ = "getUpdates" + + offset: Optional[int] = None + """Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as :class:`aiogram.methods.get_updates.GetUpdates` is called with an *offset* higher than its *update_id*. The negative offset can be specified to retrieve updates starting from *-offset* update from the end of the updates queue. All previous updates will be forgotten.""" + limit: Optional[int] = None + """Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100.""" + timeout: Optional[int] = None + """Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Should be positive, short polling should be used for testing purposes only.""" + allowed_updates: Optional[List[str]] = None + """A JSON-serialized list of the update types you want your bot to receive. For example, specify :code:`["message", "edited_channel_post", "callback_query"]` to only receive updates of these types. See :class:`aiogram.types.update.Update` for a complete list of available update types. Specify an empty list to receive all update types except *chat_member*, *message_reaction*, and *message_reaction_count* (default). If not specified, the previous setting will be used.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + offset: Optional[int] = None, + limit: Optional[int] = None, + timeout: Optional[int] = None, + allowed_updates: Optional[List[str]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + offset=offset, + limit=limit, + timeout=timeout, + allowed_updates=allowed_updates, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/get_user_chat_boosts.py b/env/Lib/site-packages/aiogram/methods/get_user_chat_boosts.py new file mode 100644 index 0000000..f3eae26 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_user_chat_boosts.py @@ -0,0 +1,33 @@ +from typing import TYPE_CHECKING, Any, Union + +from ..types import UserChatBoosts +from .base import TelegramMethod + + +class GetUserChatBoosts(TelegramMethod[UserChatBoosts]): + """ + Use this method to get the list of boosts added to a chat by a user. Requires administrator rights in the chat. Returns a :class:`aiogram.types.user_chat_boosts.UserChatBoosts` object. + + Source: https://core.telegram.org/bots/api#getuserchatboosts + """ + + __returning__ = UserChatBoosts + __api_method__ = "getUserChatBoosts" + + chat_id: Union[int, str] + """Unique identifier for the chat or username of the channel (in the format :code:`@channelusername`)""" + user_id: int + """Unique identifier of the target user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], user_id: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, user_id=user_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_user_profile_photos.py b/env/Lib/site-packages/aiogram/methods/get_user_profile_photos.py new file mode 100644 index 0000000..488885e --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_user_profile_photos.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..types import UserProfilePhotos +from .base import TelegramMethod + + +class GetUserProfilePhotos(TelegramMethod[UserProfilePhotos]): + """ + Use this method to get a list of profile pictures for a user. Returns a :class:`aiogram.types.user_profile_photos.UserProfilePhotos` object. + + Source: https://core.telegram.org/bots/api#getuserprofilephotos + """ + + __returning__ = UserProfilePhotos + __api_method__ = "getUserProfilePhotos" + + user_id: int + """Unique identifier of the target user""" + offset: Optional[int] = None + """Sequential number of the first photo to be returned. By default, all photos are returned.""" + limit: Optional[int] = None + """Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + offset: Optional[int] = None, + limit: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(user_id=user_id, offset=offset, limit=limit, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/get_webhook_info.py b/env/Lib/site-packages/aiogram/methods/get_webhook_info.py new file mode 100644 index 0000000..c9f0e46 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/get_webhook_info.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from ..types import WebhookInfo +from .base import TelegramMethod + + +class GetWebhookInfo(TelegramMethod[WebhookInfo]): + """ + Use this method to get current webhook status. Requires no parameters. On success, returns a :class:`aiogram.types.webhook_info.WebhookInfo` object. If the bot is using :class:`aiogram.methods.get_updates.GetUpdates`, will return an object with the *url* field empty. + + Source: https://core.telegram.org/bots/api#getwebhookinfo + """ + + __returning__ = WebhookInfo + __api_method__ = "getWebhookInfo" diff --git a/env/Lib/site-packages/aiogram/methods/hide_general_forum_topic.py b/env/Lib/site-packages/aiogram/methods/hide_general_forum_topic.py new file mode 100644 index 0000000..a3b6ee3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/hide_general_forum_topic.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class HideGeneralForumTopic(TelegramMethod[bool]): + """ + Use this method to hide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. The topic will be automatically closed if it was open. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#hidegeneralforumtopic + """ + + __returning__ = bool + __api_method__ = "hideGeneralForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/leave_chat.py b/env/Lib/site-packages/aiogram/methods/leave_chat.py new file mode 100644 index 0000000..f9d4312 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/leave_chat.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class LeaveChat(TelegramMethod[bool]): + """ + Use this method for your bot to leave a group, supergroup or channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#leavechat + """ + + __returning__ = bool + __api_method__ = "leaveChat" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup or channel (in the format :code:`@channelusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/log_out.py b/env/Lib/site-packages/aiogram/methods/log_out.py new file mode 100644 index 0000000..2a62653 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/log_out.py @@ -0,0 +1,14 @@ +from __future__ import annotations + +from .base import TelegramMethod + + +class LogOut(TelegramMethod[bool]): + """ + Use this method to log out from the cloud Bot API server before launching the bot locally. You **must** log out the bot before running it locally, otherwise there is no guarantee that the bot will receive updates. After a successful call, you can immediately log in on a local server, but will not be able to log in back to the cloud Bot API server for 10 minutes. Returns :code:`True` on success. Requires no parameters. + + Source: https://core.telegram.org/bots/api#logout + """ + + __returning__ = bool + __api_method__ = "logOut" diff --git a/env/Lib/site-packages/aiogram/methods/pin_chat_message.py b/env/Lib/site-packages/aiogram/methods/pin_chat_message.py new file mode 100644 index 0000000..47c28f1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/pin_chat_message.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramMethod + + +class PinChatMessage(TelegramMethod[bool]): + """ + Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#pinchatmessage + """ + + __returning__ = bool + __api_method__ = "pinChatMessage" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: int + """Identifier of a message to pin""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be pinned""" + disable_notification: Optional[bool] = None + """Pass :code:`True` if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_id: int, + business_connection_id: Optional[str] = None, + disable_notification: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + message_id=message_id, + business_connection_id=business_connection_id, + disable_notification=disable_notification, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/promote_chat_member.py b/env/Lib/site-packages/aiogram/methods/promote_chat_member.py new file mode 100644 index 0000000..2ca410f --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/promote_chat_member.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramMethod + + +class PromoteChatMember(TelegramMethod[bool]): + """ + Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass :code:`False` for all boolean parameters to demote a user. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#promotechatmember + """ + + __returning__ = bool + __api_method__ = "promoteChatMember" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + user_id: int + """Unique identifier of the target user""" + is_anonymous: Optional[bool] = None + """Pass :code:`True` if the administrator's presence in the chat is hidden""" + can_manage_chat: Optional[bool] = None + """Pass :code:`True` if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages and ignore slow mode. Implied by any other administrator privilege.""" + can_delete_messages: Optional[bool] = None + """Pass :code:`True` if the administrator can delete messages of other users""" + can_manage_video_chats: Optional[bool] = None + """Pass :code:`True` if the administrator can manage video chats""" + can_restrict_members: Optional[bool] = None + """Pass :code:`True` if the administrator can restrict, ban or unban chat members, or access supergroup statistics""" + can_promote_members: Optional[bool] = None + """Pass :code:`True` if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him)""" + can_change_info: Optional[bool] = None + """Pass :code:`True` if the administrator can change chat title, photo and other settings""" + can_invite_users: Optional[bool] = None + """Pass :code:`True` if the administrator can invite new users to the chat""" + can_post_stories: Optional[bool] = None + """Pass :code:`True` if the administrator can post stories to the chat""" + can_edit_stories: Optional[bool] = None + """Pass :code:`True` if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive""" + can_delete_stories: Optional[bool] = None + """Pass :code:`True` if the administrator can delete stories posted by other users""" + can_post_messages: Optional[bool] = None + """Pass :code:`True` if the administrator can post messages in the channel, or access channel statistics; for channels only""" + can_edit_messages: Optional[bool] = None + """Pass :code:`True` if the administrator can edit messages of other users and can pin messages; for channels only""" + can_pin_messages: Optional[bool] = None + """Pass :code:`True` if the administrator can pin messages; for supergroups only""" + can_manage_topics: Optional[bool] = None + """Pass :code:`True` if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + user_id: int, + is_anonymous: Optional[bool] = None, + can_manage_chat: Optional[bool] = None, + can_delete_messages: Optional[bool] = None, + can_manage_video_chats: Optional[bool] = None, + can_restrict_members: Optional[bool] = None, + can_promote_members: Optional[bool] = None, + can_change_info: Optional[bool] = None, + can_invite_users: Optional[bool] = None, + can_post_stories: Optional[bool] = None, + can_edit_stories: Optional[bool] = None, + can_delete_stories: Optional[bool] = None, + can_post_messages: Optional[bool] = None, + can_edit_messages: Optional[bool] = None, + can_pin_messages: Optional[bool] = None, + can_manage_topics: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + user_id=user_id, + is_anonymous=is_anonymous, + can_manage_chat=can_manage_chat, + can_delete_messages=can_delete_messages, + can_manage_video_chats=can_manage_video_chats, + can_restrict_members=can_restrict_members, + can_promote_members=can_promote_members, + can_change_info=can_change_info, + can_invite_users=can_invite_users, + can_post_stories=can_post_stories, + can_edit_stories=can_edit_stories, + can_delete_stories=can_delete_stories, + can_post_messages=can_post_messages, + can_edit_messages=can_edit_messages, + can_pin_messages=can_pin_messages, + can_manage_topics=can_manage_topics, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/refund_star_payment.py b/env/Lib/site-packages/aiogram/methods/refund_star_payment.py new file mode 100644 index 0000000..495cc9e --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/refund_star_payment.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramMethod + + +class RefundStarPayment(TelegramMethod[bool]): + """ + Refunds a successful payment in `Telegram Stars `_. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#refundstarpayment + """ + + __returning__ = bool + __api_method__ = "refundStarPayment" + + user_id: int + """Identifier of the user whose payment will be refunded""" + telegram_payment_charge_id: str + """Telegram payment identifier""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + telegram_payment_charge_id: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + user_id=user_id, + telegram_payment_charge_id=telegram_payment_charge_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/reopen_forum_topic.py b/env/Lib/site-packages/aiogram/methods/reopen_forum_topic.py new file mode 100644 index 0000000..45eb18d --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/reopen_forum_topic.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class ReopenForumTopic(TelegramMethod[bool]): + """ + Use this method to reopen a closed topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights, unless it is the creator of the topic. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#reopenforumtopic + """ + + __returning__ = bool + __api_method__ = "reopenForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + message_thread_id: int + """Unique identifier for the target message thread of the forum topic""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_thread_id: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, message_thread_id=message_thread_id, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/reopen_general_forum_topic.py b/env/Lib/site-packages/aiogram/methods/reopen_general_forum_topic.py new file mode 100644 index 0000000..a6dc04e --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/reopen_general_forum_topic.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class ReopenGeneralForumTopic(TelegramMethod[bool]): + """ + Use this method to reopen a closed 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. The topic will be automatically unhidden if it was hidden. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#reopengeneralforumtopic + """ + + __returning__ = bool + __api_method__ = "reopenGeneralForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/replace_sticker_in_set.py b/env/Lib/site-packages/aiogram/methods/replace_sticker_in_set.py new file mode 100644 index 0000000..f46eef2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/replace_sticker_in_set.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ..types import InputSticker +from .base import TelegramMethod + + +class ReplaceStickerInSet(TelegramMethod[bool]): + """ + Use this method to replace an existing sticker in a sticker set with a new one. The method is equivalent to calling :class:`aiogram.methods.delete_sticker_from_set.DeleteStickerFromSet`, then :class:`aiogram.methods.add_sticker_to_set.AddStickerToSet`, then :class:`aiogram.methods.set_sticker_position_in_set.SetStickerPositionInSet`. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#replacestickerinset + """ + + __returning__ = bool + __api_method__ = "replaceStickerInSet" + + user_id: int + """User identifier of the sticker set owner""" + name: str + """Sticker set name""" + old_sticker: str + """File identifier of the replaced sticker""" + sticker: InputSticker + """A JSON-serialized object with information about the added sticker. If exactly the same sticker had already been added to the set, then the set remains unchanged.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + name: str, + old_sticker: str, + sticker: InputSticker, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + user_id=user_id, + name=name, + old_sticker=old_sticker, + sticker=sticker, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/restrict_chat_member.py b/env/Lib/site-packages/aiogram/methods/restrict_chat_member.py new file mode 100644 index 0000000..5dfbd01 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/restrict_chat_member.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ChatPermissions +from .base import TelegramMethod + + +class RestrictChatMember(TelegramMethod[bool]): + """ + Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass :code:`True` for all permissions to lift restrictions from a user. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#restrictchatmember + """ + + __returning__ = bool + __api_method__ = "restrictChatMember" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + user_id: int + """Unique identifier of the target user""" + permissions: ChatPermissions + """A JSON-serialized object for new user permissions""" + use_independent_chat_permissions: Optional[bool] = None + """Pass :code:`True` if chat permissions are set independently. Otherwise, the *can_send_other_messages* and *can_add_web_page_previews* permissions will imply the *can_send_messages*, *can_send_audios*, *can_send_documents*, *can_send_photos*, *can_send_videos*, *can_send_video_notes*, and *can_send_voice_notes* permissions; the *can_send_polls* permission will imply the *can_send_messages* permission.""" + until_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None + """Date when restrictions will be lifted for the user; Unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + user_id: int, + permissions: ChatPermissions, + use_independent_chat_permissions: Optional[bool] = None, + until_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + user_id=user_id, + permissions=permissions, + use_independent_chat_permissions=use_independent_chat_permissions, + until_date=until_date, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/revoke_chat_invite_link.py b/env/Lib/site-packages/aiogram/methods/revoke_chat_invite_link.py new file mode 100644 index 0000000..414feb3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/revoke_chat_invite_link.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from ..types import ChatInviteLink +from .base import TelegramMethod + + +class RevokeChatInviteLink(TelegramMethod[ChatInviteLink]): + """ + Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#revokechatinvitelink + """ + + __returning__ = ChatInviteLink + __api_method__ = "revokeChatInviteLink" + + chat_id: Union[int, str] + """Unique identifier of the target chat or username of the target channel (in the format :code:`@channelusername`)""" + invite_link: str + """The invite link to revoke""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + invite_link: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, invite_link=invite_link, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/send_animation.py b/env/Lib/site-packages/aiogram/methods/send_animation.py new file mode 100644 index 0000000..0baab73 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_animation.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputFile, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendAnimation(TelegramMethod[Message]): + """ + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendanimation + """ + + __returning__ = Message + __api_method__ = "sendAnimation" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + animation: Union[InputFile, str] + """Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. :ref:`More information on Sending Files » `""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + duration: Optional[int] = None + """Duration of sent animation in seconds""" + width: Optional[int] = None + """Animation width""" + height: Optional[int] = None + """Animation height""" + thumbnail: Optional[InputFile] = None + """Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + caption: Optional[str] = None + """Animation caption (may also be used when resending animation by *file_id*), 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the animation caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """Pass :code:`True`, if the caption must be shown above the message media""" + has_spoiler: Optional[bool] = None + """Pass :code:`True` if the animation needs to be covered with a spoiler animation""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + animation: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + animation=animation, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_audio.py b/env/Lib/site-packages/aiogram/methods/send_audio.py new file mode 100644 index 0000000..b15824a --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_audio.py @@ -0,0 +1,132 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputFile, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendAudio(TelegramMethod[Message]): + """ + Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + For sending voice messages, use the :class:`aiogram.methods.send_voice.SendVoice` method instead. + + Source: https://core.telegram.org/bots/api#sendaudio + """ + + __returning__ = Message + __api_method__ = "sendAudio" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + audio: Union[InputFile, str] + """Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » `""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + caption: Optional[str] = None + """Audio caption, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the audio caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + duration: Optional[int] = None + """Duration of the audio in seconds""" + performer: Optional[str] = None + """Performer""" + title: Optional[str] = None + """Track name""" + thumbnail: Optional[InputFile] = None + """Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + audio: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + audio=audio, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_chat_action.py b/env/Lib/site-packages/aiogram/methods/send_chat_action.py new file mode 100644 index 0000000..a9f452a --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_chat_action.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramMethod + + +class SendChatAction(TelegramMethod[bool]): + """ + Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns :code:`True` on success. + + Example: The `ImageBot `_ needs some time to process a request and upload the image. Instead of sending a text message along the lines of 'Retrieving image, please wait…', the bot may use :class:`aiogram.methods.send_chat_action.SendChatAction` with *action* = *upload_photo*. The user will see a 'sending photo' status for the bot. + + We only recommend using this method when a response from the bot will take a **noticeable** amount of time to arrive. + + Source: https://core.telegram.org/bots/api#sendchataction + """ + + __returning__ = bool + __api_method__ = "sendChatAction" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + action: str + """Type of action to broadcast. Choose one, depending on what the user is about to receive: *typing* for `text messages `_, *upload_photo* for `photos `_, *record_video* or *upload_video* for `videos `_, *record_voice* or *upload_voice* for `voice notes `_, *upload_document* for `general files `_, *choose_sticker* for `stickers `_, *find_location* for `location data `_, *record_video_note* or *upload_video_note* for `video notes `_.""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the action will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread; for supergroups only""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + action: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + action=action, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_contact.py b/env/Lib/site-packages/aiogram/methods/send_contact.py new file mode 100644 index 0000000..6c14d56 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_contact.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + Message, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendContact(TelegramMethod[Message]): + """ + Use this method to send phone contacts. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendcontact + """ + + __returning__ = Message + __api_method__ = "sendContact" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + phone_number: str + """Contact's phone number""" + first_name: str + """Contact's first name""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + last_name: Optional[str] = None + """Contact's last name""" + vcard: Optional[str] = None + """Additional data about the contact in the form of a `vCard `_, 0-2048 bytes""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + phone_number: str, + first_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + phone_number=phone_number, + first_name=first_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + last_name=last_name, + vcard=vcard, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_dice.py b/env/Lib/site-packages/aiogram/methods/send_dice.py new file mode 100644 index 0000000..42d2bf5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_dice.py @@ -0,0 +1,101 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + Message, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendDice(TelegramMethod[Message]): + """ + Use this method to send an animated emoji that will display a random value. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#senddice + """ + + __returning__ = Message + __api_method__ = "sendDice" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + emoji: Optional[str] = None + """Emoji on which the dice throw animation is based. Currently, must be one of '🎲', '🎯', '🏀', '⚽', '🎳', or '🎰'. Dice can have values 1-6 for '🎲', '🎯' and '🎳', values 1-5 for '🏀' and '⚽', and values 1-64 for '🎰'. Defaults to '🎲'""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_document.py b/env/Lib/site-packages/aiogram/methods/send_document.py new file mode 100644 index 0000000..411165d --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_document.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputFile, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendDocument(TelegramMethod[Message]): + """ + Use this method to send general files. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#senddocument + """ + + __returning__ = Message + __api_method__ = "sendDocument" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + document: Union[InputFile, str] + """File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » `""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + thumbnail: Optional[InputFile] = None + """Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + caption: Optional[str] = None + """Document caption (may also be used when resending documents by *file_id*), 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the document caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + disable_content_type_detection: Optional[bool] = None + """Disables automatic server-side content type detection for files uploaded using multipart/form-data""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + document: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + document=document, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_game.py b/env/Lib/site-packages/aiogram/methods/send_game.py new file mode 100644 index 0000000..eb96330 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_game.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import InlineKeyboardMarkup, Message, ReplyParameters +from .base import TelegramMethod + + +class SendGame(TelegramMethod[Message]): + """ + Use this method to send a game. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendgame + """ + + __returning__ = Message + __api_method__ = "sendGame" + + chat_id: int + """Unique identifier for the target chat""" + game_short_name: str + """Short name of the game, serves as the unique identifier for the game. Set up your games via `@BotFather `_.""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for an `inline keyboard `_. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game.""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: int, + game_short_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + game_short_name=game_short_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_invoice.py b/env/Lib/site-packages/aiogram/methods/send_invoice.py new file mode 100644 index 0000000..108219e --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_invoice.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import InlineKeyboardMarkup, LabeledPrice, Message, ReplyParameters +from .base import TelegramMethod + + +class SendInvoice(TelegramMethod[Message]): + """ + Use this method to send invoices. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendinvoice + """ + + __returning__ = Message + __api_method__ = "sendInvoice" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + title: str + """Product name, 1-32 characters""" + description: str + """Product description, 1-255 characters""" + payload: str + """Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.""" + currency: str + """Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_.""" + prices: List[LabeledPrice] + """Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_.""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + provider_token: Optional[str] = None + """Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_.""" + max_tip_amount: Optional[int] = None + """The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_.""" + suggested_tip_amounts: Optional[List[int]] = None + """A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*.""" + start_parameter: Optional[str] = None + """Unique deep-linking parameter. If left empty, **forwarded copies** of the sent message will have a *Pay* button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a *URL* button with a deep link to the bot (instead of a *Pay* button), with the value used as the start parameter""" + provider_data: Optional[str] = None + """JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider.""" + photo_url: Optional[str] = None + """URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for.""" + photo_size: Optional[int] = None + """Photo size in bytes""" + photo_width: Optional[int] = None + """Photo width""" + photo_height: Optional[int] = None + """Photo height""" + need_name: Optional[bool] = None + """Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_phone_number: Optional[bool] = None + """Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_email: Optional[bool] = None + """Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_shipping_address: Optional[bool] = None + """Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_.""" + send_phone_number_to_provider: Optional[bool] = None + """Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_.""" + send_email_to_provider: Optional[bool] = None + """Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_.""" + is_flexible: Optional[bool] = None + """Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_.""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for an `inline keyboard `_. If empty, one 'Pay :code:`total price`' button will be shown. If not empty, the first button must be a Pay button.""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + message_thread_id: Optional[int] = None, + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + start_parameter: Optional[str] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + message_thread_id=message_thread_id, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + start_parameter=start_parameter, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_location.py b/env/Lib/site-packages/aiogram/methods/send_location.py new file mode 100644 index 0000000..d33f676 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_location.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + Message, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendLocation(TelegramMethod[Message]): + """ + Use this method to send point on the map. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendlocation + """ + + __returning__ = Message + __api_method__ = "sendLocation" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + latitude: float + """Latitude of the location""" + longitude: float + """Longitude of the location""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + horizontal_accuracy: Optional[float] = None + """The radius of uncertainty for the location, measured in meters; 0-1500""" + live_period: Optional[int] = None + """Period in seconds during which the location will be updated (see `Live Locations `_, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely.""" + heading: Optional[int] = None + """For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.""" + proximity_alert_radius: Optional[int] = None + """For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + latitude: float, + longitude: float, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + latitude=latitude, + longitude=longitude, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_media_group.py b/env/Lib/site-packages/aiogram/methods/send_media_group.py new file mode 100644 index 0000000..f8c081a --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_media_group.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputMediaAudio, + InputMediaDocument, + InputMediaPhoto, + InputMediaVideo, + Message, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendMediaGroup(TelegramMethod[List[Message]]): + """ + Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of `Messages `_ that were sent is returned. + + Source: https://core.telegram.org/bots/api#sendmediagroup + """ + + __returning__ = List[Message] + __api_method__ = "sendMediaGroup" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + media: List[Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo]] + """A JSON-serialized array describing messages to be sent, must include 2-10 items""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + disable_notification: Optional[bool] = None + """Sends messages `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent messages from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the messages are a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + media: List[ + Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo] + ], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + media=media, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_message.py b/env/Lib/site-packages/aiogram/methods/send_message.py new file mode 100644 index 0000000..caf2852 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_message.py @@ -0,0 +1,128 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + LinkPreviewOptions, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendMessage(TelegramMethod[Message]): + """ + Use this method to send text messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendmessage + """ + + __returning__ = Message + __api_method__ = "sendMessage" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + text: str + """Text of the message to be sent, 1-4096 characters after entities parsing""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the message text. See `formatting options `_ for more details.""" + entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode*""" + link_preview_options: Optional[Union[LinkPreviewOptions, Default]] = Default("link_preview") + """Link preview generation options for the message""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + disable_web_page_preview: Optional[Union[bool, Default]] = Field( + Default("link_preview_is_disabled"), json_schema_extra={"deprecated": True} + ) + """Disables link previews for links in this message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + text: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[Union[LinkPreviewOptions, Default]] = Default( + "link_preview" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + text=text, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + disable_web_page_preview=disable_web_page_preview, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_paid_media.py b/env/Lib/site-packages/aiogram/methods/send_paid_media.py new file mode 100644 index 0000000..dd847f5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_paid_media.py @@ -0,0 +1,97 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputPaidMediaPhoto, + InputPaidMediaVideo, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendPaidMedia(TelegramMethod[Message]): + """ + Use this method to send paid media. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpaidmedia + """ + + __returning__ = Message + __api_method__ = "sendPaidMedia" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`). If the chat is a channel, all Telegram Star proceeds from this media will be credited to the chat's balance. Otherwise, they will be credited to the bot's balance.""" + star_count: int + """The number of Telegram Stars that must be paid to buy access to the media""" + media: List[Union[InputPaidMediaPhoto, InputPaidMediaVideo]] + """A JSON-serialized array describing the media to be sent; up to 10 items""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + caption: Optional[str] = None + """Media caption, 0-1024 characters after entities parsing""" + parse_mode: Optional[str] = None + """Mode for parsing entities in the media caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[bool] = None + """Pass :code:`True`, if the caption must be shown above the message media""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[bool] = None + """Protects the contents of the sent message from forwarding and saving""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + star_count: int, + media: List[Union[InputPaidMediaPhoto, InputPaidMediaVideo]], + business_connection_id: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[str] = None, + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[bool] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + star_count=star_count, + media=media, + business_connection_id=business_connection_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + disable_notification=disable_notification, + protect_content=protect_content, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_photo.py b/env/Lib/site-packages/aiogram/methods/send_photo.py new file mode 100644 index 0000000..3ba7da1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_photo.py @@ -0,0 +1,125 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputFile, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendPhoto(TelegramMethod[Message]): + """ + Use this method to send photos. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendphoto + """ + + __returning__ = Message + __api_method__ = "sendPhoto" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + photo: Union[InputFile, str] + """Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. :ref:`More information on Sending Files » `""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + caption: Optional[str] = None + """Photo caption (may also be used when resending photos by *file_id*), 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the photo caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """Pass :code:`True`, if the caption must be shown above the message media""" + has_spoiler: Optional[bool] = None + """Pass :code:`True` if the photo needs to be covered with a spoiler animation""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + photo: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + photo=photo, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_poll.py b/env/Lib/site-packages/aiogram/methods/send_poll.py new file mode 100644 index 0000000..e791b70 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_poll.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputPollOption, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendPoll(TelegramMethod[Message]): + """ + Use this method to send a native poll. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpoll + """ + + __returning__ = Message + __api_method__ = "sendPoll" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + question: str + """Poll question, 1-300 characters""" + options: List[Union[InputPollOption, str]] + """A JSON-serialized list of 2-10 answer options""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + question_parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the question. See `formatting options `_ for more details. Currently, only custom emoji entities are allowed""" + question_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of *question_parse_mode*""" + is_anonymous: Optional[bool] = None + """:code:`True`, if the poll needs to be anonymous, defaults to :code:`True`""" + type: Optional[str] = None + """Poll type, 'quiz' or 'regular', defaults to 'regular'""" + allows_multiple_answers: Optional[bool] = None + """:code:`True`, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to :code:`False`""" + correct_option_id: Optional[int] = None + """0-based identifier of the correct answer option, required for polls in quiz mode""" + explanation: Optional[str] = None + """Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing""" + explanation_parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the explanation. See `formatting options `_ for more details.""" + explanation_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of *explanation_parse_mode*""" + open_period: Optional[int] = None + """Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with *close_date*.""" + close_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None + """Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with *open_period*.""" + is_closed: Optional[bool] = None + """Pass :code:`True` if the poll needs to be immediately closed. This can be useful for poll preview.""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + question: str, + options: List[Union[InputPollOption, str]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + question_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + question_entities: Optional[List[MessageEntity]] = None, + is_anonymous: Optional[bool] = None, + type: Optional[str] = None, + allows_multiple_answers: Optional[bool] = None, + correct_option_id: Optional[int] = None, + explanation: Optional[str] = None, + explanation_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + explanation_entities: Optional[List[MessageEntity]] = None, + open_period: Optional[int] = None, + close_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + is_closed: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + question=question, + options=options, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + question_parse_mode=question_parse_mode, + question_entities=question_entities, + is_anonymous=is_anonymous, + type=type, + allows_multiple_answers=allows_multiple_answers, + correct_option_id=correct_option_id, + explanation=explanation, + explanation_parse_mode=explanation_parse_mode, + explanation_entities=explanation_entities, + open_period=open_period, + close_date=close_date, + is_closed=is_closed, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_sticker.py b/env/Lib/site-packages/aiogram/methods/send_sticker.py new file mode 100644 index 0000000..236792b --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_sticker.py @@ -0,0 +1,106 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputFile, + Message, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendSticker(TelegramMethod[Message]): + """ + Use this method to send static .WEBP, `animated `_ .TGS, or `video `_ .WEBM stickers. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendsticker + """ + + __returning__ = Message + __api_method__ = "sendSticker" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + sticker: Union[InputFile, str] + """Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. :ref:`More information on Sending Files » `. Video and animated stickers can't be sent via an HTTP URL.""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + emoji: Optional[str] = None + """Emoji associated with the sticker; only for just uploaded stickers""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + sticker: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + sticker=sticker, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_venue.py b/env/Lib/site-packages/aiogram/methods/send_venue.py new file mode 100644 index 0000000..04ebcee --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_venue.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + Message, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendVenue(TelegramMethod[Message]): + """ + Use this method to send information about a venue. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvenue + """ + + __returning__ = Message + __api_method__ = "sendVenue" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + latitude: float + """Latitude of the venue""" + longitude: float + """Longitude of the venue""" + title: str + """Name of the venue""" + address: str + """Address of the venue""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + foursquare_id: Optional[str] = None + """Foursquare identifier of the venue""" + foursquare_type: Optional[str] = None + """Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.)""" + google_place_id: Optional[str] = None + """Google Places identifier of the venue""" + google_place_type: Optional[str] = None + """Google Places type of the venue. (See `supported types `_.)""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + latitude: float, + longitude: float, + title: str, + address: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + latitude=latitude, + longitude=longitude, + title=title, + address=address, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_video.py b/env/Lib/site-packages/aiogram/methods/send_video.py new file mode 100644 index 0000000..33fb7aa --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_video.py @@ -0,0 +1,145 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputFile, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendVideo(TelegramMethod[Message]): + """ + Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvideo + """ + + __returning__ = Message + __api_method__ = "sendVideo" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + video: Union[InputFile, str] + """Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. :ref:`More information on Sending Files » `""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + duration: Optional[int] = None + """Duration of sent video in seconds""" + width: Optional[int] = None + """Video width""" + height: Optional[int] = None + """Video height""" + thumbnail: Optional[InputFile] = None + """Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + caption: Optional[str] = None + """Video caption (may also be used when resending videos by *file_id*), 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the video caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """Pass :code:`True`, if the caption must be shown above the message media""" + has_spoiler: Optional[bool] = None + """Pass :code:`True` if the video needs to be covered with a spoiler animation""" + supports_streaming: Optional[bool] = None + """Pass :code:`True` if the uploaded video is suitable for streaming""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + video: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + supports_streaming: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + video=video, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + supports_streaming=supports_streaming, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_video_note.py b/env/Lib/site-packages/aiogram/methods/send_video_note.py new file mode 100644 index 0000000..43d685b --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_video_note.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputFile, + Message, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendVideoNote(TelegramMethod[Message]): + """ + As of `v.4.0 `_, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvideonote + """ + + __returning__ = Message + __api_method__ = "sendVideoNote" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + video_note: Union[InputFile, str] + """Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. :ref:`More information on Sending Files » `. Sending video notes by a URL is currently unsupported""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + duration: Optional[int] = None + """Duration of sent video in seconds""" + length: Optional[int] = None + """Video width and height, i.e. diameter of the video message""" + thumbnail: Optional[InputFile] = None + """Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + video_note: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + length: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + video_note=video_note, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + length=length, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/send_voice.py b/env/Lib/site-packages/aiogram/methods/send_voice.py new file mode 100644 index 0000000..ccb27d3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/send_voice.py @@ -0,0 +1,119 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from ..types import ( + ForceReply, + InlineKeyboardMarkup, + InputFile, + Message, + MessageEntity, + ReplyKeyboardMarkup, + ReplyKeyboardRemove, + ReplyParameters, +) +from .base import TelegramMethod + + +class SendVoice(TelegramMethod[Message]): + """ + Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as :class:`aiogram.types.audio.Audio` or :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvoice + """ + + __returning__ = Message + __api_method__ = "sendVoice" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + voice: Union[InputFile, str] + """Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » `""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be sent""" + message_thread_id: Optional[int] = None + """Unique identifier for the target message thread (topic) of the forum; for forum supergroups only""" + caption: Optional[str] = None + """Voice message caption, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """Mode for parsing entities in the voice message caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + duration: Optional[int] = None + """Duration of the voice message in seconds""" + disable_notification: Optional[bool] = None + """Sends the message `silently `_. Users will receive a notification with no sound.""" + protect_content: Optional[Union[bool, Default]] = Default("protect_content") + """Protects the contents of the sent message from forwarding and saving""" + message_effect_id: Optional[str] = None + """Unique identifier of the message effect to be added to the message; for private chats only""" + reply_parameters: Optional[ReplyParameters] = None + """Description of the message to reply to""" + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None + """Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user""" + allow_sending_without_reply: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + reply_to_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """If the message is a reply, ID of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + voice: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + voice=voice, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_chat_administrator_custom_title.py b/env/Lib/site-packages/aiogram/methods/set_chat_administrator_custom_title.py new file mode 100644 index 0000000..a7953c1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_chat_administrator_custom_title.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class SetChatAdministratorCustomTitle(TelegramMethod[bool]): + """ + Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatadministratorcustomtitle + """ + + __returning__ = bool + __api_method__ = "setChatAdministratorCustomTitle" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + user_id: int + """Unique identifier of the target user""" + custom_title: str + """New custom title for the administrator; 0-16 characters, emoji are not allowed""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + user_id: int, + custom_title: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, user_id=user_id, custom_title=custom_title, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_chat_description.py b/env/Lib/site-packages/aiogram/methods/set_chat_description.py new file mode 100644 index 0000000..0f8a4a4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_chat_description.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramMethod + + +class SetChatDescription(TelegramMethod[bool]): + """ + Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatdescription + """ + + __returning__ = bool + __api_method__ = "setChatDescription" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + description: Optional[str] = None + """New chat description, 0-255 characters""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + description: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, description=description, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_chat_menu_button.py b/env/Lib/site-packages/aiogram/methods/set_chat_menu_button.py new file mode 100644 index 0000000..97515d5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_chat_menu_button.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import MenuButtonCommands, MenuButtonDefault, MenuButtonWebApp +from .base import TelegramMethod + + +class SetChatMenuButton(TelegramMethod[bool]): + """ + Use this method to change the bot's menu button in a private chat, or the default menu button. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatmenubutton + """ + + __returning__ = bool + __api_method__ = "setChatMenuButton" + + chat_id: Optional[int] = None + """Unique identifier for the target private chat. If not specified, default bot's menu button will be changed""" + menu_button: Optional[Union[MenuButtonCommands, MenuButtonWebApp, MenuButtonDefault]] = None + """A JSON-serialized object for the bot's new menu button. Defaults to :class:`aiogram.types.menu_button_default.MenuButtonDefault`""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Optional[int] = None, + menu_button: Optional[ + Union[MenuButtonCommands, MenuButtonWebApp, MenuButtonDefault] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, menu_button=menu_button, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_chat_permissions.py b/env/Lib/site-packages/aiogram/methods/set_chat_permissions.py new file mode 100644 index 0000000..232af08 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_chat_permissions.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import ChatPermissions +from .base import TelegramMethod + + +class SetChatPermissions(TelegramMethod[bool]): + """ + Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the *can_restrict_members* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatpermissions + """ + + __returning__ = bool + __api_method__ = "setChatPermissions" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + permissions: ChatPermissions + """A JSON-serialized object for new default chat permissions""" + use_independent_chat_permissions: Optional[bool] = None + """Pass :code:`True` if chat permissions are set independently. Otherwise, the *can_send_other_messages* and *can_add_web_page_previews* permissions will imply the *can_send_messages*, *can_send_audios*, *can_send_documents*, *can_send_photos*, *can_send_videos*, *can_send_video_notes*, and *can_send_voice_notes* permissions; the *can_send_polls* permission will imply the *can_send_messages* permission.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + permissions: ChatPermissions, + use_independent_chat_permissions: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + permissions=permissions, + use_independent_chat_permissions=use_independent_chat_permissions, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_chat_photo.py b/env/Lib/site-packages/aiogram/methods/set_chat_photo.py new file mode 100644 index 0000000..105f8f8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_chat_photo.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from ..types import InputFile +from .base import TelegramMethod + + +class SetChatPhoto(TelegramMethod[bool]): + """ + Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatphoto + """ + + __returning__ = bool + __api_method__ = "setChatPhoto" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + photo: InputFile + """New chat photo, uploaded using multipart/form-data""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + photo: InputFile, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, photo=photo, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_chat_sticker_set.py b/env/Lib/site-packages/aiogram/methods/set_chat_sticker_set.py new file mode 100644 index 0000000..62ed5d1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_chat_sticker_set.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class SetChatStickerSet(TelegramMethod[bool]): + """ + Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field *can_set_sticker_set* optionally returned in :class:`aiogram.methods.get_chat.GetChat` requests to check if the bot can use this method. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatstickerset + """ + + __returning__ = bool + __api_method__ = "setChatStickerSet" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + sticker_set_name: str + """Name of the sticker set to be set as the group sticker set""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + sticker_set_name: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, sticker_set_name=sticker_set_name, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_chat_title.py b/env/Lib/site-packages/aiogram/methods/set_chat_title.py new file mode 100644 index 0000000..04b52e0 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_chat_title.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class SetChatTitle(TelegramMethod[bool]): + """ + Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchattitle + """ + + __returning__ = bool + __api_method__ = "setChatTitle" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + title: str + """New chat title, 1-128 characters""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], title: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, title=title, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_custom_emoji_sticker_set_thumbnail.py b/env/Lib/site-packages/aiogram/methods/set_custom_emoji_sticker_set_thumbnail.py new file mode 100644 index 0000000..47e9c03 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_custom_emoji_sticker_set_thumbnail.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramMethod + + +class SetCustomEmojiStickerSetThumbnail(TelegramMethod[bool]): + """ + Use this method to set the thumbnail of a custom emoji sticker set. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setcustomemojistickersetthumbnail + """ + + __returning__ = bool + __api_method__ = "setCustomEmojiStickerSetThumbnail" + + name: str + """Sticker set name""" + custom_emoji_id: Optional[str] = None + """Custom emoji identifier of a sticker from the sticker set; pass an empty string to drop the thumbnail and use the first sticker as the thumbnail.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + name: str, + custom_emoji_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(name=name, custom_emoji_id=custom_emoji_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_game_score.py b/env/Lib/site-packages/aiogram/methods/set_game_score.py new file mode 100644 index 0000000..38e5374 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_game_score.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import Message +from .base import TelegramMethod + + +class SetGameScore(TelegramMethod[Union[Message, bool]]): + """ + Use this method to set the score of the specified user in a game message. On success, if the message is not an inline message, the :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Returns an error, if the new score is not greater than the user's current score in the chat and *force* is :code:`False`. + + Source: https://core.telegram.org/bots/api#setgamescore + """ + + __returning__ = Union[Message, bool] + __api_method__ = "setGameScore" + + user_id: int + """User identifier""" + score: int + """New score, must be non-negative""" + force: Optional[bool] = None + """Pass :code:`True` if the high score is allowed to decrease. This can be useful when fixing mistakes or banning cheaters""" + disable_edit_message: Optional[bool] = None + """Pass :code:`True` if the game message should not be automatically edited to include the current scoreboard""" + chat_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Unique identifier for the target chat""" + message_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Identifier of the sent message""" + inline_message_id: Optional[str] = None + """Required if *chat_id* and *message_id* are not specified. Identifier of the inline message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + score: int, + force: Optional[bool] = None, + disable_edit_message: Optional[bool] = None, + chat_id: Optional[int] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + user_id=user_id, + score=score, + force=force, + disable_edit_message=disable_edit_message, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_message_reaction.py b/env/Lib/site-packages/aiogram/methods/set_message_reaction.py new file mode 100644 index 0000000..d1c061c --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_message_reaction.py @@ -0,0 +1,53 @@ +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..types import ReactionTypeCustomEmoji, ReactionTypeEmoji, ReactionTypePaid +from .base import TelegramMethod + + +class SetMessageReaction(TelegramMethod[bool]): + """ + Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmessagereaction + """ + + __returning__ = bool + __api_method__ = "setMessageReaction" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: int + """Identifier of the target message. If the message belongs to a media group, the reaction is set to the first non-deleted message in the group instead.""" + reaction: Optional[ + List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + ] = None + """A JSON-serialized list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots.""" + is_big: Optional[bool] = None + """Pass :code:`True` to set the reaction with a big animation""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_id: int, + reaction: Optional[ + List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + ] = None, + is_big: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + message_id=message_id, + reaction=reaction, + is_big=is_big, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_my_commands.py b/env/Lib/site-packages/aiogram/methods/set_my_commands.py new file mode 100644 index 0000000..2e52771 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_my_commands.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..types import ( + BotCommand, + BotCommandScopeAllChatAdministrators, + BotCommandScopeAllGroupChats, + BotCommandScopeAllPrivateChats, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + BotCommandScopeDefault, +) +from .base import TelegramMethod + + +class SetMyCommands(TelegramMethod[bool]): + """ + Use this method to change the list of the bot's commands. See `this manual `_ for more details about bot commands. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmycommands + """ + + __returning__ = bool + __api_method__ = "setMyCommands" + + commands: List[BotCommand] + """A JSON-serialized list of bot commands to be set as the list of the bot's commands. At most 100 commands can be specified.""" + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None + """A JSON-serialized object, describing scope of users for which the commands are relevant. Defaults to :class:`aiogram.types.bot_command_scope_default.BotCommandScopeDefault`.""" + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code. If empty, commands will be applied to all users from the given scope, for whose language there are no dedicated commands""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + commands: List[BotCommand], + scope: Optional[ + Union[ + BotCommandScopeDefault, + BotCommandScopeAllPrivateChats, + BotCommandScopeAllGroupChats, + BotCommandScopeAllChatAdministrators, + BotCommandScopeChat, + BotCommandScopeChatAdministrators, + BotCommandScopeChatMember, + ] + ] = None, + language_code: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + commands=commands, scope=scope, language_code=language_code, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_my_default_administrator_rights.py b/env/Lib/site-packages/aiogram/methods/set_my_default_administrator_rights.py new file mode 100644 index 0000000..02aa7ad --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_my_default_administrator_rights.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..types import ChatAdministratorRights +from .base import TelegramMethod + + +class SetMyDefaultAdministratorRights(TelegramMethod[bool]): + """ + Use this method to change the default administrator rights requested by the bot when it's added as an administrator to groups or channels. These rights will be suggested to users, but they are free to modify the list before adding the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmydefaultadministratorrights + """ + + __returning__ = bool + __api_method__ = "setMyDefaultAdministratorRights" + + rights: Optional[ChatAdministratorRights] = None + """A JSON-serialized object describing new default administrator rights. If not specified, the default administrator rights will be cleared.""" + for_channels: Optional[bool] = None + """Pass :code:`True` to change the default administrator rights of the bot in channels. Otherwise, the default administrator rights of the bot for groups and supergroups will be changed.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + rights: Optional[ChatAdministratorRights] = None, + for_channels: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(rights=rights, for_channels=for_channels, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_my_description.py b/env/Lib/site-packages/aiogram/methods/set_my_description.py new file mode 100644 index 0000000..ee192c8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_my_description.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramMethod + + +class SetMyDescription(TelegramMethod[bool]): + """ + Use this method to change the bot's description, which is shown in the chat with the bot if the chat is empty. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmydescription + """ + + __returning__ = bool + __api_method__ = "setMyDescription" + + description: Optional[str] = None + """New bot description; 0-512 characters. Pass an empty string to remove the dedicated description for the given language.""" + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code. If empty, the description will be applied to all users for whose language there is no dedicated description.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + description: Optional[str] = None, + language_code: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + description=description, language_code=language_code, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_my_name.py b/env/Lib/site-packages/aiogram/methods/set_my_name.py new file mode 100644 index 0000000..3633fdc --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_my_name.py @@ -0,0 +1,36 @@ +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramMethod + + +class SetMyName(TelegramMethod[bool]): + """ + Use this method to change the bot's name. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmyname + """ + + __returning__ = bool + __api_method__ = "setMyName" + + name: Optional[str] = None + """New bot name; 0-64 characters. Pass an empty string to remove the dedicated name for the given language.""" + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code. If empty, the name will be shown to all users for whose language there is no dedicated name.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + name: Optional[str] = None, + language_code: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(name=name, language_code=language_code, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_my_short_description.py b/env/Lib/site-packages/aiogram/methods/set_my_short_description.py new file mode 100644 index 0000000..22fa581 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_my_short_description.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramMethod + + +class SetMyShortDescription(TelegramMethod[bool]): + """ + Use this method to change the bot's short description, which is shown on the bot's profile page and is sent together with the link when users share the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmyshortdescription + """ + + __returning__ = bool + __api_method__ = "setMyShortDescription" + + short_description: Optional[str] = None + """New short description for the bot; 0-120 characters. Pass an empty string to remove the dedicated short description for the given language.""" + language_code: Optional[str] = None + """A two-letter ISO 639-1 language code. If empty, the short description will be applied to all users for whose language there is no dedicated short description.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + short_description: Optional[str] = None, + language_code: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + short_description=short_description, + language_code=language_code, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_passport_data_errors.py b/env/Lib/site-packages/aiogram/methods/set_passport_data_errors.py new file mode 100644 index 0000000..0ad7e8b --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_passport_data_errors.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Union + +from ..types import ( + PassportElementErrorDataField, + PassportElementErrorFile, + PassportElementErrorFiles, + PassportElementErrorFrontSide, + PassportElementErrorReverseSide, + PassportElementErrorSelfie, + PassportElementErrorTranslationFile, + PassportElementErrorTranslationFiles, + PassportElementErrorUnspecified, +) +from .base import TelegramMethod + + +class SetPassportDataErrors(TelegramMethod[bool]): + """ + Informs a user that some of the Telegram Passport elements they provided contains errors. The user will not be able to re-submit their Passport to you until the errors are fixed (the contents of the field for which you returned the error must change). Returns :code:`True` on success. + Use this if the data submitted by the user doesn't satisfy the standards your service requires for any reason. For example, if a birthday date seems invalid, a submitted document is blurry, a scan shows evidence of tampering, etc. Supply some details in the error message to make sure the user knows how to correct the issues. + + Source: https://core.telegram.org/bots/api#setpassportdataerrors + """ + + __returning__ = bool + __api_method__ = "setPassportDataErrors" + + user_id: int + """User identifier""" + errors: List[ + Union[ + PassportElementErrorDataField, + PassportElementErrorFrontSide, + PassportElementErrorReverseSide, + PassportElementErrorSelfie, + PassportElementErrorFile, + PassportElementErrorFiles, + PassportElementErrorTranslationFile, + PassportElementErrorTranslationFiles, + PassportElementErrorUnspecified, + ] + ] + """A JSON-serialized array describing the errors""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + errors: List[ + Union[ + PassportElementErrorDataField, + PassportElementErrorFrontSide, + PassportElementErrorReverseSide, + PassportElementErrorSelfie, + PassportElementErrorFile, + PassportElementErrorFiles, + PassportElementErrorTranslationFile, + PassportElementErrorTranslationFiles, + PassportElementErrorUnspecified, + ] + ], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(user_id=user_id, errors=errors, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_sticker_emoji_list.py b/env/Lib/site-packages/aiogram/methods/set_sticker_emoji_list.py new file mode 100644 index 0000000..ac268c1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_sticker_emoji_list.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramMethod + + +class SetStickerEmojiList(TelegramMethod[bool]): + """ + Use this method to change the list of emoji assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickeremojilist + """ + + __returning__ = bool + __api_method__ = "setStickerEmojiList" + + sticker: str + """File identifier of the sticker""" + emoji_list: List[str] + """A JSON-serialized list of 1-20 emoji associated with the sticker""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, sticker: str, emoji_list: List[str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(sticker=sticker, emoji_list=emoji_list, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_sticker_keywords.py b/env/Lib/site-packages/aiogram/methods/set_sticker_keywords.py new file mode 100644 index 0000000..49e68f8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_sticker_keywords.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramMethod + + +class SetStickerKeywords(TelegramMethod[bool]): + """ + Use this method to change search keywords assigned to a regular or custom emoji sticker. The sticker must belong to a sticker set created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickerkeywords + """ + + __returning__ = bool + __api_method__ = "setStickerKeywords" + + sticker: str + """File identifier of the sticker""" + keywords: Optional[List[str]] = None + """A JSON-serialized list of 0-20 search keywords for the sticker with total length of up to 64 characters""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + sticker: str, + keywords: Optional[List[str]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(sticker=sticker, keywords=keywords, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_sticker_mask_position.py b/env/Lib/site-packages/aiogram/methods/set_sticker_mask_position.py new file mode 100644 index 0000000..617e48b --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_sticker_mask_position.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..types import MaskPosition +from .base import TelegramMethod + + +class SetStickerMaskPosition(TelegramMethod[bool]): + """ + Use this method to change the `mask position `_ of a mask sticker. The sticker must belong to a sticker set that was created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickermaskposition + """ + + __returning__ = bool + __api_method__ = "setStickerMaskPosition" + + sticker: str + """File identifier of the sticker""" + mask_position: Optional[MaskPosition] = None + """A JSON-serialized object with the position where the mask should be placed on faces. Omit the parameter to remove the mask position.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + sticker: str, + mask_position: Optional[MaskPosition] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(sticker=sticker, mask_position=mask_position, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_sticker_position_in_set.py b/env/Lib/site-packages/aiogram/methods/set_sticker_position_in_set.py new file mode 100644 index 0000000..8d30eab --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_sticker_position_in_set.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramMethod + + +class SetStickerPositionInSet(TelegramMethod[bool]): + """ + Use this method to move a sticker in a set created by the bot to a specific position. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickerpositioninset + """ + + __returning__ = bool + __api_method__ = "setStickerPositionInSet" + + sticker: str + """File identifier of the sticker""" + position: int + """New sticker position in the set, zero-based""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, sticker: str, position: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(sticker=sticker, position=position, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_sticker_set_thumbnail.py b/env/Lib/site-packages/aiogram/methods/set_sticker_set_thumbnail.py new file mode 100644 index 0000000..ef83f70 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_sticker_set_thumbnail.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import InputFile +from .base import TelegramMethod + + +class SetStickerSetThumbnail(TelegramMethod[bool]): + """ + Use this method to set the thumbnail of a regular or mask sticker set. The format of the thumbnail file must match the format of the stickers in the set. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickersetthumbnail + """ + + __returning__ = bool + __api_method__ = "setStickerSetThumbnail" + + name: str + """Sticker set name""" + user_id: int + """User identifier of the sticker set owner""" + format: str + """Format of the thumbnail, must be one of 'static' for a **.WEBP** or **.PNG** image, 'animated' for a **.TGS** animation, or 'video' for a **WEBM** video""" + thumbnail: Optional[Union[InputFile, str]] = None + """A **.WEBP** or **.PNG** image with the thumbnail, must be up to 128 kilobytes in size and have a width and height of exactly 100px, or a **.TGS** animation with a thumbnail up to 32 kilobytes in size (see `https://core.telegram.org/stickers#animation-requirements `_`https://core.telegram.org/stickers#animation-requirements `_ for animated sticker technical requirements), or a **WEBM** video with the thumbnail up to 32 kilobytes in size; see `https://core.telegram.org/stickers#video-requirements `_`https://core.telegram.org/stickers#video-requirements `_ for video sticker technical requirements. Pass a *file_id* as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » `. Animated and video sticker set thumbnails can't be uploaded via HTTP URL. If omitted, then the thumbnail is dropped and the first sticker is used as the thumbnail.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + name: str, + user_id: int, + format: str, + thumbnail: Optional[Union[InputFile, str]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + name=name, user_id=user_id, format=format, thumbnail=thumbnail, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/set_sticker_set_title.py b/env/Lib/site-packages/aiogram/methods/set_sticker_set_title.py new file mode 100644 index 0000000..ec25473 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_sticker_set_title.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramMethod + + +class SetStickerSetTitle(TelegramMethod[bool]): + """ + Use this method to set the title of a created sticker set. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickersettitle + """ + + __returning__ = bool + __api_method__ = "setStickerSetTitle" + + name: str + """Sticker set name""" + title: str + """Sticker set title, 1-64 characters""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, name: str, title: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(name=name, title=title, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/set_webhook.py b/env/Lib/site-packages/aiogram/methods/set_webhook.py new file mode 100644 index 0000000..998e51b --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/set_webhook.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from ..types import InputFile +from .base import TelegramMethod + + +class SetWebhook(TelegramMethod[bool]): + """ + Use this method to specify a URL and receive incoming updates via an outgoing webhook. Whenever there is an update for the bot, we will send an HTTPS POST request to the specified URL, containing a JSON-serialized :class:`aiogram.types.update.Update`. In case of an unsuccessful request, we will give up after a reasonable amount of attempts. Returns :code:`True` on success. + If you'd like to make sure that the webhook was set by you, you can specify secret data in the parameter *secret_token*. If specified, the request will contain a header 'X-Telegram-Bot-Api-Secret-Token' with the secret token as content. + + **Notes** + + **1.** You will not be able to receive updates using :class:`aiogram.methods.get_updates.GetUpdates` for as long as an outgoing webhook is set up. + + **2.** To use a self-signed certificate, you need to upload your `public key certificate `_ using *certificate* parameter. Please upload as InputFile, sending a String will not work. + + **3.** Ports currently supported *for webhooks*: **443, 80, 88, 8443**. + If you're having any trouble setting up webhooks, please check out this `amazing guide to webhooks `_. + + Source: https://core.telegram.org/bots/api#setwebhook + """ + + __returning__ = bool + __api_method__ = "setWebhook" + + url: str + """HTTPS URL to send updates to. Use an empty string to remove webhook integration""" + certificate: Optional[InputFile] = None + """Upload your public key certificate so that the root certificate in use can be checked. See our `self-signed guide `_ for details.""" + ip_address: Optional[str] = None + """The fixed IP address which will be used to send webhook requests instead of the IP address resolved through DNS""" + max_connections: Optional[int] = None + """The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100. Defaults to *40*. Use lower values to limit the load on your bot's server, and higher values to increase your bot's throughput.""" + allowed_updates: Optional[List[str]] = None + """A JSON-serialized list of the update types you want your bot to receive. For example, specify :code:`["message", "edited_channel_post", "callback_query"]` to only receive updates of these types. See :class:`aiogram.types.update.Update` for a complete list of available update types. Specify an empty list to receive all update types except *chat_member*, *message_reaction*, and *message_reaction_count* (default). If not specified, the previous setting will be used.""" + drop_pending_updates: Optional[bool] = None + """Pass :code:`True` to drop all pending updates""" + secret_token: Optional[str] = None + """A secret token to be sent in a header 'X-Telegram-Bot-Api-Secret-Token' in every webhook request, 1-256 characters. Only characters :code:`A-Z`, :code:`a-z`, :code:`0-9`, :code:`_` and :code:`-` are allowed. The header is useful to ensure that the request comes from a webhook set by you.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + url: str, + certificate: Optional[InputFile] = None, + ip_address: Optional[str] = None, + max_connections: Optional[int] = None, + allowed_updates: Optional[List[str]] = None, + drop_pending_updates: Optional[bool] = None, + secret_token: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + url=url, + certificate=certificate, + ip_address=ip_address, + max_connections=max_connections, + allowed_updates=allowed_updates, + drop_pending_updates=drop_pending_updates, + secret_token=secret_token, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/stop_message_live_location.py b/env/Lib/site-packages/aiogram/methods/stop_message_live_location.py new file mode 100644 index 0000000..f5fe335 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/stop_message_live_location.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import InlineKeyboardMarkup, Message +from .base import TelegramMethod + + +class StopMessageLiveLocation(TelegramMethod[Union[Message, bool]]): + """ + Use this method to stop updating a live location message before *live_period* expires. On success, if the message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#stopmessagelivelocation + """ + + __returning__ = Union[Message, bool] + __api_method__ = "stopMessageLiveLocation" + + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message to be edited was sent""" + chat_id: Optional[Union[int, str]] = None + """Required if *inline_message_id* is not specified. Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: Optional[int] = None + """Required if *inline_message_id* is not specified. Identifier of the message with live location to stop""" + inline_message_id: Optional[str] = None + """Required if *chat_id* and *message_id* are not specified. Identifier of the inline message""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for a new `inline keyboard `_.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + business_connection_id: Optional[str] = None, + chat_id: Optional[Union[int, str]] = None, + message_id: Optional[int] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + business_connection_id=business_connection_id, + chat_id=chat_id, + message_id=message_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/stop_poll.py b/env/Lib/site-packages/aiogram/methods/stop_poll.py new file mode 100644 index 0000000..8393a52 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/stop_poll.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..types import InlineKeyboardMarkup, Poll +from .base import TelegramMethod + + +class StopPoll(TelegramMethod[Poll]): + """ + Use this method to stop a poll which was sent by the bot. On success, the stopped :class:`aiogram.types.poll.Poll` is returned. + + Source: https://core.telegram.org/bots/api#stoppoll + """ + + __returning__ = Poll + __api_method__ = "stopPoll" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + message_id: int + """Identifier of the original message with the poll""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message to be edited was sent""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """A JSON-serialized object for a new message `inline keyboard `_.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_id: int, + business_connection_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + message_id=message_id, + business_connection_id=business_connection_id, + reply_markup=reply_markup, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/unban_chat_member.py b/env/Lib/site-packages/aiogram/methods/unban_chat_member.py new file mode 100644 index 0000000..1094db5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/unban_chat_member.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramMethod + + +class UnbanChatMember(TelegramMethod[bool]): + """ + Use this method to unban a previously banned user in a supergroup or channel. The user will **not** return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be **removed** from the chat. If you don't want this, use the parameter *only_if_banned*. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unbanchatmember + """ + + __returning__ = bool + __api_method__ = "unbanChatMember" + + chat_id: Union[int, str] + """Unique identifier for the target group or username of the target supergroup or channel (in the format :code:`@channelusername`)""" + user_id: int + """Unique identifier of the target user""" + only_if_banned: Optional[bool] = None + """Do nothing if the user is not banned""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + user_id: int, + only_if_banned: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + user_id=user_id, + only_if_banned=only_if_banned, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/unban_chat_sender_chat.py b/env/Lib/site-packages/aiogram/methods/unban_chat_sender_chat.py new file mode 100644 index 0000000..b981698 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/unban_chat_sender_chat.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class UnbanChatSenderChat(TelegramMethod[bool]): + """ + Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unbanchatsenderchat + """ + + __returning__ = bool + __api_method__ = "unbanChatSenderChat" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + sender_chat_id: int + """Unique identifier of the target sender chat""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + sender_chat_id: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, sender_chat_id=sender_chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/unhide_general_forum_topic.py b/env/Lib/site-packages/aiogram/methods/unhide_general_forum_topic.py new file mode 100644 index 0000000..a9149bc --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/unhide_general_forum_topic.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class UnhideGeneralForumTopic(TelegramMethod[bool]): + """ + Use this method to unhide the 'General' topic in a forum supergroup chat. The bot must be an administrator in the chat for this to work and must have the *can_manage_topics* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unhidegeneralforumtopic + """ + + __returning__ = bool + __api_method__ = "unhideGeneralForumTopic" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/unpin_all_chat_messages.py b/env/Lib/site-packages/aiogram/methods/unpin_all_chat_messages.py new file mode 100644 index 0000000..aca090f --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/unpin_all_chat_messages.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class UnpinAllChatMessages(TelegramMethod[bool]): + """ + Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinallchatmessages + """ + + __returning__ = bool + __api_method__ = "unpinAllChatMessages" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/unpin_all_forum_topic_messages.py b/env/Lib/site-packages/aiogram/methods/unpin_all_forum_topic_messages.py new file mode 100644 index 0000000..f1350ec --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/unpin_all_forum_topic_messages.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramMethod + + +class UnpinAllForumTopicMessages(TelegramMethod[bool]): + """ + Use this method to clear the list of pinned messages in a forum topic. The bot must be an administrator in the chat for this to work and must have the *can_pin_messages* administrator right in the supergroup. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinallforumtopicmessages + """ + + __returning__ = bool + __api_method__ = "unpinAllForumTopicMessages" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + message_thread_id: int + """Unique identifier for the target message thread of the forum topic""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + message_thread_id: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, message_thread_id=message_thread_id, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/methods/unpin_all_general_forum_topic_messages.py b/env/Lib/site-packages/aiogram/methods/unpin_all_general_forum_topic_messages.py new file mode 100644 index 0000000..be76c19 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/unpin_all_general_forum_topic_messages.py @@ -0,0 +1,30 @@ +from typing import TYPE_CHECKING, Any, Union + +from aiogram.methods import TelegramMethod + + +class UnpinAllGeneralForumTopicMessages(TelegramMethod[bool]): + """ + Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the *can_pin_messages* administrator right in the supergroup. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages + """ + + __returning__ = bool + __api_method__ = "unpinAllGeneralForumTopicMessages" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat_id: Union[int, str], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/methods/unpin_chat_message.py b/env/Lib/site-packages/aiogram/methods/unpin_chat_message.py new file mode 100644 index 0000000..249aee6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/unpin_chat_message.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramMethod + + +class UnpinChatMessage(TelegramMethod[bool]): + """ + Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinchatmessage + """ + + __returning__ = bool + __api_method__ = "unpinChatMessage" + + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`)""" + business_connection_id: Optional[str] = None + """Unique identifier of the business connection on behalf of which the message will be unpinned""" + message_id: Optional[int] = None + """Identifier of the message to unpin. Required if *business_connection_id* is specified. If not specified, the most recent pinned message (by sending date) will be unpinned.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat_id: Union[int, str], + business_connection_id: Optional[str] = None, + message_id: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat_id=chat_id, + business_connection_id=business_connection_id, + message_id=message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/methods/upload_sticker_file.py b/env/Lib/site-packages/aiogram/methods/upload_sticker_file.py new file mode 100644 index 0000000..600f83a --- /dev/null +++ b/env/Lib/site-packages/aiogram/methods/upload_sticker_file.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from ..types import File, InputFile +from .base import TelegramMethod + + +class UploadStickerFile(TelegramMethod[File]): + """ + Use this method to upload a file with a sticker for later use in the :class:`aiogram.methods.create_new_sticker_set.CreateNewStickerSet`, :class:`aiogram.methods.add_sticker_to_set.AddStickerToSet`, or :class:`aiogram.methods.replace_sticker_in_set.ReplaceStickerInSet` methods (the file can be used multiple times). Returns the uploaded :class:`aiogram.types.file.File` on success. + + Source: https://core.telegram.org/bots/api#uploadstickerfile + """ + + __returning__ = File + __api_method__ = "uploadStickerFile" + + user_id: int + """User identifier of sticker file owner""" + sticker: InputFile + """A file with the sticker in .WEBP, .PNG, .TGS, or .WEBM format. See `https://core.telegram.org/stickers `_`https://core.telegram.org/stickers `_ for technical requirements. :ref:`More information on Sending Files » `""" + sticker_format: str + """Format of the sticker, must be one of 'static', 'animated', 'video'""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + sticker: InputFile, + sticker_format: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + user_id=user_id, + sticker=sticker, + sticker_format=sticker_format, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/py.typed b/env/Lib/site-packages/aiogram/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/types/__init__.py b/env/Lib/site-packages/aiogram/types/__init__.py new file mode 100644 index 0000000..97442b3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/__init__.py @@ -0,0 +1,490 @@ +from typing import List, Literal, Optional, Union + +from .animation import Animation +from .audio import Audio +from .background_fill import BackgroundFill +from .background_fill_freeform_gradient import BackgroundFillFreeformGradient +from .background_fill_gradient import BackgroundFillGradient +from .background_fill_solid import BackgroundFillSolid +from .background_type import BackgroundType +from .background_type_chat_theme import BackgroundTypeChatTheme +from .background_type_fill import BackgroundTypeFill +from .background_type_pattern import BackgroundTypePattern +from .background_type_wallpaper import BackgroundTypeWallpaper +from .base import UNSET_PARSE_MODE, TelegramObject +from .birthdate import Birthdate +from .bot_command import BotCommand +from .bot_command_scope import BotCommandScope +from .bot_command_scope_all_chat_administrators import ( + BotCommandScopeAllChatAdministrators, +) +from .bot_command_scope_all_group_chats import BotCommandScopeAllGroupChats +from .bot_command_scope_all_private_chats import BotCommandScopeAllPrivateChats +from .bot_command_scope_chat import BotCommandScopeChat +from .bot_command_scope_chat_administrators import BotCommandScopeChatAdministrators +from .bot_command_scope_chat_member import BotCommandScopeChatMember +from .bot_command_scope_default import BotCommandScopeDefault +from .bot_description import BotDescription +from .bot_name import BotName +from .bot_short_description import BotShortDescription +from .business_connection import BusinessConnection +from .business_intro import BusinessIntro +from .business_location import BusinessLocation +from .business_messages_deleted import BusinessMessagesDeleted +from .business_opening_hours import BusinessOpeningHours +from .business_opening_hours_interval import BusinessOpeningHoursInterval +from .callback_game import CallbackGame +from .callback_query import CallbackQuery +from .chat import Chat +from .chat_administrator_rights import ChatAdministratorRights +from .chat_background import ChatBackground +from .chat_boost import ChatBoost +from .chat_boost_added import ChatBoostAdded +from .chat_boost_removed import ChatBoostRemoved +from .chat_boost_source import ChatBoostSource +from .chat_boost_source_gift_code import ChatBoostSourceGiftCode +from .chat_boost_source_giveaway import ChatBoostSourceGiveaway +from .chat_boost_source_premium import ChatBoostSourcePremium +from .chat_boost_updated import ChatBoostUpdated +from .chat_full_info import ChatFullInfo +from .chat_invite_link import ChatInviteLink +from .chat_join_request import ChatJoinRequest +from .chat_location import ChatLocation +from .chat_member import ChatMember +from .chat_member_administrator import ChatMemberAdministrator +from .chat_member_banned import ChatMemberBanned +from .chat_member_left import ChatMemberLeft +from .chat_member_member import ChatMemberMember +from .chat_member_owner import ChatMemberOwner +from .chat_member_restricted import ChatMemberRestricted +from .chat_member_updated import ChatMemberUpdated +from .chat_permissions import ChatPermissions +from .chat_photo import ChatPhoto +from .chat_shared import ChatShared +from .chosen_inline_result import ChosenInlineResult +from .contact import Contact +from .custom import DateTime +from .dice import Dice +from .document import Document +from .downloadable import Downloadable +from .encrypted_credentials import EncryptedCredentials +from .encrypted_passport_element import EncryptedPassportElement +from .error_event import ErrorEvent +from .external_reply_info import ExternalReplyInfo +from .file import File +from .force_reply import ForceReply +from .forum_topic import ForumTopic +from .forum_topic_closed import ForumTopicClosed +from .forum_topic_created import ForumTopicCreated +from .forum_topic_edited import ForumTopicEdited +from .forum_topic_reopened import ForumTopicReopened +from .game import Game +from .game_high_score import GameHighScore +from .general_forum_topic_hidden import GeneralForumTopicHidden +from .general_forum_topic_unhidden import GeneralForumTopicUnhidden +from .giveaway import Giveaway +from .giveaway_completed import GiveawayCompleted +from .giveaway_created import GiveawayCreated +from .giveaway_winners import GiveawayWinners +from .inaccessible_message import InaccessibleMessage +from .inline_keyboard_button import InlineKeyboardButton +from .inline_keyboard_markup import InlineKeyboardMarkup +from .inline_query import InlineQuery +from .inline_query_result import InlineQueryResult +from .inline_query_result_article import InlineQueryResultArticle +from .inline_query_result_audio import InlineQueryResultAudio +from .inline_query_result_cached_audio import InlineQueryResultCachedAudio +from .inline_query_result_cached_document import InlineQueryResultCachedDocument +from .inline_query_result_cached_gif import InlineQueryResultCachedGif +from .inline_query_result_cached_mpeg4_gif import InlineQueryResultCachedMpeg4Gif +from .inline_query_result_cached_photo import InlineQueryResultCachedPhoto +from .inline_query_result_cached_sticker import InlineQueryResultCachedSticker +from .inline_query_result_cached_video import InlineQueryResultCachedVideo +from .inline_query_result_cached_voice import InlineQueryResultCachedVoice +from .inline_query_result_contact import InlineQueryResultContact +from .inline_query_result_document import InlineQueryResultDocument +from .inline_query_result_game import InlineQueryResultGame +from .inline_query_result_gif import InlineQueryResultGif +from .inline_query_result_location import InlineQueryResultLocation +from .inline_query_result_mpeg4_gif import InlineQueryResultMpeg4Gif +from .inline_query_result_photo import InlineQueryResultPhoto +from .inline_query_result_venue import InlineQueryResultVenue +from .inline_query_result_video import InlineQueryResultVideo +from .inline_query_result_voice import InlineQueryResultVoice +from .inline_query_results_button import InlineQueryResultsButton +from .input_contact_message_content import InputContactMessageContent +from .input_file import BufferedInputFile, FSInputFile, InputFile, URLInputFile +from .input_invoice_message_content import InputInvoiceMessageContent +from .input_location_message_content import InputLocationMessageContent +from .input_media import InputMedia +from .input_media_animation import InputMediaAnimation +from .input_media_audio import InputMediaAudio +from .input_media_document import InputMediaDocument +from .input_media_photo import InputMediaPhoto +from .input_media_video import InputMediaVideo +from .input_message_content import InputMessageContent +from .input_paid_media import InputPaidMedia +from .input_paid_media_photo import InputPaidMediaPhoto +from .input_paid_media_video import InputPaidMediaVideo +from .input_poll_option import InputPollOption +from .input_sticker import InputSticker +from .input_text_message_content import InputTextMessageContent +from .input_venue_message_content import InputVenueMessageContent +from .invoice import Invoice +from .keyboard_button import KeyboardButton +from .keyboard_button_poll_type import KeyboardButtonPollType +from .keyboard_button_request_chat import KeyboardButtonRequestChat +from .keyboard_button_request_user import KeyboardButtonRequestUser +from .keyboard_button_request_users import KeyboardButtonRequestUsers +from .labeled_price import LabeledPrice +from .link_preview_options import LinkPreviewOptions +from .location import Location +from .login_url import LoginUrl +from .mask_position import MaskPosition +from .maybe_inaccessible_message import MaybeInaccessibleMessage +from .menu_button import MenuButton +from .menu_button_commands import MenuButtonCommands +from .menu_button_default import MenuButtonDefault +from .menu_button_web_app import MenuButtonWebApp +from .message import ContentType, Message +from .message_auto_delete_timer_changed import MessageAutoDeleteTimerChanged +from .message_entity import MessageEntity +from .message_id import MessageId +from .message_origin import MessageOrigin +from .message_origin_channel import MessageOriginChannel +from .message_origin_chat import MessageOriginChat +from .message_origin_hidden_user import MessageOriginHiddenUser +from .message_origin_user import MessageOriginUser +from .message_reaction_count_updated import MessageReactionCountUpdated +from .message_reaction_updated import MessageReactionUpdated +from .order_info import OrderInfo +from .paid_media import PaidMedia +from .paid_media_info import PaidMediaInfo +from .paid_media_photo import PaidMediaPhoto +from .paid_media_preview import PaidMediaPreview +from .paid_media_video import PaidMediaVideo +from .passport_data import PassportData +from .passport_element_error import PassportElementError +from .passport_element_error_data_field import PassportElementErrorDataField +from .passport_element_error_file import PassportElementErrorFile +from .passport_element_error_files import PassportElementErrorFiles +from .passport_element_error_front_side import PassportElementErrorFrontSide +from .passport_element_error_reverse_side import PassportElementErrorReverseSide +from .passport_element_error_selfie import PassportElementErrorSelfie +from .passport_element_error_translation_file import PassportElementErrorTranslationFile +from .passport_element_error_translation_files import ( + PassportElementErrorTranslationFiles, +) +from .passport_element_error_unspecified import PassportElementErrorUnspecified +from .passport_file import PassportFile +from .photo_size import PhotoSize +from .poll import Poll +from .poll_answer import PollAnswer +from .poll_option import PollOption +from .pre_checkout_query import PreCheckoutQuery +from .proximity_alert_triggered import ProximityAlertTriggered +from .reaction_count import ReactionCount +from .reaction_type import ReactionType +from .reaction_type_custom_emoji import ReactionTypeCustomEmoji +from .reaction_type_emoji import ReactionTypeEmoji +from .reaction_type_paid import ReactionTypePaid +from .refunded_payment import RefundedPayment +from .reply_keyboard_markup import ReplyKeyboardMarkup +from .reply_keyboard_remove import ReplyKeyboardRemove +from .reply_parameters import ReplyParameters +from .response_parameters import ResponseParameters +from .revenue_withdrawal_state import RevenueWithdrawalState +from .revenue_withdrawal_state_failed import RevenueWithdrawalStateFailed +from .revenue_withdrawal_state_pending import RevenueWithdrawalStatePending +from .revenue_withdrawal_state_succeeded import RevenueWithdrawalStateSucceeded +from .sent_web_app_message import SentWebAppMessage +from .shared_user import SharedUser +from .shipping_address import ShippingAddress +from .shipping_option import ShippingOption +from .shipping_query import ShippingQuery +from .star_transaction import StarTransaction +from .star_transactions import StarTransactions +from .sticker import Sticker +from .sticker_set import StickerSet +from .story import Story +from .successful_payment import SuccessfulPayment +from .switch_inline_query_chosen_chat import SwitchInlineQueryChosenChat +from .text_quote import TextQuote +from .transaction_partner import TransactionPartner +from .transaction_partner_fragment import TransactionPartnerFragment +from .transaction_partner_other import TransactionPartnerOther +from .transaction_partner_telegram_ads import TransactionPartnerTelegramAds +from .transaction_partner_user import TransactionPartnerUser +from .update import Update +from .user import User +from .user_chat_boosts import UserChatBoosts +from .user_profile_photos import UserProfilePhotos +from .user_shared import UserShared +from .users_shared import UsersShared +from .venue import Venue +from .video import Video +from .video_chat_ended import VideoChatEnded +from .video_chat_participants_invited import VideoChatParticipantsInvited +from .video_chat_scheduled import VideoChatScheduled +from .video_chat_started import VideoChatStarted +from .video_note import VideoNote +from .voice import Voice +from .web_app_data import WebAppData +from .web_app_info import WebAppInfo +from .webhook_info import WebhookInfo +from .write_access_allowed import WriteAccessAllowed + +__all__ = ( + "Animation", + "Audio", + "BackgroundFill", + "BackgroundFillFreeformGradient", + "BackgroundFillGradient", + "BackgroundFillSolid", + "BackgroundType", + "BackgroundTypeChatTheme", + "BackgroundTypeFill", + "BackgroundTypePattern", + "BackgroundTypeWallpaper", + "Birthdate", + "BotCommand", + "BotCommandScope", + "BotCommandScopeAllChatAdministrators", + "BotCommandScopeAllGroupChats", + "BotCommandScopeAllPrivateChats", + "BotCommandScopeChat", + "BotCommandScopeChatAdministrators", + "BotCommandScopeChatMember", + "BotCommandScopeDefault", + "BotDescription", + "BotName", + "BotShortDescription", + "BufferedInputFile", + "BusinessConnection", + "BusinessIntro", + "BusinessLocation", + "BusinessMessagesDeleted", + "BusinessOpeningHours", + "BusinessOpeningHoursInterval", + "CallbackGame", + "CallbackQuery", + "Chat", + "ChatAdministratorRights", + "ChatBackground", + "ChatBoost", + "ChatBoostAdded", + "ChatBoostRemoved", + "ChatBoostSource", + "ChatBoostSourceGiftCode", + "ChatBoostSourceGiveaway", + "ChatBoostSourcePremium", + "ChatBoostUpdated", + "ChatFullInfo", + "ChatInviteLink", + "ChatJoinRequest", + "ChatLocation", + "ChatMember", + "ChatMemberAdministrator", + "ChatMemberBanned", + "ChatMemberLeft", + "ChatMemberMember", + "ChatMemberOwner", + "ChatMemberRestricted", + "ChatMemberUpdated", + "ChatPermissions", + "ChatPhoto", + "ChatShared", + "ChosenInlineResult", + "Contact", + "ContentType", + "DateTime", + "Dice", + "Document", + "Downloadable", + "EncryptedCredentials", + "EncryptedPassportElement", + "ErrorEvent", + "ExternalReplyInfo", + "FSInputFile", + "File", + "ForceReply", + "ForumTopic", + "ForumTopicClosed", + "ForumTopicCreated", + "ForumTopicEdited", + "ForumTopicReopened", + "Game", + "GameHighScore", + "GeneralForumTopicHidden", + "GeneralForumTopicUnhidden", + "Giveaway", + "GiveawayCompleted", + "GiveawayCreated", + "GiveawayWinners", + "InaccessibleMessage", + "InlineKeyboardButton", + "InlineKeyboardMarkup", + "InlineQuery", + "InlineQueryResult", + "InlineQueryResultArticle", + "InlineQueryResultAudio", + "InlineQueryResultCachedAudio", + "InlineQueryResultCachedDocument", + "InlineQueryResultCachedGif", + "InlineQueryResultCachedMpeg4Gif", + "InlineQueryResultCachedPhoto", + "InlineQueryResultCachedSticker", + "InlineQueryResultCachedVideo", + "InlineQueryResultCachedVoice", + "InlineQueryResultContact", + "InlineQueryResultDocument", + "InlineQueryResultGame", + "InlineQueryResultGif", + "InlineQueryResultLocation", + "InlineQueryResultMpeg4Gif", + "InlineQueryResultPhoto", + "InlineQueryResultVenue", + "InlineQueryResultVideo", + "InlineQueryResultVoice", + "InlineQueryResultsButton", + "InputContactMessageContent", + "InputFile", + "InputInvoiceMessageContent", + "InputLocationMessageContent", + "InputMedia", + "InputMediaAnimation", + "InputMediaAudio", + "InputMediaDocument", + "InputMediaPhoto", + "InputMediaVideo", + "InputMessageContent", + "InputPaidMedia", + "InputPaidMediaPhoto", + "InputPaidMediaVideo", + "InputPollOption", + "InputSticker", + "InputTextMessageContent", + "InputVenueMessageContent", + "Invoice", + "KeyboardButton", + "KeyboardButtonPollType", + "KeyboardButtonRequestChat", + "KeyboardButtonRequestUser", + "KeyboardButtonRequestUsers", + "LabeledPrice", + "LinkPreviewOptions", + "Location", + "LoginUrl", + "MaskPosition", + "MaybeInaccessibleMessage", + "MenuButton", + "MenuButtonCommands", + "MenuButtonDefault", + "MenuButtonWebApp", + "Message", + "MessageAutoDeleteTimerChanged", + "MessageEntity", + "MessageId", + "MessageOrigin", + "MessageOriginChannel", + "MessageOriginChat", + "MessageOriginHiddenUser", + "MessageOriginUser", + "MessageReactionCountUpdated", + "MessageReactionUpdated", + "OrderInfo", + "PaidMedia", + "PaidMediaInfo", + "PaidMediaPhoto", + "PaidMediaPreview", + "PaidMediaVideo", + "PassportData", + "PassportElementError", + "PassportElementErrorDataField", + "PassportElementErrorFile", + "PassportElementErrorFiles", + "PassportElementErrorFrontSide", + "PassportElementErrorReverseSide", + "PassportElementErrorSelfie", + "PassportElementErrorTranslationFile", + "PassportElementErrorTranslationFiles", + "PassportElementErrorUnspecified", + "PassportFile", + "PhotoSize", + "Poll", + "PollAnswer", + "PollOption", + "PreCheckoutQuery", + "ProximityAlertTriggered", + "ReactionCount", + "ReactionType", + "ReactionTypeCustomEmoji", + "ReactionTypeEmoji", + "ReactionTypePaid", + "RefundedPayment", + "ReplyKeyboardMarkup", + "ReplyKeyboardRemove", + "ReplyParameters", + "ResponseParameters", + "RevenueWithdrawalState", + "RevenueWithdrawalStateFailed", + "RevenueWithdrawalStatePending", + "RevenueWithdrawalStateSucceeded", + "SentWebAppMessage", + "SharedUser", + "ShippingAddress", + "ShippingOption", + "ShippingQuery", + "StarTransaction", + "StarTransactions", + "Sticker", + "StickerSet", + "Story", + "SuccessfulPayment", + "SwitchInlineQueryChosenChat", + "TelegramObject", + "TextQuote", + "TransactionPartner", + "TransactionPartnerFragment", + "TransactionPartnerOther", + "TransactionPartnerTelegramAds", + "TransactionPartnerUser", + "UNSET_PARSE_MODE", + "URLInputFile", + "Update", + "User", + "UserChatBoosts", + "UserProfilePhotos", + "UserShared", + "UsersShared", + "Venue", + "Video", + "VideoChatEnded", + "VideoChatParticipantsInvited", + "VideoChatScheduled", + "VideoChatStarted", + "VideoNote", + "Voice", + "WebAppData", + "WebAppInfo", + "WebhookInfo", + "WriteAccessAllowed", +) + +# Load typing forward refs for every TelegramObject +for _entity_name in __all__: + _entity = globals()[_entity_name] + if not hasattr(_entity, "model_rebuild"): + continue + _entity.model_rebuild( + _types_namespace={ + "List": List, + "Optional": Optional, + "Union": Union, + "Literal": Literal, + **{k: v for k, v in globals().items() if k in __all__}, + } + ) + +del _entity +del _entity_name diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..a2b9a11 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/animation.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/animation.cpython-311.pyc new file mode 100644 index 0000000..a9479f9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/animation.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/audio.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/audio.cpython-311.pyc new file mode 100644 index 0000000..3106a0a Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/audio.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_fill.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_fill.cpython-311.pyc new file mode 100644 index 0000000..fd5e1ea Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_fill.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_freeform_gradient.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_freeform_gradient.cpython-311.pyc new file mode 100644 index 0000000..f375c71 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_freeform_gradient.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_gradient.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_gradient.cpython-311.pyc new file mode 100644 index 0000000..2444fa8 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_gradient.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_solid.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_solid.cpython-311.pyc new file mode 100644 index 0000000..592570c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_fill_solid.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_type.cpython-311.pyc new file mode 100644 index 0000000..153c961 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_type_chat_theme.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_type_chat_theme.cpython-311.pyc new file mode 100644 index 0000000..bef87da Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_type_chat_theme.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_type_fill.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_type_fill.cpython-311.pyc new file mode 100644 index 0000000..2b6a97d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_type_fill.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_type_pattern.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_type_pattern.cpython-311.pyc new file mode 100644 index 0000000..d05c75e Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_type_pattern.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/background_type_wallpaper.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/background_type_wallpaper.cpython-311.pyc new file mode 100644 index 0000000..6668677 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/background_type_wallpaper.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..8199e4d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/birthdate.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/birthdate.cpython-311.pyc new file mode 100644 index 0000000..ca1bfd4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/birthdate.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command.cpython-311.pyc new file mode 100644 index 0000000..34ee071 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope.cpython-311.pyc new file mode 100644 index 0000000..4b23afe Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_chat_administrators.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_chat_administrators.cpython-311.pyc new file mode 100644 index 0000000..467af53 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_chat_administrators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_group_chats.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_group_chats.cpython-311.pyc new file mode 100644 index 0000000..50c7af2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_group_chats.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_private_chats.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_private_chats.cpython-311.pyc new file mode 100644 index 0000000..bcf8045 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_all_private_chats.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat.cpython-311.pyc new file mode 100644 index 0000000..bff4841 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat_administrators.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat_administrators.cpython-311.pyc new file mode 100644 index 0000000..71e028e Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat_administrators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat_member.cpython-311.pyc new file mode 100644 index 0000000..d06725d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_default.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_default.cpython-311.pyc new file mode 100644 index 0000000..d639657 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_command_scope_default.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_description.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_description.cpython-311.pyc new file mode 100644 index 0000000..60abf2b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_description.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_name.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_name.cpython-311.pyc new file mode 100644 index 0000000..3cf5955 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_name.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/bot_short_description.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/bot_short_description.cpython-311.pyc new file mode 100644 index 0000000..fb69b3e Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/bot_short_description.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/business_connection.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/business_connection.cpython-311.pyc new file mode 100644 index 0000000..92cb3cb Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/business_connection.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/business_intro.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/business_intro.cpython-311.pyc new file mode 100644 index 0000000..d5dc4b3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/business_intro.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/business_location.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/business_location.cpython-311.pyc new file mode 100644 index 0000000..08bfbc2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/business_location.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/business_messages_deleted.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/business_messages_deleted.cpython-311.pyc new file mode 100644 index 0000000..ea98910 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/business_messages_deleted.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/business_opening_hours.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/business_opening_hours.cpython-311.pyc new file mode 100644 index 0000000..f704a12 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/business_opening_hours.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/business_opening_hours_interval.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/business_opening_hours_interval.cpython-311.pyc new file mode 100644 index 0000000..077ac41 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/business_opening_hours_interval.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/callback_game.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/callback_game.cpython-311.pyc new file mode 100644 index 0000000..749f55a Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/callback_game.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/callback_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/callback_query.cpython-311.pyc new file mode 100644 index 0000000..995ffe7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/callback_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat.cpython-311.pyc new file mode 100644 index 0000000..922a23d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_administrator_rights.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_administrator_rights.cpython-311.pyc new file mode 100644 index 0000000..531bd52 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_administrator_rights.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_background.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_background.cpython-311.pyc new file mode 100644 index 0000000..cacaec7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_background.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost.cpython-311.pyc new file mode 100644 index 0000000..c08148b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_added.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_added.cpython-311.pyc new file mode 100644 index 0000000..b239fdd Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_added.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_removed.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_removed.cpython-311.pyc new file mode 100644 index 0000000..920fa18 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_removed.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source.cpython-311.pyc new file mode 100644 index 0000000..d76db39 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_gift_code.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_gift_code.cpython-311.pyc new file mode 100644 index 0000000..068af11 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_gift_code.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_giveaway.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_giveaway.cpython-311.pyc new file mode 100644 index 0000000..6837edb Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_giveaway.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_premium.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_premium.cpython-311.pyc new file mode 100644 index 0000000..0159d5b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_source_premium.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_updated.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_updated.cpython-311.pyc new file mode 100644 index 0000000..6d4a39c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_boost_updated.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_full_info.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_full_info.cpython-311.pyc new file mode 100644 index 0000000..b638ac9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_full_info.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_invite_link.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_invite_link.cpython-311.pyc new file mode 100644 index 0000000..cc462fd Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_invite_link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_join_request.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_join_request.cpython-311.pyc new file mode 100644 index 0000000..a57e370 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_join_request.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_location.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_location.cpython-311.pyc new file mode 100644 index 0000000..26a218b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_location.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member.cpython-311.pyc new file mode 100644 index 0000000..1b89a5e Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_administrator.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_administrator.cpython-311.pyc new file mode 100644 index 0000000..315bde1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_administrator.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_banned.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_banned.cpython-311.pyc new file mode 100644 index 0000000..7ed43f5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_banned.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_left.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_left.cpython-311.pyc new file mode 100644 index 0000000..161154d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_left.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_member.cpython-311.pyc new file mode 100644 index 0000000..37843c6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_owner.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_owner.cpython-311.pyc new file mode 100644 index 0000000..4158b97 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_owner.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_restricted.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_restricted.cpython-311.pyc new file mode 100644 index 0000000..0bb342c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_restricted.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_updated.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_updated.cpython-311.pyc new file mode 100644 index 0000000..a199fd1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_member_updated.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_permissions.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_permissions.cpython-311.pyc new file mode 100644 index 0000000..659fdfe Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_permissions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_photo.cpython-311.pyc new file mode 100644 index 0000000..3797f52 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chat_shared.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chat_shared.cpython-311.pyc new file mode 100644 index 0000000..60dc75a Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chat_shared.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/chosen_inline_result.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/chosen_inline_result.cpython-311.pyc new file mode 100644 index 0000000..0a0ecb0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/chosen_inline_result.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/contact.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/contact.cpython-311.pyc new file mode 100644 index 0000000..b6556b7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/contact.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/custom.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/custom.cpython-311.pyc new file mode 100644 index 0000000..822891b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/custom.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/dice.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/dice.cpython-311.pyc new file mode 100644 index 0000000..11f00a6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/dice.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/document.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/document.cpython-311.pyc new file mode 100644 index 0000000..81389ab Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/document.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/downloadable.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/downloadable.cpython-311.pyc new file mode 100644 index 0000000..77828d5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/downloadable.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/encrypted_credentials.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/encrypted_credentials.cpython-311.pyc new file mode 100644 index 0000000..782e04d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/encrypted_credentials.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/encrypted_passport_element.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/encrypted_passport_element.cpython-311.pyc new file mode 100644 index 0000000..b691eff Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/encrypted_passport_element.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/error_event.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/error_event.cpython-311.pyc new file mode 100644 index 0000000..2e96c85 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/error_event.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/external_reply_info.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/external_reply_info.cpython-311.pyc new file mode 100644 index 0000000..cb15587 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/external_reply_info.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/file.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/file.cpython-311.pyc new file mode 100644 index 0000000..ef730d8 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/file.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/force_reply.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/force_reply.cpython-311.pyc new file mode 100644 index 0000000..ccf8ed6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/force_reply.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic.cpython-311.pyc new file mode 100644 index 0000000..9015b62 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_closed.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_closed.cpython-311.pyc new file mode 100644 index 0000000..cb759b3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_closed.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_created.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_created.cpython-311.pyc new file mode 100644 index 0000000..e0637d3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_created.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_edited.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_edited.cpython-311.pyc new file mode 100644 index 0000000..941eb8b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_edited.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_reopened.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_reopened.cpython-311.pyc new file mode 100644 index 0000000..d84d429 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/forum_topic_reopened.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/game.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/game.cpython-311.pyc new file mode 100644 index 0000000..3a2f37e Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/game.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/game_high_score.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/game_high_score.cpython-311.pyc new file mode 100644 index 0000000..34a6bf5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/game_high_score.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/general_forum_topic_hidden.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/general_forum_topic_hidden.cpython-311.pyc new file mode 100644 index 0000000..f40accd Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/general_forum_topic_hidden.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/general_forum_topic_unhidden.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/general_forum_topic_unhidden.cpython-311.pyc new file mode 100644 index 0000000..41260f0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/general_forum_topic_unhidden.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/giveaway.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/giveaway.cpython-311.pyc new file mode 100644 index 0000000..aa83d41 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/giveaway.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_completed.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_completed.cpython-311.pyc new file mode 100644 index 0000000..1a6e5d6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_completed.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_created.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_created.cpython-311.pyc new file mode 100644 index 0000000..8a06ef6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_created.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_winners.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_winners.cpython-311.pyc new file mode 100644 index 0000000..c932048 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/giveaway_winners.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inaccessible_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inaccessible_message.cpython-311.pyc new file mode 100644 index 0000000..1d4661b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inaccessible_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_keyboard_button.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_keyboard_button.cpython-311.pyc new file mode 100644 index 0000000..376d8c6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_keyboard_button.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_keyboard_markup.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_keyboard_markup.cpython-311.pyc new file mode 100644 index 0000000..c9505f9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_keyboard_markup.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query.cpython-311.pyc new file mode 100644 index 0000000..54c86c0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result.cpython-311.pyc new file mode 100644 index 0000000..a127073 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_article.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_article.cpython-311.pyc new file mode 100644 index 0000000..6bc4c67 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_article.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_audio.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_audio.cpython-311.pyc new file mode 100644 index 0000000..299a86d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_audio.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_audio.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_audio.cpython-311.pyc new file mode 100644 index 0000000..ad60d9c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_audio.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_document.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_document.cpython-311.pyc new file mode 100644 index 0000000..2afa48d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_document.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_gif.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_gif.cpython-311.pyc new file mode 100644 index 0000000..dc38aff Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_gif.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_mpeg4_gif.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_mpeg4_gif.cpython-311.pyc new file mode 100644 index 0000000..a593a8d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_mpeg4_gif.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_photo.cpython-311.pyc new file mode 100644 index 0000000..ebee0bc Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_sticker.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_sticker.cpython-311.pyc new file mode 100644 index 0000000..d8982df Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_sticker.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_video.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_video.cpython-311.pyc new file mode 100644 index 0000000..7f648c7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_video.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_voice.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_voice.cpython-311.pyc new file mode 100644 index 0000000..96e7a46 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_cached_voice.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_contact.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_contact.cpython-311.pyc new file mode 100644 index 0000000..ef8ecf4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_contact.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_document.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_document.cpython-311.pyc new file mode 100644 index 0000000..407571c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_document.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_game.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_game.cpython-311.pyc new file mode 100644 index 0000000..e731d0d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_game.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_gif.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_gif.cpython-311.pyc new file mode 100644 index 0000000..cdce8d0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_gif.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_location.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_location.cpython-311.pyc new file mode 100644 index 0000000..f476f70 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_location.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_mpeg4_gif.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_mpeg4_gif.cpython-311.pyc new file mode 100644 index 0000000..8549d03 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_mpeg4_gif.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_photo.cpython-311.pyc new file mode 100644 index 0000000..d7cd99f Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_venue.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_venue.cpython-311.pyc new file mode 100644 index 0000000..cb3e817 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_venue.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_video.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_video.cpython-311.pyc new file mode 100644 index 0000000..b191cc0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_video.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_voice.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_voice.cpython-311.pyc new file mode 100644 index 0000000..bd719a8 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_result_voice.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_results_button.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_results_button.cpython-311.pyc new file mode 100644 index 0000000..06c3c87 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/inline_query_results_button.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_contact_message_content.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_contact_message_content.cpython-311.pyc new file mode 100644 index 0000000..db146dc Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_contact_message_content.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_file.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_file.cpython-311.pyc new file mode 100644 index 0000000..bf05a26 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_file.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_invoice_message_content.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_invoice_message_content.cpython-311.pyc new file mode 100644 index 0000000..c83de73 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_invoice_message_content.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_location_message_content.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_location_message_content.cpython-311.pyc new file mode 100644 index 0000000..64acb26 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_location_message_content.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_media.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_media.cpython-311.pyc new file mode 100644 index 0000000..c39aaef Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_media.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_media_animation.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_animation.cpython-311.pyc new file mode 100644 index 0000000..e014488 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_animation.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_media_audio.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_audio.cpython-311.pyc new file mode 100644 index 0000000..1f65173 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_audio.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_media_document.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_document.cpython-311.pyc new file mode 100644 index 0000000..8d4c173 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_document.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_media_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_photo.cpython-311.pyc new file mode 100644 index 0000000..0c450b6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_media_video.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_video.cpython-311.pyc new file mode 100644 index 0000000..d04f230 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_media_video.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_message_content.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_message_content.cpython-311.pyc new file mode 100644 index 0000000..81abad1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_message_content.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media.cpython-311.pyc new file mode 100644 index 0000000..79c686d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media_photo.cpython-311.pyc new file mode 100644 index 0000000..c43e539 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media_video.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media_video.cpython-311.pyc new file mode 100644 index 0000000..51337fc Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_paid_media_video.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_poll_option.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_poll_option.cpython-311.pyc new file mode 100644 index 0000000..86c74ac Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_poll_option.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_sticker.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_sticker.cpython-311.pyc new file mode 100644 index 0000000..39a479d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_sticker.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_text_message_content.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_text_message_content.cpython-311.pyc new file mode 100644 index 0000000..5ea0ee9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_text_message_content.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/input_venue_message_content.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/input_venue_message_content.cpython-311.pyc new file mode 100644 index 0000000..6ef6fc8 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/input_venue_message_content.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/invoice.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/invoice.cpython-311.pyc new file mode 100644 index 0000000..82a1f5c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/invoice.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button.cpython-311.pyc new file mode 100644 index 0000000..2f2afd4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_poll_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_poll_type.cpython-311.pyc new file mode 100644 index 0000000..406f3b5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_poll_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_chat.cpython-311.pyc new file mode 100644 index 0000000..ef02824 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_user.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_user.cpython-311.pyc new file mode 100644 index 0000000..fd9d842 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_user.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_users.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_users.cpython-311.pyc new file mode 100644 index 0000000..f54cad4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/keyboard_button_request_users.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/labeled_price.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/labeled_price.cpython-311.pyc new file mode 100644 index 0000000..ce8d2c0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/labeled_price.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/link_preview_options.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/link_preview_options.cpython-311.pyc new file mode 100644 index 0000000..dc019e6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/link_preview_options.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/location.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/location.cpython-311.pyc new file mode 100644 index 0000000..512ef25 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/location.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/login_url.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/login_url.cpython-311.pyc new file mode 100644 index 0000000..df163a3 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/login_url.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/mask_position.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/mask_position.cpython-311.pyc new file mode 100644 index 0000000..9441953 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/mask_position.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/maybe_inaccessible_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/maybe_inaccessible_message.cpython-311.pyc new file mode 100644 index 0000000..1b3d560 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/maybe_inaccessible_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/menu_button.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/menu_button.cpython-311.pyc new file mode 100644 index 0000000..6d1200f Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/menu_button.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_commands.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_commands.cpython-311.pyc new file mode 100644 index 0000000..4e66493 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_commands.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_default.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_default.cpython-311.pyc new file mode 100644 index 0000000..6787bde Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_default.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_web_app.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_web_app.cpython-311.pyc new file mode 100644 index 0000000..0af0a68 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/menu_button_web_app.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message.cpython-311.pyc new file mode 100644 index 0000000..79bb2f1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_auto_delete_timer_changed.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_auto_delete_timer_changed.cpython-311.pyc new file mode 100644 index 0000000..b637a96 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_auto_delete_timer_changed.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_entity.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_entity.cpython-311.pyc new file mode 100644 index 0000000..f0cef50 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_entity.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_id.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_id.cpython-311.pyc new file mode 100644 index 0000000..bd94dba Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_id.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_origin.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin.cpython-311.pyc new file mode 100644 index 0000000..590bce1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_channel.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_channel.cpython-311.pyc new file mode 100644 index 0000000..a41e8f1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_channel.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_chat.cpython-311.pyc new file mode 100644 index 0000000..5383c42 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_hidden_user.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_hidden_user.cpython-311.pyc new file mode 100644 index 0000000..1f53c68 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_hidden_user.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_user.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_user.cpython-311.pyc new file mode 100644 index 0000000..86b50c9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_origin_user.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_reaction_count_updated.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_reaction_count_updated.cpython-311.pyc new file mode 100644 index 0000000..347ca66 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_reaction_count_updated.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/message_reaction_updated.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/message_reaction_updated.cpython-311.pyc new file mode 100644 index 0000000..7e864a0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/message_reaction_updated.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/order_info.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/order_info.cpython-311.pyc new file mode 100644 index 0000000..08a9623 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/order_info.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/paid_media.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media.cpython-311.pyc new file mode 100644 index 0000000..bc7f056 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_info.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_info.cpython-311.pyc new file mode 100644 index 0000000..94d42ca Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_info.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_photo.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_photo.cpython-311.pyc new file mode 100644 index 0000000..c723aec Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_photo.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_preview.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_preview.cpython-311.pyc new file mode 100644 index 0000000..93aed1e Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_preview.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_video.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_video.cpython-311.pyc new file mode 100644 index 0000000..fb5515c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/paid_media_video.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_data.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_data.cpython-311.pyc new file mode 100644 index 0000000..f6ae9d1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_data.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error.cpython-311.pyc new file mode 100644 index 0000000..f4eca19 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_data_field.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_data_field.cpython-311.pyc new file mode 100644 index 0000000..b9c89c6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_data_field.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_file.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_file.cpython-311.pyc new file mode 100644 index 0000000..ba22cb9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_file.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_files.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_files.cpython-311.pyc new file mode 100644 index 0000000..b0712e9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_files.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_front_side.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_front_side.cpython-311.pyc new file mode 100644 index 0000000..2e2b9ee Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_front_side.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_reverse_side.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_reverse_side.cpython-311.pyc new file mode 100644 index 0000000..0f4c939 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_reverse_side.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_selfie.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_selfie.cpython-311.pyc new file mode 100644 index 0000000..3226ac8 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_selfie.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_translation_file.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_translation_file.cpython-311.pyc new file mode 100644 index 0000000..b15c314 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_translation_file.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_translation_files.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_translation_files.cpython-311.pyc new file mode 100644 index 0000000..a530ad7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_translation_files.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_unspecified.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_unspecified.cpython-311.pyc new file mode 100644 index 0000000..b01c7a4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_element_error_unspecified.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/passport_file.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/passport_file.cpython-311.pyc new file mode 100644 index 0000000..0886e2f Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/passport_file.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/photo_size.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/photo_size.cpython-311.pyc new file mode 100644 index 0000000..b096e86 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/photo_size.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/poll.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/poll.cpython-311.pyc new file mode 100644 index 0000000..8ac5a10 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/poll.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/poll_answer.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/poll_answer.cpython-311.pyc new file mode 100644 index 0000000..6276b66 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/poll_answer.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/poll_option.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/poll_option.cpython-311.pyc new file mode 100644 index 0000000..26d011c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/poll_option.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/pre_checkout_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/pre_checkout_query.cpython-311.pyc new file mode 100644 index 0000000..c5a4704 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/pre_checkout_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/proximity_alert_triggered.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/proximity_alert_triggered.cpython-311.pyc new file mode 100644 index 0000000..8ade302 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/proximity_alert_triggered.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/reaction_count.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_count.cpython-311.pyc new file mode 100644 index 0000000..78f80f6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_count.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type.cpython-311.pyc new file mode 100644 index 0000000..7146427 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_custom_emoji.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_custom_emoji.cpython-311.pyc new file mode 100644 index 0000000..1733a5b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_custom_emoji.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_emoji.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_emoji.cpython-311.pyc new file mode 100644 index 0000000..a53f785 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_emoji.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_paid.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_paid.cpython-311.pyc new file mode 100644 index 0000000..ba1c7de Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/reaction_type_paid.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/refunded_payment.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/refunded_payment.cpython-311.pyc new file mode 100644 index 0000000..044e426 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/refunded_payment.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/reply_keyboard_markup.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/reply_keyboard_markup.cpython-311.pyc new file mode 100644 index 0000000..adf898c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/reply_keyboard_markup.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/reply_keyboard_remove.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/reply_keyboard_remove.cpython-311.pyc new file mode 100644 index 0000000..318cd4d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/reply_keyboard_remove.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/reply_parameters.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/reply_parameters.cpython-311.pyc new file mode 100644 index 0000000..40ea5e2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/reply_parameters.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/response_parameters.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/response_parameters.cpython-311.pyc new file mode 100644 index 0000000..9a61df5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/response_parameters.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state.cpython-311.pyc new file mode 100644 index 0000000..0ad1d6a Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_failed.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_failed.cpython-311.pyc new file mode 100644 index 0000000..5a08e76 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_failed.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_pending.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_pending.cpython-311.pyc new file mode 100644 index 0000000..3e3af10 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_pending.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_succeeded.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_succeeded.cpython-311.pyc new file mode 100644 index 0000000..1561d50 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/revenue_withdrawal_state_succeeded.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/sent_web_app_message.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/sent_web_app_message.cpython-311.pyc new file mode 100644 index 0000000..dcb85af Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/sent_web_app_message.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/shared_user.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/shared_user.cpython-311.pyc new file mode 100644 index 0000000..999ce70 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/shared_user.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/shipping_address.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/shipping_address.cpython-311.pyc new file mode 100644 index 0000000..2596a21 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/shipping_address.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/shipping_option.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/shipping_option.cpython-311.pyc new file mode 100644 index 0000000..f0aceb4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/shipping_option.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/shipping_query.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/shipping_query.cpython-311.pyc new file mode 100644 index 0000000..7978e0c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/shipping_query.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/star_transaction.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/star_transaction.cpython-311.pyc new file mode 100644 index 0000000..62e25be Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/star_transaction.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/star_transactions.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/star_transactions.cpython-311.pyc new file mode 100644 index 0000000..7676adf Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/star_transactions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/sticker.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/sticker.cpython-311.pyc new file mode 100644 index 0000000..e37cf00 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/sticker.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/sticker_set.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/sticker_set.cpython-311.pyc new file mode 100644 index 0000000..16acbf2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/sticker_set.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/story.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/story.cpython-311.pyc new file mode 100644 index 0000000..b095c8e Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/story.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/successful_payment.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/successful_payment.cpython-311.pyc new file mode 100644 index 0000000..b7a01a6 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/successful_payment.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/switch_inline_query_chosen_chat.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/switch_inline_query_chosen_chat.cpython-311.pyc new file mode 100644 index 0000000..acd8955 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/switch_inline_query_chosen_chat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/text_quote.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/text_quote.cpython-311.pyc new file mode 100644 index 0000000..42524f7 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/text_quote.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner.cpython-311.pyc new file mode 100644 index 0000000..7dc88ae Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_fragment.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_fragment.cpython-311.pyc new file mode 100644 index 0000000..bc0135d Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_fragment.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_other.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_other.cpython-311.pyc new file mode 100644 index 0000000..cf3777c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_other.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_telegram_ads.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_telegram_ads.cpython-311.pyc new file mode 100644 index 0000000..92e0ee5 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_telegram_ads.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_user.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_user.cpython-311.pyc new file mode 100644 index 0000000..dd6a7cc Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/transaction_partner_user.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/update.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/update.cpython-311.pyc new file mode 100644 index 0000000..21e7fed Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/update.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/user.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/user.cpython-311.pyc new file mode 100644 index 0000000..7cc1edf Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/user.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/user_chat_boosts.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/user_chat_boosts.cpython-311.pyc new file mode 100644 index 0000000..9291076 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/user_chat_boosts.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/user_profile_photos.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/user_profile_photos.cpython-311.pyc new file mode 100644 index 0000000..8f895d2 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/user_profile_photos.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/user_shared.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/user_shared.cpython-311.pyc new file mode 100644 index 0000000..6f226d9 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/user_shared.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/users_shared.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/users_shared.cpython-311.pyc new file mode 100644 index 0000000..e5b8632 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/users_shared.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/venue.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/venue.cpython-311.pyc new file mode 100644 index 0000000..7c73bc0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/venue.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/video.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/video.cpython-311.pyc new file mode 100644 index 0000000..b1a1162 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/video.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_ended.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_ended.cpython-311.pyc new file mode 100644 index 0000000..0530974 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_ended.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_participants_invited.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_participants_invited.cpython-311.pyc new file mode 100644 index 0000000..f6cf48c Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_participants_invited.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_scheduled.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_scheduled.cpython-311.pyc new file mode 100644 index 0000000..a0132f4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_scheduled.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_started.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_started.cpython-311.pyc new file mode 100644 index 0000000..db02603 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/video_chat_started.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/video_note.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/video_note.cpython-311.pyc new file mode 100644 index 0000000..cb6bef1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/video_note.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/voice.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/voice.cpython-311.pyc new file mode 100644 index 0000000..26f4d06 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/voice.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/web_app_data.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/web_app_data.cpython-311.pyc new file mode 100644 index 0000000..0809f0b Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/web_app_data.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/web_app_info.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/web_app_info.cpython-311.pyc new file mode 100644 index 0000000..378c8bc Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/web_app_info.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/webhook_info.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/webhook_info.cpython-311.pyc new file mode 100644 index 0000000..4cef111 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/webhook_info.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/__pycache__/write_access_allowed.cpython-311.pyc b/env/Lib/site-packages/aiogram/types/__pycache__/write_access_allowed.cpython-311.pyc new file mode 100644 index 0000000..c9f9229 Binary files /dev/null and b/env/Lib/site-packages/aiogram/types/__pycache__/write_access_allowed.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/types/animation.py b/env/Lib/site-packages/aiogram/types/animation.py new file mode 100644 index 0000000..1fb45b7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/animation.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class Animation(TelegramObject): + """ + This object represents an animation file (GIF or H.264/MPEG-4 AVC video without sound). + + Source: https://core.telegram.org/bots/api#animation + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + width: int + """Video width as defined by the sender""" + height: int + """Video height as defined by the sender""" + duration: int + """Duration of the video in seconds as defined by the sender""" + thumbnail: Optional[PhotoSize] = None + """*Optional*. Animation thumbnail as defined by the sender""" + file_name: Optional[str] = None + """*Optional*. Original animation filename as defined by the sender""" + mime_type: Optional[str] = None + """*Optional*. MIME type of the file as defined by the sender""" + file_size: Optional[int] = None + """*Optional*. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + width: int, + height: int, + duration: int, + thumbnail: Optional[PhotoSize] = None, + file_name: Optional[str] = None, + mime_type: Optional[str] = None, + file_size: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + width=width, + height=height, + duration=duration, + thumbnail=thumbnail, + file_name=file_name, + mime_type=mime_type, + file_size=file_size, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/audio.py b/env/Lib/site-packages/aiogram/types/audio.py new file mode 100644 index 0000000..8c11412 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/audio.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class Audio(TelegramObject): + """ + This object represents an audio file to be treated as music by the Telegram clients. + + Source: https://core.telegram.org/bots/api#audio + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + duration: int + """Duration of the audio in seconds as defined by the sender""" + performer: Optional[str] = None + """*Optional*. Performer of the audio as defined by the sender or by audio tags""" + title: Optional[str] = None + """*Optional*. Title of the audio as defined by the sender or by audio tags""" + file_name: Optional[str] = None + """*Optional*. Original filename as defined by the sender""" + mime_type: Optional[str] = None + """*Optional*. MIME type of the file as defined by the sender""" + file_size: Optional[int] = None + """*Optional*. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.""" + thumbnail: Optional[PhotoSize] = None + """*Optional*. Thumbnail of the album cover to which the music file belongs""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + duration: int, + performer: Optional[str] = None, + title: Optional[str] = None, + file_name: Optional[str] = None, + mime_type: Optional[str] = None, + file_size: Optional[int] = None, + thumbnail: Optional[PhotoSize] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + duration=duration, + performer=performer, + title=title, + file_name=file_name, + mime_type=mime_type, + file_size=file_size, + thumbnail=thumbnail, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/background_fill.py b/env/Lib/site-packages/aiogram/types/background_fill.py new file mode 100644 index 0000000..dbeda46 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_fill.py @@ -0,0 +1,13 @@ +from .base import TelegramObject + + +class BackgroundFill(TelegramObject): + """ + This object describes the way a background is filled based on the selected colors. Currently, it can be one of + + - :class:`aiogram.types.background_fill_solid.BackgroundFillSolid` + - :class:`aiogram.types.background_fill_gradient.BackgroundFillGradient` + - :class:`aiogram.types.background_fill_freeform_gradient.BackgroundFillFreeformGradient` + + Source: https://core.telegram.org/bots/api#backgroundfill + """ diff --git a/env/Lib/site-packages/aiogram/types/background_fill_freeform_gradient.py b/env/Lib/site-packages/aiogram/types/background_fill_freeform_gradient.py new file mode 100644 index 0000000..916f6a7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_fill_freeform_gradient.py @@ -0,0 +1,33 @@ +from typing import TYPE_CHECKING, Any, List, Literal + +from .background_fill import BackgroundFill + + +class BackgroundFillFreeformGradient(BackgroundFill): + """ + The background is a freeform gradient that rotates after every message in the chat. + + Source: https://core.telegram.org/bots/api#backgroundfillfreeformgradient + """ + + type: Literal["freeform_gradient"] = "freeform_gradient" + """Type of the background fill, always 'freeform_gradient'""" + colors: List[int] + """A list of the 3 or 4 base colors that are used to generate the freeform gradient in the RGB24 format""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal["freeform_gradient"] = "freeform_gradient", + colors: List[int], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, colors=colors, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/background_fill_gradient.py b/env/Lib/site-packages/aiogram/types/background_fill_gradient.py new file mode 100644 index 0000000..abc485c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_fill_gradient.py @@ -0,0 +1,45 @@ +from typing import TYPE_CHECKING, Any, Literal + +from .background_fill import BackgroundFill + + +class BackgroundFillGradient(BackgroundFill): + """ + The background is a gradient fill. + + Source: https://core.telegram.org/bots/api#backgroundfillgradient + """ + + type: Literal["gradient"] = "gradient" + """Type of the background fill, always 'gradient'""" + top_color: int + """Top color of the gradient in the RGB24 format""" + bottom_color: int + """Bottom color of the gradient in the RGB24 format""" + rotation_angle: int + """Clockwise rotation angle of the background fill in degrees; 0-359""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal["gradient"] = "gradient", + top_color: int, + bottom_color: int, + rotation_angle: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + top_color=top_color, + bottom_color=bottom_color, + rotation_angle=rotation_angle, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/background_fill_solid.py b/env/Lib/site-packages/aiogram/types/background_fill_solid.py new file mode 100644 index 0000000..f9fe22f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_fill_solid.py @@ -0,0 +1,33 @@ +from typing import TYPE_CHECKING, Any, Literal + +from .background_fill import BackgroundFill + + +class BackgroundFillSolid(BackgroundFill): + """ + The background is filled using the selected color. + + Source: https://core.telegram.org/bots/api#backgroundfillsolid + """ + + type: Literal["solid"] = "solid" + """Type of the background fill, always 'solid'""" + color: int + """The color of the background fill in the RGB24 format""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal["solid"] = "solid", + color: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, color=color, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/background_type.py b/env/Lib/site-packages/aiogram/types/background_type.py new file mode 100644 index 0000000..6abccef --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_type.py @@ -0,0 +1,14 @@ +from .base import TelegramObject + + +class BackgroundType(TelegramObject): + """ + This object describes the type of a background. Currently, it can be one of + + - :class:`aiogram.types.background_type_fill.BackgroundTypeFill` + - :class:`aiogram.types.background_type_wallpaper.BackgroundTypeWallpaper` + - :class:`aiogram.types.background_type_pattern.BackgroundTypePattern` + - :class:`aiogram.types.background_type_chat_theme.BackgroundTypeChatTheme` + + Source: https://core.telegram.org/bots/api#backgroundtype + """ diff --git a/env/Lib/site-packages/aiogram/types/background_type_chat_theme.py b/env/Lib/site-packages/aiogram/types/background_type_chat_theme.py new file mode 100644 index 0000000..ac93534 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_type_chat_theme.py @@ -0,0 +1,33 @@ +from typing import TYPE_CHECKING, Any, Literal + +from .background_type import BackgroundType + + +class BackgroundTypeChatTheme(BackgroundType): + """ + The background is taken directly from a built-in chat theme. + + Source: https://core.telegram.org/bots/api#backgroundtypechattheme + """ + + type: Literal["chat_theme"] = "chat_theme" + """Type of the background, always 'chat_theme'""" + theme_name: str + """Name of the chat theme, which is usually an emoji""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal["chat_theme"] = "chat_theme", + theme_name: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, theme_name=theme_name, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/background_type_fill.py b/env/Lib/site-packages/aiogram/types/background_type_fill.py new file mode 100644 index 0000000..c506e4e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_type_fill.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Union + +from .background_type import BackgroundType + +if TYPE_CHECKING: + from .background_fill_freeform_gradient import BackgroundFillFreeformGradient + from .background_fill_gradient import BackgroundFillGradient + from .background_fill_solid import BackgroundFillSolid + + +class BackgroundTypeFill(BackgroundType): + """ + The background is automatically filled based on the selected colors. + + Source: https://core.telegram.org/bots/api#backgroundtypefill + """ + + type: Literal["fill"] = "fill" + """Type of the background, always 'fill'""" + fill: Union[BackgroundFillSolid, BackgroundFillGradient, BackgroundFillFreeformGradient] + """The background fill""" + dark_theme_dimming: int + """Dimming of the background in dark themes, as a percentage; 0-100""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal["fill"] = "fill", + fill: Union[ + BackgroundFillSolid, BackgroundFillGradient, BackgroundFillFreeformGradient + ], + dark_theme_dimming: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, fill=fill, dark_theme_dimming=dark_theme_dimming, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/background_type_pattern.py b/env/Lib/site-packages/aiogram/types/background_type_pattern.py new file mode 100644 index 0000000..29c383c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_type_pattern.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from .background_type import BackgroundType + +if TYPE_CHECKING: + from .background_fill_freeform_gradient import BackgroundFillFreeformGradient + from .background_fill_gradient import BackgroundFillGradient + from .background_fill_solid import BackgroundFillSolid + from .document import Document + + +class BackgroundTypePattern(BackgroundType): + """ + The background is a PNG or TGV (gzipped subset of SVG with MIME type 'application/x-tgwallpattern') pattern to be combined with the background fill chosen by the user. + + Source: https://core.telegram.org/bots/api#backgroundtypepattern + """ + + type: Literal["pattern"] = "pattern" + """Type of the background, always 'pattern'""" + document: Document + """Document with the pattern""" + fill: Union[BackgroundFillSolid, BackgroundFillGradient, BackgroundFillFreeformGradient] + """The background fill that is combined with the pattern""" + intensity: int + """Intensity of the pattern when it is shown above the filled background; 0-100""" + is_inverted: Optional[bool] = None + """*Optional*. :code:`True`, if the background fill must be applied only to the pattern itself. All other pixels are black in this case. For dark themes only""" + is_moving: Optional[bool] = None + """*Optional*. :code:`True`, if the background moves slightly when the device is tilted""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal["pattern"] = "pattern", + document: Document, + fill: Union[ + BackgroundFillSolid, BackgroundFillGradient, BackgroundFillFreeformGradient + ], + intensity: int, + is_inverted: Optional[bool] = None, + is_moving: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + document=document, + fill=fill, + intensity=intensity, + is_inverted=is_inverted, + is_moving=is_moving, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/background_type_wallpaper.py b/env/Lib/site-packages/aiogram/types/background_type_wallpaper.py new file mode 100644 index 0000000..4ad2905 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/background_type_wallpaper.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from .background_type import BackgroundType + +if TYPE_CHECKING: + from .document import Document + + +class BackgroundTypeWallpaper(BackgroundType): + """ + The background is a wallpaper in the JPEG format. + + Source: https://core.telegram.org/bots/api#backgroundtypewallpaper + """ + + type: Literal["wallpaper"] = "wallpaper" + """Type of the background, always 'wallpaper'""" + document: Document + """Document with the wallpaper""" + dark_theme_dimming: int + """Dimming of the background in dark themes, as a percentage; 0-100""" + is_blurred: Optional[bool] = None + """*Optional*. :code:`True`, if the wallpaper is downscaled to fit in a 450x450 square and then box-blurred with radius 12""" + is_moving: Optional[bool] = None + """*Optional*. :code:`True`, if the background moves slightly when the device is tilted""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal["wallpaper"] = "wallpaper", + document: Document, + dark_theme_dimming: int, + is_blurred: Optional[bool] = None, + is_moving: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + document=document, + dark_theme_dimming=dark_theme_dimming, + is_blurred=is_blurred, + is_moving=is_moving, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/base.py b/env/Lib/site-packages/aiogram/types/base.py new file mode 100644 index 0000000..7ae0052 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/base.py @@ -0,0 +1,51 @@ +from typing import Any, Dict +from unittest.mock import sentinel + +from pydantic import BaseModel, ConfigDict, model_validator + +from aiogram.client.context_controller import BotContextController +from aiogram.client.default import Default + + +class TelegramObject(BotContextController, BaseModel): + model_config = ConfigDict( + use_enum_values=True, + extra="allow", + validate_assignment=True, + frozen=True, + populate_by_name=True, + arbitrary_types_allowed=True, + defer_build=True, + ) + + @model_validator(mode="before") + @classmethod + def remove_unset(cls, values: Dict[str, Any]) -> Dict[str, Any]: + """ + Remove UNSET before fields validation. + + We use UNSET as a sentinel value for `parse_mode` and replace it to real value later. + It isn't a problem when it's just default value for a model field, + but UNSET might be passed to a model initialization from `Bot.method_name`, + so we must take care of it and remove it before fields validation. + """ + if not isinstance(values, dict): + return values + return {k: v for k, v in values.items() if not isinstance(v, UNSET_TYPE)} + + +class MutableTelegramObject(TelegramObject): + model_config = ConfigDict( + frozen=False, + ) + + +# special sentinel object which used in a situation when None might be a useful value +UNSET: Any = sentinel.UNSET +UNSET_TYPE: Any = type(UNSET) + +# Unused constants are needed only for backward compatibility with external +# libraries that a working with framework internals +UNSET_PARSE_MODE: Any = Default("parse_mode") +UNSET_DISABLE_WEB_PAGE_PREVIEW: Any = Default("link_preview_is_disabled") +UNSET_PROTECT_CONTENT: Any = Default("protect_content") diff --git a/env/Lib/site-packages/aiogram/types/birthdate.py b/env/Lib/site-packages/aiogram/types/birthdate.py new file mode 100644 index 0000000..6955554 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/birthdate.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class Birthdate(TelegramObject): + """ + Describes the birthdate of a user. + + Source: https://core.telegram.org/bots/api#birthdate + """ + + day: int + """Day of the user's birth; 1-31""" + month: int + """Month of the user's birth; 1-12""" + year: Optional[int] = None + """*Optional*. Year of the user's birth""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + day: int, + month: int, + year: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(day=day, month=month, year=year, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_command.py b/env/Lib/site-packages/aiogram/types/bot_command.py new file mode 100644 index 0000000..e4e9175 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import MutableTelegramObject + + +class BotCommand(MutableTelegramObject): + """ + This object represents a bot command. + + Source: https://core.telegram.org/bots/api#botcommand + """ + + command: str + """Text of the command; 1-32 characters. Can contain only lowercase English letters, digits and underscores.""" + description: str + """Description of the command; 1-256 characters.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, command: str, description: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(command=command, description=description, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_command_scope.py b/env/Lib/site-packages/aiogram/types/bot_command_scope.py new file mode 100644 index 0000000..dfb1d52 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command_scope.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from .base import TelegramObject + + +class BotCommandScope(TelegramObject): + """ + This object represents the scope to which bot commands are applied. Currently, the following 7 scopes are supported: + + - :class:`aiogram.types.bot_command_scope_default.BotCommandScopeDefault` + - :class:`aiogram.types.bot_command_scope_all_private_chats.BotCommandScopeAllPrivateChats` + - :class:`aiogram.types.bot_command_scope_all_group_chats.BotCommandScopeAllGroupChats` + - :class:`aiogram.types.bot_command_scope_all_chat_administrators.BotCommandScopeAllChatAdministrators` + - :class:`aiogram.types.bot_command_scope_chat.BotCommandScopeChat` + - :class:`aiogram.types.bot_command_scope_chat_administrators.BotCommandScopeChatAdministrators` + - :class:`aiogram.types.bot_command_scope_chat_member.BotCommandScopeChatMember` + + Source: https://core.telegram.org/bots/api#botcommandscope + """ diff --git a/env/Lib/site-packages/aiogram/types/bot_command_scope_all_chat_administrators.py b/env/Lib/site-packages/aiogram/types/bot_command_scope_all_chat_administrators.py new file mode 100644 index 0000000..4417363 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command_scope_all_chat_administrators.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import BotCommandScopeType +from .bot_command_scope import BotCommandScope + + +class BotCommandScopeAllChatAdministrators(BotCommandScope): + """ + Represents the `scope `_ of bot commands, covering all group and supergroup chat administrators. + + Source: https://core.telegram.org/bots/api#botcommandscopeallchatadministrators + """ + + type: Literal[BotCommandScopeType.ALL_CHAT_ADMINISTRATORS] = ( + BotCommandScopeType.ALL_CHAT_ADMINISTRATORS + ) + """Scope type, must be *all_chat_administrators*""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[ + BotCommandScopeType.ALL_CHAT_ADMINISTRATORS + ] = BotCommandScopeType.ALL_CHAT_ADMINISTRATORS, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_command_scope_all_group_chats.py b/env/Lib/site-packages/aiogram/types/bot_command_scope_all_group_chats.py new file mode 100644 index 0000000..a17a51d --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command_scope_all_group_chats.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import BotCommandScopeType +from .bot_command_scope import BotCommandScope + + +class BotCommandScopeAllGroupChats(BotCommandScope): + """ + Represents the `scope `_ of bot commands, covering all group and supergroup chats. + + Source: https://core.telegram.org/bots/api#botcommandscopeallgroupchats + """ + + type: Literal[BotCommandScopeType.ALL_GROUP_CHATS] = BotCommandScopeType.ALL_GROUP_CHATS + """Scope type, must be *all_group_chats*""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[ + BotCommandScopeType.ALL_GROUP_CHATS + ] = BotCommandScopeType.ALL_GROUP_CHATS, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_command_scope_all_private_chats.py b/env/Lib/site-packages/aiogram/types/bot_command_scope_all_private_chats.py new file mode 100644 index 0000000..54d406f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command_scope_all_private_chats.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import BotCommandScopeType +from .bot_command_scope import BotCommandScope + + +class BotCommandScopeAllPrivateChats(BotCommandScope): + """ + Represents the `scope `_ of bot commands, covering all private chats. + + Source: https://core.telegram.org/bots/api#botcommandscopeallprivatechats + """ + + type: Literal[BotCommandScopeType.ALL_PRIVATE_CHATS] = BotCommandScopeType.ALL_PRIVATE_CHATS + """Scope type, must be *all_private_chats*""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[ + BotCommandScopeType.ALL_PRIVATE_CHATS + ] = BotCommandScopeType.ALL_PRIVATE_CHATS, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_command_scope_chat.py b/env/Lib/site-packages/aiogram/types/bot_command_scope_chat.py new file mode 100644 index 0000000..f36c4a1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command_scope_chat.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Union + +from ..enums import BotCommandScopeType +from .bot_command_scope import BotCommandScope + + +class BotCommandScopeChat(BotCommandScope): + """ + Represents the `scope `_ of bot commands, covering a specific chat. + + Source: https://core.telegram.org/bots/api#botcommandscopechat + """ + + type: Literal[BotCommandScopeType.CHAT] = BotCommandScopeType.CHAT + """Scope type, must be *chat*""" + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[BotCommandScopeType.CHAT] = BotCommandScopeType.CHAT, + chat_id: Union[int, str], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_command_scope_chat_administrators.py b/env/Lib/site-packages/aiogram/types/bot_command_scope_chat_administrators.py new file mode 100644 index 0000000..f90623e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command_scope_chat_administrators.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Union + +from ..enums import BotCommandScopeType +from .bot_command_scope import BotCommandScope + + +class BotCommandScopeChatAdministrators(BotCommandScope): + """ + Represents the `scope `_ of bot commands, covering all administrators of a specific group or supergroup chat. + + Source: https://core.telegram.org/bots/api#botcommandscopechatadministrators + """ + + type: Literal[BotCommandScopeType.CHAT_ADMINISTRATORS] = ( + BotCommandScopeType.CHAT_ADMINISTRATORS + ) + """Scope type, must be *chat_administrators*""" + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[ + BotCommandScopeType.CHAT_ADMINISTRATORS + ] = BotCommandScopeType.CHAT_ADMINISTRATORS, + chat_id: Union[int, str], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, chat_id=chat_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_command_scope_chat_member.py b/env/Lib/site-packages/aiogram/types/bot_command_scope_chat_member.py new file mode 100644 index 0000000..4d20b1f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command_scope_chat_member.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Union + +from ..enums import BotCommandScopeType +from .bot_command_scope import BotCommandScope + + +class BotCommandScopeChatMember(BotCommandScope): + """ + Represents the `scope `_ of bot commands, covering a specific member of a group or supergroup chat. + + Source: https://core.telegram.org/bots/api#botcommandscopechatmember + """ + + type: Literal[BotCommandScopeType.CHAT_MEMBER] = BotCommandScopeType.CHAT_MEMBER + """Scope type, must be *chat_member*""" + chat_id: Union[int, str] + """Unique identifier for the target chat or username of the target supergroup (in the format :code:`@supergroupusername`)""" + user_id: int + """Unique identifier of the target user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[BotCommandScopeType.CHAT_MEMBER] = BotCommandScopeType.CHAT_MEMBER, + chat_id: Union[int, str], + user_id: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, chat_id=chat_id, user_id=user_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_command_scope_default.py b/env/Lib/site-packages/aiogram/types/bot_command_scope_default.py new file mode 100644 index 0000000..33b7a0c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_command_scope_default.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import BotCommandScopeType +from .bot_command_scope import BotCommandScope + + +class BotCommandScopeDefault(BotCommandScope): + """ + Represents the default `scope `_ of bot commands. Default commands are used if no commands with a `narrower scope `_ are specified for the user. + + Source: https://core.telegram.org/bots/api#botcommandscopedefault + """ + + type: Literal[BotCommandScopeType.DEFAULT] = BotCommandScopeType.DEFAULT + """Scope type, must be *default*""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[BotCommandScopeType.DEFAULT] = BotCommandScopeType.DEFAULT, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_description.py b/env/Lib/site-packages/aiogram/types/bot_description.py new file mode 100644 index 0000000..5d8646d --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_description.py @@ -0,0 +1,25 @@ +from typing import TYPE_CHECKING, Any + +from aiogram.types import TelegramObject + + +class BotDescription(TelegramObject): + """ + This object represents the bot's description. + + Source: https://core.telegram.org/bots/api#botdescription + """ + + description: str + """The bot's description""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, description: str, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(description=description, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_name.py b/env/Lib/site-packages/aiogram/types/bot_name.py new file mode 100644 index 0000000..f2dc074 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_name.py @@ -0,0 +1,25 @@ +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class BotName(TelegramObject): + """ + This object represents the bot's name. + + Source: https://core.telegram.org/bots/api#botname + """ + + name: str + """The bot's name""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, name: str, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(name=name, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/bot_short_description.py b/env/Lib/site-packages/aiogram/types/bot_short_description.py new file mode 100644 index 0000000..86b11cf --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/bot_short_description.py @@ -0,0 +1,27 @@ +from typing import TYPE_CHECKING, Any + +from aiogram.types import TelegramObject + + +class BotShortDescription(TelegramObject): + """ + This object represents the bot's short description. + + Source: https://core.telegram.org/bots/api#botshortdescription + """ + + short_description: str + """The bot's short description""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, short_description: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(short_description=short_description, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/business_connection.py b/env/Lib/site-packages/aiogram/types/business_connection.py new file mode 100644 index 0000000..80c472a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/business_connection.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from .user import User + + +class BusinessConnection(TelegramObject): + """ + Describes the connection of the bot with a business account. + + Source: https://core.telegram.org/bots/api#businessconnection + """ + + id: str + """Unique identifier of the business connection""" + user: User + """Business account user that created the business connection""" + user_chat_id: int + """Identifier of a private chat with the user who created the business connection. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.""" + date: DateTime + """Date the connection was established in Unix time""" + can_reply: bool + """True, if the bot can act on behalf of the business account in chats that were active in the last 24 hours""" + is_enabled: bool + """True, if the connection is active""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: str, + user: User, + user_chat_id: int, + date: DateTime, + can_reply: bool, + is_enabled: bool, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + user=user, + user_chat_id=user_chat_id, + date=date, + can_reply=can_reply, + is_enabled=is_enabled, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/business_intro.py b/env/Lib/site-packages/aiogram/types/business_intro.py new file mode 100644 index 0000000..c360fbe --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/business_intro.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .sticker import Sticker + + +class BusinessIntro(TelegramObject): + """ + Contains information about the start page settings of a Telegram Business account. + + Source: https://core.telegram.org/bots/api#businessintro + """ + + title: Optional[str] = None + """*Optional*. Title text of the business intro""" + message: Optional[str] = None + """*Optional*. Message text of the business intro""" + sticker: Optional[Sticker] = None + """*Optional*. Sticker of the business intro""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + title: Optional[str] = None, + message: Optional[str] = None, + sticker: Optional[Sticker] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(title=title, message=message, sticker=sticker, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/business_location.py b/env/Lib/site-packages/aiogram/types/business_location.py new file mode 100644 index 0000000..af7989a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/business_location.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .location import Location + + +class BusinessLocation(TelegramObject): + """ + Contains information about the location of a Telegram Business account. + + Source: https://core.telegram.org/bots/api#businesslocation + """ + + address: str + """Address of the business""" + location: Optional[Location] = None + """*Optional*. Location of the business""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + address: str, + location: Optional[Location] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(address=address, location=location, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/business_messages_deleted.py b/env/Lib/site-packages/aiogram/types/business_messages_deleted.py new file mode 100644 index 0000000..44bc45f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/business_messages_deleted.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat import Chat + + +class BusinessMessagesDeleted(TelegramObject): + """ + This object is received when messages are deleted from a connected business account. + + Source: https://core.telegram.org/bots/api#businessmessagesdeleted + """ + + business_connection_id: str + """Unique identifier of the business connection""" + chat: Chat + """Information about a chat in the business account. The bot may not have access to the chat or the corresponding user.""" + message_ids: List[int] + """The list of identifiers of deleted messages in the chat of the business account""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + business_connection_id: str, + chat: Chat, + message_ids: List[int], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + business_connection_id=business_connection_id, + chat=chat, + message_ids=message_ids, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/business_opening_hours.py b/env/Lib/site-packages/aiogram/types/business_opening_hours.py new file mode 100644 index 0000000..7fd5c75 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/business_opening_hours.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .business_opening_hours_interval import BusinessOpeningHoursInterval + + +class BusinessOpeningHours(TelegramObject): + """ + Describes the opening hours of a business. + + Source: https://core.telegram.org/bots/api#businessopeninghours + """ + + time_zone_name: str + """Unique name of the time zone for which the opening hours are defined""" + opening_hours: List[BusinessOpeningHoursInterval] + """List of time intervals describing business opening hours""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + time_zone_name: str, + opening_hours: List[BusinessOpeningHoursInterval], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + time_zone_name=time_zone_name, opening_hours=opening_hours, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/business_opening_hours_interval.py b/env/Lib/site-packages/aiogram/types/business_opening_hours_interval.py new file mode 100644 index 0000000..52efd2c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/business_opening_hours_interval.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class BusinessOpeningHoursInterval(TelegramObject): + """ + Describes an interval of time during which a business is open. + + Source: https://core.telegram.org/bots/api#businessopeninghoursinterval + """ + + opening_minute: int + """The minute's sequence number in a week, starting on Monday, marking the start of the time interval during which the business is open; 0 - 7 * 24 * 60""" + closing_minute: int + """The minute's sequence number in a week, starting on Monday, marking the end of the time interval during which the business is open; 0 - 8 * 24 * 60""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + opening_minute: int, + closing_minute: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + opening_minute=opening_minute, closing_minute=closing_minute, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/callback_game.py b/env/Lib/site-packages/aiogram/types/callback_game.py new file mode 100644 index 0000000..6d8c556 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/callback_game.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from .base import TelegramObject + + +class CallbackGame(TelegramObject): + """ + A placeholder, currently holds no information. Use `BotFather `_ to set up your game. + + Source: https://core.telegram.org/bots/api#callbackgame + """ diff --git a/env/Lib/site-packages/aiogram/types/callback_query.py b/env/Lib/site-packages/aiogram/types/callback_query.py new file mode 100644 index 0000000..c3b33b5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/callback_query.py @@ -0,0 +1,109 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from pydantic import Field + +from .base import TelegramObject + +if TYPE_CHECKING: + from ..methods import AnswerCallbackQuery + from .inaccessible_message import InaccessibleMessage + from .message import Message + from .user import User + + +class CallbackQuery(TelegramObject): + """ + This object represents an incoming callback query from a callback button in an `inline keyboard `_. If the button that originated the query was attached to a message sent by the bot, the field *message* will be present. If the button was attached to a message sent via the bot (in `inline mode `_), the field *inline_message_id* will be present. Exactly one of the fields *data* or *game_short_name* will be present. + + **NOTE:** After the user presses a callback button, Telegram clients will display a progress bar until you call :class:`aiogram.methods.answer_callback_query.AnswerCallbackQuery`. It is, therefore, necessary to react by calling :class:`aiogram.methods.answer_callback_query.AnswerCallbackQuery` even if no notification to the user is needed (e.g., without specifying any of the optional parameters). + + Source: https://core.telegram.org/bots/api#callbackquery + """ + + id: str + """Unique identifier for this query""" + from_user: User = Field(..., alias="from") + """Sender""" + chat_instance: str + """Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent. Useful for high scores in :class:`aiogram.methods.games.Games`.""" + message: Optional[Union[Message, InaccessibleMessage]] = None + """*Optional*. Message sent by the bot with the callback button that originated the query""" + inline_message_id: Optional[str] = None + """*Optional*. Identifier of the message sent via the bot in inline mode, that originated the query.""" + data: Optional[str] = None + """*Optional*. Data associated with the callback button. Be aware that the message originated the query can contain no callback buttons with this data.""" + game_short_name: Optional[str] = None + """*Optional*. Short name of a `Game `_ to be returned, serves as the unique identifier for the game""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: str, + from_user: User, + chat_instance: str, + message: Optional[Union[Message, InaccessibleMessage]] = None, + inline_message_id: Optional[str] = None, + data: Optional[str] = None, + game_short_name: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + from_user=from_user, + chat_instance=chat_instance, + message=message, + inline_message_id=inline_message_id, + data=data, + game_short_name=game_short_name, + **__pydantic_kwargs, + ) + + def answer( + self, + text: Optional[str] = None, + show_alert: Optional[bool] = None, + url: Optional[str] = None, + cache_time: Optional[int] = None, + **kwargs: Any, + ) -> AnswerCallbackQuery: + """ + Shortcut for method :class:`aiogram.methods.answer_callback_query.AnswerCallbackQuery` + will automatically fill method attributes: + + - :code:`callback_query_id` + + Use this method to send answers to callback queries sent from `inline keyboards `_. The answer will be displayed to the user as a notification at the top of the chat screen or as an alert. On success, :code:`True` is returned. + + Alternatively, the user can be redirected to the specified Game URL. For this option to work, you must first create a game for your bot via `@BotFather `_ and accept the terms. Otherwise, you may use links like :code:`t.me/your_bot?start=XXXX` that open your bot with a parameter. + + Source: https://core.telegram.org/bots/api#answercallbackquery + + :param text: Text of the notification. If not specified, nothing will be shown to the user, 0-200 characters + :param show_alert: If :code:`True`, an alert will be shown by the client instead of a notification at the top of the chat screen. Defaults to *false*. + :param url: URL that will be opened by the user's client. If you have created a :class:`aiogram.types.game.Game` and accepted the conditions via `@BotFather `_, specify the URL that opens your game - note that this will only work if the query comes from a `https://core.telegram.org/bots/api#inlinekeyboardbutton `_ *callback_game* button. + :param cache_time: The maximum amount of time in seconds that the result of the callback query may be cached client-side. Telegram apps will support caching starting in version 3.14. Defaults to 0. + :return: instance of method :class:`aiogram.methods.answer_callback_query.AnswerCallbackQuery` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import AnswerCallbackQuery + + return AnswerCallbackQuery( + callback_query_id=self.id, + text=text, + show_alert=show_alert, + url=url, + cache_time=cache_time, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/chat.py b/env/Lib/site-packages/aiogram/types/chat.py new file mode 100644 index 0000000..c4feba4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat.py @@ -0,0 +1,1320 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from ..methods import ( + BanChatMember, + BanChatSenderChat, + CreateChatInviteLink, + DeleteChatPhoto, + DeleteChatStickerSet, + DeleteMessage, + EditChatInviteLink, + ExportChatInviteLink, + GetChatAdministrators, + GetChatMember, + GetChatMemberCount, + LeaveChat, + PinChatMessage, + PromoteChatMember, + RestrictChatMember, + RevokeChatInviteLink, + SendChatAction, + SetChatAdministratorCustomTitle, + SetChatDescription, + SetChatPermissions, + SetChatPhoto, + SetChatStickerSet, + SetChatTitle, + UnbanChatMember, + UnbanChatSenderChat, + UnpinAllChatMessages, + UnpinAllGeneralForumTopicMessages, + UnpinChatMessage, + ) + from .birthdate import Birthdate + from .business_intro import BusinessIntro + from .business_location import BusinessLocation + from .business_opening_hours import BusinessOpeningHours + from .chat_location import ChatLocation + from .chat_permissions import ChatPermissions + from .chat_photo import ChatPhoto + from .input_file import InputFile + from .message import Message + from .reaction_type_custom_emoji import ReactionTypeCustomEmoji + from .reaction_type_emoji import ReactionTypeEmoji + from .reaction_type_paid import ReactionTypePaid + + +class Chat(TelegramObject): + """ + This object represents a chat. + + Source: https://core.telegram.org/bots/api#chat + """ + + id: int + """Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.""" + type: str + """Type of the chat, can be either 'private', 'group', 'supergroup' or 'channel'""" + title: Optional[str] = None + """*Optional*. Title, for supergroups, channels and group chats""" + username: Optional[str] = None + """*Optional*. Username, for private chats, supergroups and channels if available""" + first_name: Optional[str] = None + """*Optional*. First name of the other party in a private chat""" + last_name: Optional[str] = None + """*Optional*. Last name of the other party in a private chat""" + is_forum: Optional[bool] = None + """*Optional*. :code:`True`, if the supergroup chat is a forum (has `topics `_ enabled)""" + accent_color_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Identifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See `accent colors `_ for more details. Returned only in :class:`aiogram.methods.get_chat.GetChat`. Always returned in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + active_usernames: Optional[List[str]] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. If non-empty, the list of all `active chat usernames `_; for private chats, supergroups and channels. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + available_reactions: Optional[ + List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + ] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. List of available reactions allowed in the chat. If omitted, then all `emoji reactions `_ are allowed. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + background_custom_emoji_id: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Custom emoji identifier of emoji chosen by the chat for the reply header and link preview background. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + bio: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Bio of the other party in a private chat. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + birthdate: Optional[Birthdate] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For private chats, the date of birth of the user. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + business_intro: Optional[BusinessIntro] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For private chats with business accounts, the intro of the business. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + business_location: Optional[BusinessLocation] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional*. For private chats with business accounts, the location of the business. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + business_opening_hours: Optional[BusinessOpeningHours] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional*. For private chats with business accounts, the opening hours of the business. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + can_set_sticker_set: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. :code:`True`, if the bot can change the group sticker set. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + custom_emoji_sticker_set_name: Optional[str] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional*. For supergroups, the name of the group's custom emoji sticker set. Custom emoji from this set can be used by all users and bots in the group. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + description: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Description, for groups, supergroups and channel chats. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + emoji_status_custom_emoji_id: Optional[str] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional*. Custom emoji identifier of the emoji status of the chat or the other party in a private chat. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + emoji_status_expiration_date: Optional[DateTime] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional*. Expiration date of the emoji status of the chat or the other party in a private chat, in Unix time, if any. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + has_aggressive_anti_spam_enabled: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional*. :code:`True`, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + has_hidden_members: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. :code:`True`, if non-administrators can only get the list of bots and administrators in the chat. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + has_private_forwards: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. :code:`True`, if privacy settings of the other party in the private chat allows to use :code:`tg://user?id=` links only in chats with the user. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + has_protected_content: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. :code:`True`, if messages from the chat can't be forwarded to other chats. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + has_restricted_voice_and_video_messages: Optional[bool] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional*. :code:`True`, if the privacy settings of the other party restrict sending voice and video note messages in the private chat. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + has_visible_history: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. :code:`True`, if new chat members will have access to old messages; available only to chat administrators. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + invite_link: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Primary invite link, for groups, supergroups and channel chats. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + join_by_request: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. :code:`True`, if all users directly joining the supergroup need to be approved by supergroup administrators. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + join_to_send_messages: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. :code:`True`, if users need to join the supergroup before they can send messages. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + linked_chat_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + location: Optional[ChatLocation] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For supergroups, the location to which the supergroup is connected. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + message_auto_delete_time: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. The time after which all messages sent to the chat will be automatically deleted; in seconds. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + permissions: Optional[ChatPermissions] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Default chat member permissions, for groups and supergroups. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + personal_chat: Optional[Chat] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For private chats, the personal channel of the user. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + photo: Optional[ChatPhoto] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Chat photo. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + pinned_message: Optional[Message] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. The most recent pinned message (by sending date). Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + profile_accent_color_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Identifier of the accent color for the chat's profile background. See `profile accent colors `_ for more details. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + profile_background_custom_emoji_id: Optional[str] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional*. Custom emoji identifier of the emoji chosen by the chat for its profile background. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + slow_mode_delay: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user; in seconds. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + sticker_set_name: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For supergroups, name of group sticker set. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + unrestrict_boost_count: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For supergroups, the minimum number of boosts that a non-administrator user needs to add in order to ignore slow mode and chat permissions. Returned only in :class:`aiogram.methods.get_chat.GetChat`. + +.. deprecated:: API:7.3 + https://core.telegram.org/bots/api-changelog#may-6-2024""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: int, + type: str, + title: Optional[str] = None, + username: Optional[str] = None, + first_name: Optional[str] = None, + last_name: Optional[str] = None, + is_forum: Optional[bool] = None, + accent_color_id: Optional[int] = None, + active_usernames: Optional[List[str]] = None, + available_reactions: Optional[ + List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + ] = None, + background_custom_emoji_id: Optional[str] = None, + bio: Optional[str] = None, + birthdate: Optional[Birthdate] = None, + business_intro: Optional[BusinessIntro] = None, + business_location: Optional[BusinessLocation] = None, + business_opening_hours: Optional[BusinessOpeningHours] = None, + can_set_sticker_set: Optional[bool] = None, + custom_emoji_sticker_set_name: Optional[str] = None, + description: Optional[str] = None, + emoji_status_custom_emoji_id: Optional[str] = None, + emoji_status_expiration_date: Optional[DateTime] = None, + has_aggressive_anti_spam_enabled: Optional[bool] = None, + has_hidden_members: Optional[bool] = None, + has_private_forwards: Optional[bool] = None, + has_protected_content: Optional[bool] = None, + has_restricted_voice_and_video_messages: Optional[bool] = None, + has_visible_history: Optional[bool] = None, + invite_link: Optional[str] = None, + join_by_request: Optional[bool] = None, + join_to_send_messages: Optional[bool] = None, + linked_chat_id: Optional[int] = None, + location: Optional[ChatLocation] = None, + message_auto_delete_time: Optional[int] = None, + permissions: Optional[ChatPermissions] = None, + personal_chat: Optional[Chat] = None, + photo: Optional[ChatPhoto] = None, + pinned_message: Optional[Message] = None, + profile_accent_color_id: Optional[int] = None, + profile_background_custom_emoji_id: Optional[str] = None, + slow_mode_delay: Optional[int] = None, + sticker_set_name: Optional[str] = None, + unrestrict_boost_count: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + type=type, + title=title, + username=username, + first_name=first_name, + last_name=last_name, + is_forum=is_forum, + accent_color_id=accent_color_id, + active_usernames=active_usernames, + available_reactions=available_reactions, + background_custom_emoji_id=background_custom_emoji_id, + bio=bio, + birthdate=birthdate, + business_intro=business_intro, + business_location=business_location, + business_opening_hours=business_opening_hours, + can_set_sticker_set=can_set_sticker_set, + custom_emoji_sticker_set_name=custom_emoji_sticker_set_name, + description=description, + emoji_status_custom_emoji_id=emoji_status_custom_emoji_id, + emoji_status_expiration_date=emoji_status_expiration_date, + has_aggressive_anti_spam_enabled=has_aggressive_anti_spam_enabled, + has_hidden_members=has_hidden_members, + has_private_forwards=has_private_forwards, + has_protected_content=has_protected_content, + has_restricted_voice_and_video_messages=has_restricted_voice_and_video_messages, + has_visible_history=has_visible_history, + invite_link=invite_link, + join_by_request=join_by_request, + join_to_send_messages=join_to_send_messages, + linked_chat_id=linked_chat_id, + location=location, + message_auto_delete_time=message_auto_delete_time, + permissions=permissions, + personal_chat=personal_chat, + photo=photo, + pinned_message=pinned_message, + profile_accent_color_id=profile_accent_color_id, + profile_background_custom_emoji_id=profile_background_custom_emoji_id, + slow_mode_delay=slow_mode_delay, + sticker_set_name=sticker_set_name, + unrestrict_boost_count=unrestrict_boost_count, + **__pydantic_kwargs, + ) + + @property + def shifted_id(self) -> int: + """ + Returns shifted chat ID (positive and without "-100" prefix). + Mostly used for private links like t.me/c/chat_id/message_id + + Currently supergroup/channel IDs have 10-digit ID after "-100" prefix removed. + However, these IDs might become 11-digit in future. So, first we remove "-100" + prefix and count remaining number length. Then we multiple + -1 * 10 ^ (number_length + 2) + Finally, self.id is substracted from that number + """ + short_id = str(self.id).replace("-100", "") + shift = int(-1 * pow(10, len(short_id) + 2)) + return shift - self.id + + @property + def full_name(self) -> str: + """Get full name of the Chat. + + For private chat it is first_name + last_name. + For other chat types it is title. + """ + if self.title is not None: + return self.title + + if self.last_name is not None: + return f"{self.first_name} {self.last_name}" + + return f"{self.first_name}" + + def ban_sender_chat( + self, + sender_chat_id: int, + **kwargs: Any, + ) -> BanChatSenderChat: + """ + Shortcut for method :class:`aiogram.methods.ban_chat_sender_chat.BanChatSenderChat` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to ban a channel chat in a supergroup or a channel. Until the chat is `unbanned `_, the owner of the banned chat won't be able to send messages on behalf of **any of their channels**. The bot must be an administrator in the supergroup or channel for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#banchatsenderchat + + :param sender_chat_id: Unique identifier of the target sender chat + :return: instance of method :class:`aiogram.methods.ban_chat_sender_chat.BanChatSenderChat` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import BanChatSenderChat + + return BanChatSenderChat( + chat_id=self.id, + sender_chat_id=sender_chat_id, + **kwargs, + ).as_(self._bot) + + def unban_sender_chat( + self, + sender_chat_id: int, + **kwargs: Any, + ) -> UnbanChatSenderChat: + """ + Shortcut for method :class:`aiogram.methods.unban_chat_sender_chat.UnbanChatSenderChat` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to unban a previously banned channel chat in a supergroup or channel. The bot must be an administrator for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unbanchatsenderchat + + :param sender_chat_id: Unique identifier of the target sender chat + :return: instance of method :class:`aiogram.methods.unban_chat_sender_chat.UnbanChatSenderChat` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import UnbanChatSenderChat + + return UnbanChatSenderChat( + chat_id=self.id, + sender_chat_id=sender_chat_id, + **kwargs, + ).as_(self._bot) + + def get_administrators( + self, + **kwargs: Any, + ) -> GetChatAdministrators: + """ + Shortcut for method :class:`aiogram.methods.get_chat_administrators.GetChatAdministrators` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to get a list of administrators in a chat, which aren't bots. Returns an Array of :class:`aiogram.types.chat_member.ChatMember` objects. + + Source: https://core.telegram.org/bots/api#getchatadministrators + + :return: instance of method :class:`aiogram.methods.get_chat_administrators.GetChatAdministrators` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import GetChatAdministrators + + return GetChatAdministrators( + chat_id=self.id, + **kwargs, + ).as_(self._bot) + + def delete_message( + self, + message_id: int, + **kwargs: Any, + ) -> DeleteMessage: + """ + Shortcut for method :class:`aiogram.methods.delete_message.DeleteMessage` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to delete a message, including service messages, with the following limitations: + + - A message can only be deleted if it was sent less than 48 hours ago. + + - Service messages about a supergroup, channel, or forum topic creation can't be deleted. + + - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. + + - Bots can delete outgoing messages in private chats, groups, and supergroups. + + - Bots can delete incoming messages in private chats. + + - Bots granted *can_post_messages* permissions can delete outgoing messages in channels. + + - If the bot is an administrator of a group, it can delete any message there. + + - If the bot has *can_delete_messages* permission in a supergroup or a channel, it can delete any message there. + + Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletemessage + + :param message_id: Identifier of the message to delete + :return: instance of method :class:`aiogram.methods.delete_message.DeleteMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import DeleteMessage + + return DeleteMessage( + chat_id=self.id, + message_id=message_id, + **kwargs, + ).as_(self._bot) + + def revoke_invite_link( + self, + invite_link: str, + **kwargs: Any, + ) -> RevokeChatInviteLink: + """ + Shortcut for method :class:`aiogram.methods.revoke_chat_invite_link.RevokeChatInviteLink` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to revoke an invite link created by the bot. If the primary link is revoked, a new link is automatically generated. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the revoked invite link as :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#revokechatinvitelink + + :param invite_link: The invite link to revoke + :return: instance of method :class:`aiogram.methods.revoke_chat_invite_link.RevokeChatInviteLink` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import RevokeChatInviteLink + + return RevokeChatInviteLink( + chat_id=self.id, + invite_link=invite_link, + **kwargs, + ).as_(self._bot) + + def edit_invite_link( + self, + invite_link: str, + name: Optional[str] = None, + expire_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + member_limit: Optional[int] = None, + creates_join_request: Optional[bool] = None, + **kwargs: Any, + ) -> EditChatInviteLink: + """ + Shortcut for method :class:`aiogram.methods.edit_chat_invite_link.EditChatInviteLink` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to edit a non-primary invite link created by the bot. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the edited invite link as a :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#editchatinvitelink + + :param invite_link: The invite link to edit + :param name: Invite link name; 0-32 characters + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + :param creates_join_request: :code:`True`, if users joining the chat via the link need to be approved by chat administrators. If :code:`True`, *member_limit* can't be specified + :return: instance of method :class:`aiogram.methods.edit_chat_invite_link.EditChatInviteLink` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import EditChatInviteLink + + return EditChatInviteLink( + chat_id=self.id, + invite_link=invite_link, + name=name, + expire_date=expire_date, + member_limit=member_limit, + creates_join_request=creates_join_request, + **kwargs, + ).as_(self._bot) + + def create_invite_link( + self, + name: Optional[str] = None, + expire_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + member_limit: Optional[int] = None, + creates_join_request: Optional[bool] = None, + **kwargs: Any, + ) -> CreateChatInviteLink: + """ + Shortcut for method :class:`aiogram.methods.create_chat_invite_link.CreateChatInviteLink` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to create an additional invite link for a chat. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. The link can be revoked using the method :class:`aiogram.methods.revoke_chat_invite_link.RevokeChatInviteLink`. Returns the new invite link as :class:`aiogram.types.chat_invite_link.ChatInviteLink` object. + + Source: https://core.telegram.org/bots/api#createchatinvitelink + + :param name: Invite link name; 0-32 characters + :param expire_date: Point in time (Unix timestamp) when the link will expire + :param member_limit: The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999 + :param creates_join_request: :code:`True`, if users joining the chat via the link need to be approved by chat administrators. If :code:`True`, *member_limit* can't be specified + :return: instance of method :class:`aiogram.methods.create_chat_invite_link.CreateChatInviteLink` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import CreateChatInviteLink + + return CreateChatInviteLink( + chat_id=self.id, + name=name, + expire_date=expire_date, + member_limit=member_limit, + creates_join_request=creates_join_request, + **kwargs, + ).as_(self._bot) + + def export_invite_link( + self, + **kwargs: Any, + ) -> ExportChatInviteLink: + """ + Shortcut for method :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to generate a new primary invite link for a chat; any previously generated primary link is revoked. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns the new invite link as *String* on success. + + Note: Each administrator in a chat generates their own invite links. Bots can't use invite links generated by other administrators. If you want your bot to work with invite links, it will need to generate its own link using :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` or by calling the :class:`aiogram.methods.get_chat.GetChat` method. If your bot needs to generate a new primary invite link replacing its previous one, use :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` again. + + Source: https://core.telegram.org/bots/api#exportchatinvitelink + + :return: instance of method :class:`aiogram.methods.export_chat_invite_link.ExportChatInviteLink` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import ExportChatInviteLink + + return ExportChatInviteLink( + chat_id=self.id, + **kwargs, + ).as_(self._bot) + + def do( + self, + action: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + **kwargs: Any, + ) -> SendChatAction: + """ + Shortcut for method :class:`aiogram.methods.send_chat_action.SendChatAction` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less (when a message arrives from your bot, Telegram clients clear its typing status). Returns :code:`True` on success. + + Example: The `ImageBot `_ needs some time to process a request and upload the image. Instead of sending a text message along the lines of 'Retrieving image, please wait…', the bot may use :class:`aiogram.methods.send_chat_action.SendChatAction` with *action* = *upload_photo*. The user will see a 'sending photo' status for the bot. + + We only recommend using this method when a response from the bot will take a **noticeable** amount of time to arrive. + + Source: https://core.telegram.org/bots/api#sendchataction + + :param action: Type of action to broadcast. Choose one, depending on what the user is about to receive: *typing* for `text messages `_, *upload_photo* for `photos `_, *record_video* or *upload_video* for `videos `_, *record_voice* or *upload_voice* for `voice notes `_, *upload_document* for `general files `_, *choose_sticker* for `stickers `_, *find_location* for `location data `_, *record_video_note* or *upload_video_note* for `video notes `_. + :param business_connection_id: Unique identifier of the business connection on behalf of which the action will be sent + :param message_thread_id: Unique identifier for the target message thread; for supergroups only + :return: instance of method :class:`aiogram.methods.send_chat_action.SendChatAction` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendChatAction + + return SendChatAction( + chat_id=self.id, + action=action, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + **kwargs, + ).as_(self._bot) + + def delete_sticker_set( + self, + **kwargs: Any, + ) -> DeleteChatStickerSet: + """ + Shortcut for method :class:`aiogram.methods.delete_chat_sticker_set.DeleteChatStickerSet` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to delete a group sticker set from a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field *can_set_sticker_set* optionally returned in :class:`aiogram.methods.get_chat.GetChat` requests to check if the bot can use this method. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletechatstickerset + + :return: instance of method :class:`aiogram.methods.delete_chat_sticker_set.DeleteChatStickerSet` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import DeleteChatStickerSet + + return DeleteChatStickerSet( + chat_id=self.id, + **kwargs, + ).as_(self._bot) + + def set_sticker_set( + self, + sticker_set_name: str, + **kwargs: Any, + ) -> SetChatStickerSet: + """ + Shortcut for method :class:`aiogram.methods.set_chat_sticker_set.SetChatStickerSet` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to set a new group sticker set for a supergroup. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Use the field *can_set_sticker_set* optionally returned in :class:`aiogram.methods.get_chat.GetChat` requests to check if the bot can use this method. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatstickerset + + :param sticker_set_name: Name of the sticker set to be set as the group sticker set + :return: instance of method :class:`aiogram.methods.set_chat_sticker_set.SetChatStickerSet` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SetChatStickerSet + + return SetChatStickerSet( + chat_id=self.id, + sticker_set_name=sticker_set_name, + **kwargs, + ).as_(self._bot) + + def get_member( + self, + user_id: int, + **kwargs: Any, + ) -> GetChatMember: + """ + Shortcut for method :class:`aiogram.methods.get_chat_member.GetChatMember` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to get information about a member of a chat. The method is only guaranteed to work for other users if the bot is an administrator in the chat. Returns a :class:`aiogram.types.chat_member.ChatMember` object on success. + + Source: https://core.telegram.org/bots/api#getchatmember + + :param user_id: Unique identifier of the target user + :return: instance of method :class:`aiogram.methods.get_chat_member.GetChatMember` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import GetChatMember + + return GetChatMember( + chat_id=self.id, + user_id=user_id, + **kwargs, + ).as_(self._bot) + + def get_member_count( + self, + **kwargs: Any, + ) -> GetChatMemberCount: + """ + Shortcut for method :class:`aiogram.methods.get_chat_member_count.GetChatMemberCount` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to get the number of members in a chat. Returns *Int* on success. + + Source: https://core.telegram.org/bots/api#getchatmembercount + + :return: instance of method :class:`aiogram.methods.get_chat_member_count.GetChatMemberCount` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import GetChatMemberCount + + return GetChatMemberCount( + chat_id=self.id, + **kwargs, + ).as_(self._bot) + + def leave( + self, + **kwargs: Any, + ) -> LeaveChat: + """ + Shortcut for method :class:`aiogram.methods.leave_chat.LeaveChat` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method for your bot to leave a group, supergroup or channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#leavechat + + :return: instance of method :class:`aiogram.methods.leave_chat.LeaveChat` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import LeaveChat + + return LeaveChat( + chat_id=self.id, + **kwargs, + ).as_(self._bot) + + def unpin_all_messages( + self, + **kwargs: Any, + ) -> UnpinAllChatMessages: + """ + Shortcut for method :class:`aiogram.methods.unpin_all_chat_messages.UnpinAllChatMessages` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to clear the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinallchatmessages + + :return: instance of method :class:`aiogram.methods.unpin_all_chat_messages.UnpinAllChatMessages` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import UnpinAllChatMessages + + return UnpinAllChatMessages( + chat_id=self.id, + **kwargs, + ).as_(self._bot) + + def unpin_message( + self, + business_connection_id: Optional[str] = None, + message_id: Optional[int] = None, + **kwargs: Any, + ) -> UnpinChatMessage: + """ + Shortcut for method :class:`aiogram.methods.unpin_chat_message.UnpinChatMessage` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinchatmessage + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be unpinned + :param message_id: Identifier of the message to unpin. Required if *business_connection_id* is specified. If not specified, the most recent pinned message (by sending date) will be unpinned. + :return: instance of method :class:`aiogram.methods.unpin_chat_message.UnpinChatMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import UnpinChatMessage + + return UnpinChatMessage( + chat_id=self.id, + business_connection_id=business_connection_id, + message_id=message_id, + **kwargs, + ).as_(self._bot) + + def pin_message( + self, + message_id: int, + business_connection_id: Optional[str] = None, + disable_notification: Optional[bool] = None, + **kwargs: Any, + ) -> PinChatMessage: + """ + Shortcut for method :class:`aiogram.methods.pin_chat_message.PinChatMessage` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#pinchatmessage + + :param message_id: Identifier of a message to pin + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be pinned + :param disable_notification: Pass :code:`True` if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats. + :return: instance of method :class:`aiogram.methods.pin_chat_message.PinChatMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import PinChatMessage + + return PinChatMessage( + chat_id=self.id, + message_id=message_id, + business_connection_id=business_connection_id, + disable_notification=disable_notification, + **kwargs, + ).as_(self._bot) + + def set_administrator_custom_title( + self, + user_id: int, + custom_title: str, + **kwargs: Any, + ) -> SetChatAdministratorCustomTitle: + """ + Shortcut for method :class:`aiogram.methods.set_chat_administrator_custom_title.SetChatAdministratorCustomTitle` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to set a custom title for an administrator in a supergroup promoted by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatadministratorcustomtitle + + :param user_id: Unique identifier of the target user + :param custom_title: New custom title for the administrator; 0-16 characters, emoji are not allowed + :return: instance of method :class:`aiogram.methods.set_chat_administrator_custom_title.SetChatAdministratorCustomTitle` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SetChatAdministratorCustomTitle + + return SetChatAdministratorCustomTitle( + chat_id=self.id, + user_id=user_id, + custom_title=custom_title, + **kwargs, + ).as_(self._bot) + + def set_permissions( + self, + permissions: ChatPermissions, + use_independent_chat_permissions: Optional[bool] = None, + **kwargs: Any, + ) -> SetChatPermissions: + """ + Shortcut for method :class:`aiogram.methods.set_chat_permissions.SetChatPermissions` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to set default chat permissions for all members. The bot must be an administrator in the group or a supergroup for this to work and must have the *can_restrict_members* administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatpermissions + + :param permissions: A JSON-serialized object for new default chat permissions + :param use_independent_chat_permissions: Pass :code:`True` if chat permissions are set independently. Otherwise, the *can_send_other_messages* and *can_add_web_page_previews* permissions will imply the *can_send_messages*, *can_send_audios*, *can_send_documents*, *can_send_photos*, *can_send_videos*, *can_send_video_notes*, and *can_send_voice_notes* permissions; the *can_send_polls* permission will imply the *can_send_messages* permission. + :return: instance of method :class:`aiogram.methods.set_chat_permissions.SetChatPermissions` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SetChatPermissions + + return SetChatPermissions( + chat_id=self.id, + permissions=permissions, + use_independent_chat_permissions=use_independent_chat_permissions, + **kwargs, + ).as_(self._bot) + + def promote( + self, + user_id: int, + is_anonymous: Optional[bool] = None, + can_manage_chat: Optional[bool] = None, + can_delete_messages: Optional[bool] = None, + can_manage_video_chats: Optional[bool] = None, + can_restrict_members: Optional[bool] = None, + can_promote_members: Optional[bool] = None, + can_change_info: Optional[bool] = None, + can_invite_users: Optional[bool] = None, + can_post_stories: Optional[bool] = None, + can_edit_stories: Optional[bool] = None, + can_delete_stories: Optional[bool] = None, + can_post_messages: Optional[bool] = None, + can_edit_messages: Optional[bool] = None, + can_pin_messages: Optional[bool] = None, + can_manage_topics: Optional[bool] = None, + **kwargs: Any, + ) -> PromoteChatMember: + """ + Shortcut for method :class:`aiogram.methods.promote_chat_member.PromoteChatMember` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to promote or demote a user in a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Pass :code:`False` for all boolean parameters to demote a user. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#promotechatmember + + :param user_id: Unique identifier of the target user + :param is_anonymous: Pass :code:`True` if the administrator's presence in the chat is hidden + :param can_manage_chat: Pass :code:`True` if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages and ignore slow mode. Implied by any other administrator privilege. + :param can_delete_messages: Pass :code:`True` if the administrator can delete messages of other users + :param can_manage_video_chats: Pass :code:`True` if the administrator can manage video chats + :param can_restrict_members: Pass :code:`True` if the administrator can restrict, ban or unban chat members, or access supergroup statistics + :param can_promote_members: Pass :code:`True` if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by him) + :param can_change_info: Pass :code:`True` if the administrator can change chat title, photo and other settings + :param can_invite_users: Pass :code:`True` if the administrator can invite new users to the chat + :param can_post_stories: Pass :code:`True` if the administrator can post stories to the chat + :param can_edit_stories: Pass :code:`True` if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive + :param can_delete_stories: Pass :code:`True` if the administrator can delete stories posted by other users + :param can_post_messages: Pass :code:`True` if the administrator can post messages in the channel, or access channel statistics; for channels only + :param can_edit_messages: Pass :code:`True` if the administrator can edit messages of other users and can pin messages; for channels only + :param can_pin_messages: Pass :code:`True` if the administrator can pin messages; for supergroups only + :param can_manage_topics: Pass :code:`True` if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only + :return: instance of method :class:`aiogram.methods.promote_chat_member.PromoteChatMember` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import PromoteChatMember + + return PromoteChatMember( + chat_id=self.id, + user_id=user_id, + is_anonymous=is_anonymous, + can_manage_chat=can_manage_chat, + can_delete_messages=can_delete_messages, + can_manage_video_chats=can_manage_video_chats, + can_restrict_members=can_restrict_members, + can_promote_members=can_promote_members, + can_change_info=can_change_info, + can_invite_users=can_invite_users, + can_post_stories=can_post_stories, + can_edit_stories=can_edit_stories, + can_delete_stories=can_delete_stories, + can_post_messages=can_post_messages, + can_edit_messages=can_edit_messages, + can_pin_messages=can_pin_messages, + can_manage_topics=can_manage_topics, + **kwargs, + ).as_(self._bot) + + def restrict( + self, + user_id: int, + permissions: ChatPermissions, + use_independent_chat_permissions: Optional[bool] = None, + until_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + **kwargs: Any, + ) -> RestrictChatMember: + """ + Shortcut for method :class:`aiogram.methods.restrict_chat_member.RestrictChatMember` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to restrict a user in a supergroup. The bot must be an administrator in the supergroup for this to work and must have the appropriate administrator rights. Pass :code:`True` for all permissions to lift restrictions from a user. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#restrictchatmember + + :param user_id: Unique identifier of the target user + :param permissions: A JSON-serialized object for new user permissions + :param use_independent_chat_permissions: Pass :code:`True` if chat permissions are set independently. Otherwise, the *can_send_other_messages* and *can_add_web_page_previews* permissions will imply the *can_send_messages*, *can_send_audios*, *can_send_documents*, *can_send_photos*, *can_send_videos*, *can_send_video_notes*, and *can_send_voice_notes* permissions; the *can_send_polls* permission will imply the *can_send_messages* permission. + :param until_date: Date when restrictions will be lifted for the user; Unix time. If user is restricted for more than 366 days or less than 30 seconds from the current time, they are considered to be restricted forever + :return: instance of method :class:`aiogram.methods.restrict_chat_member.RestrictChatMember` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import RestrictChatMember + + return RestrictChatMember( + chat_id=self.id, + user_id=user_id, + permissions=permissions, + use_independent_chat_permissions=use_independent_chat_permissions, + until_date=until_date, + **kwargs, + ).as_(self._bot) + + def unban( + self, + user_id: int, + only_if_banned: Optional[bool] = None, + **kwargs: Any, + ) -> UnbanChatMember: + """ + Shortcut for method :class:`aiogram.methods.unban_chat_member.UnbanChatMember` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to unban a previously banned user in a supergroup or channel. The user will **not** return to the group or channel automatically, but will be able to join via link, etc. The bot must be an administrator for this to work. By default, this method guarantees that after the call the user is not a member of the chat, but will be able to join it. So if the user is a member of the chat they will also be **removed** from the chat. If you don't want this, use the parameter *only_if_banned*. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unbanchatmember + + :param user_id: Unique identifier of the target user + :param only_if_banned: Do nothing if the user is not banned + :return: instance of method :class:`aiogram.methods.unban_chat_member.UnbanChatMember` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import UnbanChatMember + + return UnbanChatMember( + chat_id=self.id, + user_id=user_id, + only_if_banned=only_if_banned, + **kwargs, + ).as_(self._bot) + + def ban( + self, + user_id: int, + until_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + revoke_messages: Optional[bool] = None, + **kwargs: Any, + ) -> BanChatMember: + """ + Shortcut for method :class:`aiogram.methods.ban_chat_member.BanChatMember` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to ban a user in a group, a supergroup or a channel. In the case of supergroups and channels, the user will not be able to return to the chat on their own using invite links, etc., unless `unbanned `_ first. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#banchatmember + + :param user_id: Unique identifier of the target user + :param until_date: Date when the user will be unbanned; Unix time. If user is banned for more than 366 days or less than 30 seconds from the current time they are considered to be banned forever. Applied for supergroups and channels only. + :param revoke_messages: Pass :code:`True` to delete all messages from the chat for the user that is being removed. If :code:`False`, the user will be able to see messages in the group that were sent before the user was removed. Always :code:`True` for supergroups and channels. + :return: instance of method :class:`aiogram.methods.ban_chat_member.BanChatMember` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import BanChatMember + + return BanChatMember( + chat_id=self.id, + user_id=user_id, + until_date=until_date, + revoke_messages=revoke_messages, + **kwargs, + ).as_(self._bot) + + def set_description( + self, + description: Optional[str] = None, + **kwargs: Any, + ) -> SetChatDescription: + """ + Shortcut for method :class:`aiogram.methods.set_chat_description.SetChatDescription` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to change the description of a group, a supergroup or a channel. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatdescription + + :param description: New chat description, 0-255 characters + :return: instance of method :class:`aiogram.methods.set_chat_description.SetChatDescription` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SetChatDescription + + return SetChatDescription( + chat_id=self.id, + description=description, + **kwargs, + ).as_(self._bot) + + def set_title( + self, + title: str, + **kwargs: Any, + ) -> SetChatTitle: + """ + Shortcut for method :class:`aiogram.methods.set_chat_title.SetChatTitle` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to change the title of a chat. Titles can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchattitle + + :param title: New chat title, 1-128 characters + :return: instance of method :class:`aiogram.methods.set_chat_title.SetChatTitle` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SetChatTitle + + return SetChatTitle( + chat_id=self.id, + title=title, + **kwargs, + ).as_(self._bot) + + def delete_photo( + self, + **kwargs: Any, + ) -> DeleteChatPhoto: + """ + Shortcut for method :class:`aiogram.methods.delete_chat_photo.DeleteChatPhoto` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to delete a chat photo. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletechatphoto + + :return: instance of method :class:`aiogram.methods.delete_chat_photo.DeleteChatPhoto` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import DeleteChatPhoto + + return DeleteChatPhoto( + chat_id=self.id, + **kwargs, + ).as_(self._bot) + + def set_photo( + self, + photo: InputFile, + **kwargs: Any, + ) -> SetChatPhoto: + """ + Shortcut for method :class:`aiogram.methods.set_chat_photo.SetChatPhoto` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to set a new profile photo for the chat. Photos can't be changed for private chats. The bot must be an administrator in the chat for this to work and must have the appropriate administrator rights. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setchatphoto + + :param photo: New chat photo, uploaded using multipart/form-data + :return: instance of method :class:`aiogram.methods.set_chat_photo.SetChatPhoto` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SetChatPhoto + + return SetChatPhoto( + chat_id=self.id, + photo=photo, + **kwargs, + ).as_(self._bot) + + def unpin_all_general_forum_topic_messages( + self, + **kwargs: Any, + ) -> UnpinAllGeneralForumTopicMessages: + """ + Shortcut for method :class:`aiogram.methods.unpin_all_general_forum_topic_messages.UnpinAllGeneralForumTopicMessages` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to clear the list of pinned messages in a General forum topic. The bot must be an administrator in the chat for this to work and must have the *can_pin_messages* administrator right in the supergroup. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinallgeneralforumtopicmessages + + :return: instance of method :class:`aiogram.methods.unpin_all_general_forum_topic_messages.UnpinAllGeneralForumTopicMessages` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import UnpinAllGeneralForumTopicMessages + + return UnpinAllGeneralForumTopicMessages( + chat_id=self.id, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/chat_administrator_rights.py b/env/Lib/site-packages/aiogram/types/chat_administrator_rights.py new file mode 100644 index 0000000..0b20578 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_administrator_rights.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + pass + + +class ChatAdministratorRights(TelegramObject): + """ + Represents the rights of an administrator in a chat. + + Source: https://core.telegram.org/bots/api#chatadministratorrights + """ + + is_anonymous: bool + """:code:`True`, if the user's presence in the chat is hidden""" + can_manage_chat: bool + """:code:`True`, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages and ignore slow mode. Implied by any other administrator privilege.""" + can_delete_messages: bool + """:code:`True`, if the administrator can delete messages of other users""" + can_manage_video_chats: bool + """:code:`True`, if the administrator can manage video chats""" + can_restrict_members: bool + """:code:`True`, if the administrator can restrict, ban or unban chat members, or access supergroup statistics""" + can_promote_members: bool + """:code:`True`, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user)""" + can_change_info: bool + """:code:`True`, if the user is allowed to change the chat title, photo and other settings""" + can_invite_users: bool + """:code:`True`, if the user is allowed to invite new users to the chat""" + can_post_stories: bool + """:code:`True`, if the administrator can post stories to the chat""" + can_edit_stories: bool + """:code:`True`, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive""" + can_delete_stories: bool + """:code:`True`, if the administrator can delete stories posted by other users""" + can_post_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the administrator can post messages in the channel, or access channel statistics; for channels only""" + can_edit_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the administrator can edit messages of other users and can pin messages; for channels only""" + can_pin_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to pin messages; for groups and supergroups only""" + can_manage_topics: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + is_anonymous: bool, + can_manage_chat: bool, + can_delete_messages: bool, + can_manage_video_chats: bool, + can_restrict_members: bool, + can_promote_members: bool, + can_change_info: bool, + can_invite_users: bool, + can_post_stories: bool, + can_edit_stories: bool, + can_delete_stories: bool, + can_post_messages: Optional[bool] = None, + can_edit_messages: Optional[bool] = None, + can_pin_messages: Optional[bool] = None, + can_manage_topics: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + is_anonymous=is_anonymous, + can_manage_chat=can_manage_chat, + can_delete_messages=can_delete_messages, + can_manage_video_chats=can_manage_video_chats, + can_restrict_members=can_restrict_members, + can_promote_members=can_promote_members, + can_change_info=can_change_info, + can_invite_users=can_invite_users, + can_post_stories=can_post_stories, + can_edit_stories=can_edit_stories, + can_delete_stories=can_delete_stories, + can_post_messages=can_post_messages, + can_edit_messages=can_edit_messages, + can_pin_messages=can_pin_messages, + can_manage_topics=can_manage_topics, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_background.py b/env/Lib/site-packages/aiogram/types/chat_background.py new file mode 100644 index 0000000..937b436 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_background.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +if TYPE_CHECKING: + from .background_type_chat_theme import BackgroundTypeChatTheme + from .background_type_fill import BackgroundTypeFill + from .background_type_pattern import BackgroundTypePattern + from .background_type_wallpaper import BackgroundTypeWallpaper +from .base import TelegramObject + + +class ChatBackground(TelegramObject): + """ + This object represents a chat background. + + Source: https://core.telegram.org/bots/api#chatbackground + """ + + type: Union[ + BackgroundTypeFill, BackgroundTypeWallpaper, BackgroundTypePattern, BackgroundTypeChatTheme + ] + """Type of the background""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Union[ + BackgroundTypeFill, + BackgroundTypeWallpaper, + BackgroundTypePattern, + BackgroundTypeChatTheme, + ], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_boost.py b/env/Lib/site-packages/aiogram/types/chat_boost.py new file mode 100644 index 0000000..96e444f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_boost.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from .chat_boost_source_gift_code import ChatBoostSourceGiftCode + from .chat_boost_source_giveaway import ChatBoostSourceGiveaway + from .chat_boost_source_premium import ChatBoostSourcePremium + + +class ChatBoost(TelegramObject): + """ + This object contains information about a chat boost. + + Source: https://core.telegram.org/bots/api#chatboost + """ + + boost_id: str + """Unique identifier of the boost""" + add_date: DateTime + """Point in time (Unix timestamp) when the chat was boosted""" + expiration_date: DateTime + """Point in time (Unix timestamp) when the boost will automatically expire, unless the booster's Telegram Premium subscription is prolonged""" + source: Union[ChatBoostSourcePremium, ChatBoostSourceGiftCode, ChatBoostSourceGiveaway] + """Source of the added boost""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + boost_id: str, + add_date: DateTime, + expiration_date: DateTime, + source: Union[ + ChatBoostSourcePremium, ChatBoostSourceGiftCode, ChatBoostSourceGiveaway + ], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + boost_id=boost_id, + add_date=add_date, + expiration_date=expiration_date, + source=source, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_boost_added.py b/env/Lib/site-packages/aiogram/types/chat_boost_added.py new file mode 100644 index 0000000..4473eae --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_boost_added.py @@ -0,0 +1,25 @@ +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class ChatBoostAdded(TelegramObject): + """ + This object represents a service message about a user boosting a chat. + + Source: https://core.telegram.org/bots/api#chatboostadded + """ + + boost_count: int + """Number of boosts added by the user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, boost_count: int, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(boost_count=boost_count, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_boost_removed.py b/env/Lib/site-packages/aiogram/types/chat_boost_removed.py new file mode 100644 index 0000000..094b057 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_boost_removed.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from .chat import Chat + from .chat_boost_source_gift_code import ChatBoostSourceGiftCode + from .chat_boost_source_giveaway import ChatBoostSourceGiveaway + from .chat_boost_source_premium import ChatBoostSourcePremium + + +class ChatBoostRemoved(TelegramObject): + """ + This object represents a boost removed from a chat. + + Source: https://core.telegram.org/bots/api#chatboostremoved + """ + + chat: Chat + """Chat which was boosted""" + boost_id: str + """Unique identifier of the boost""" + remove_date: DateTime + """Point in time (Unix timestamp) when the boost was removed""" + source: Union[ChatBoostSourcePremium, ChatBoostSourceGiftCode, ChatBoostSourceGiveaway] + """Source of the removed boost""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat: Chat, + boost_id: str, + remove_date: DateTime, + source: Union[ + ChatBoostSourcePremium, ChatBoostSourceGiftCode, ChatBoostSourceGiveaway + ], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat=chat, + boost_id=boost_id, + remove_date=remove_date, + source=source, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_boost_source.py b/env/Lib/site-packages/aiogram/types/chat_boost_source.py new file mode 100644 index 0000000..3d2c262 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_boost_source.py @@ -0,0 +1,13 @@ +from aiogram.types import TelegramObject + + +class ChatBoostSource(TelegramObject): + """ + This object describes the source of a chat boost. It can be one of + + - :class:`aiogram.types.chat_boost_source_premium.ChatBoostSourcePremium` + - :class:`aiogram.types.chat_boost_source_gift_code.ChatBoostSourceGiftCode` + - :class:`aiogram.types.chat_boost_source_giveaway.ChatBoostSourceGiveaway` + + Source: https://core.telegram.org/bots/api#chatboostsource + """ diff --git a/env/Lib/site-packages/aiogram/types/chat_boost_source_gift_code.py b/env/Lib/site-packages/aiogram/types/chat_boost_source_gift_code.py new file mode 100644 index 0000000..554e58f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_boost_source_gift_code.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import ChatBoostSourceType +from .chat_boost_source import ChatBoostSource + +if TYPE_CHECKING: + from .user import User + + +class ChatBoostSourceGiftCode(ChatBoostSource): + """ + The boost was obtained by the creation of Telegram Premium gift codes to boost a chat. Each such code boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription. + + Source: https://core.telegram.org/bots/api#chatboostsourcegiftcode + """ + + source: Literal[ChatBoostSourceType.GIFT_CODE] = ChatBoostSourceType.GIFT_CODE + """Source of the boost, always 'gift_code'""" + user: User + """User for which the gift code was created""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[ChatBoostSourceType.GIFT_CODE] = ChatBoostSourceType.GIFT_CODE, + user: User, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(source=source, user=user, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_boost_source_giveaway.py b/env/Lib/site-packages/aiogram/types/chat_boost_source_giveaway.py new file mode 100644 index 0000000..dbb8150 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_boost_source_giveaway.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from ..enums import ChatBoostSourceType +from .chat_boost_source import ChatBoostSource + +if TYPE_CHECKING: + from .user import User + + +class ChatBoostSourceGiveaway(ChatBoostSource): + """ + The boost was obtained by the creation of a Telegram Premium giveaway. This boosts the chat 4 times for the duration of the corresponding Telegram Premium subscription. + + Source: https://core.telegram.org/bots/api#chatboostsourcegiveaway + """ + + source: Literal[ChatBoostSourceType.GIVEAWAY] = ChatBoostSourceType.GIVEAWAY + """Source of the boost, always 'giveaway'""" + giveaway_message_id: int + """Identifier of a message in the chat with the giveaway; the message could have been deleted already. May be 0 if the message isn't sent yet.""" + user: Optional[User] = None + """*Optional*. User that won the prize in the giveaway if any""" + is_unclaimed: Optional[bool] = None + """*Optional*. True, if the giveaway was completed, but there was no user to win the prize""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[ChatBoostSourceType.GIVEAWAY] = ChatBoostSourceType.GIVEAWAY, + giveaway_message_id: int, + user: Optional[User] = None, + is_unclaimed: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, + giveaway_message_id=giveaway_message_id, + user=user, + is_unclaimed=is_unclaimed, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_boost_source_premium.py b/env/Lib/site-packages/aiogram/types/chat_boost_source_premium.py new file mode 100644 index 0000000..97b47e6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_boost_source_premium.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import ChatBoostSourceType +from .chat_boost_source import ChatBoostSource + +if TYPE_CHECKING: + from .user import User + + +class ChatBoostSourcePremium(ChatBoostSource): + """ + The boost was obtained by subscribing to Telegram Premium or by gifting a Telegram Premium subscription to another user. + + Source: https://core.telegram.org/bots/api#chatboostsourcepremium + """ + + source: Literal[ChatBoostSourceType.PREMIUM] = ChatBoostSourceType.PREMIUM + """Source of the boost, always 'premium'""" + user: User + """User that boosted the chat""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[ChatBoostSourceType.PREMIUM] = ChatBoostSourceType.PREMIUM, + user: User, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(source=source, user=user, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_boost_updated.py b/env/Lib/site-packages/aiogram/types/chat_boost_updated.py new file mode 100644 index 0000000..0921c96 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_boost_updated.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat import Chat + from .chat_boost import ChatBoost + + +class ChatBoostUpdated(TelegramObject): + """ + This object represents a boost added to a chat or changed. + + Source: https://core.telegram.org/bots/api#chatboostupdated + """ + + chat: Chat + """Chat which was boosted""" + boost: ChatBoost + """Information about the chat boost""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, chat: Chat, boost: ChatBoost, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat=chat, boost=boost, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_full_info.py b/env/Lib/site-packages/aiogram/types/chat_full_info.py new file mode 100644 index 0000000..c639939 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_full_info.py @@ -0,0 +1,225 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from .chat import Chat +from .custom import DateTime + +if TYPE_CHECKING: + from .birthdate import Birthdate + from .business_intro import BusinessIntro + from .business_location import BusinessLocation + from .business_opening_hours import BusinessOpeningHours + from .chat_location import ChatLocation + from .chat_permissions import ChatPermissions + from .chat_photo import ChatPhoto + from .message import Message + from .reaction_type_custom_emoji import ReactionTypeCustomEmoji + from .reaction_type_emoji import ReactionTypeEmoji + from .reaction_type_paid import ReactionTypePaid + + +class ChatFullInfo(Chat): + """ + This object contains full information about a chat. + + Source: https://core.telegram.org/bots/api#chatfullinfo + """ + + id: int + """Unique identifier for this chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.""" + type: str + """Type of the chat, can be either 'private', 'group', 'supergroup' or 'channel'""" + accent_color_id: int + """Identifier of the accent color for the chat name and backgrounds of the chat photo, reply header, and link preview. See `accent colors `_ for more details.""" + max_reaction_count: int + """The maximum number of reactions that can be set on a message in the chat""" + title: Optional[str] = None + """*Optional*. Title, for supergroups, channels and group chats""" + username: Optional[str] = None + """*Optional*. Username, for private chats, supergroups and channels if available""" + first_name: Optional[str] = None + """*Optional*. First name of the other party in a private chat""" + last_name: Optional[str] = None + """*Optional*. Last name of the other party in a private chat""" + is_forum: Optional[bool] = None + """*Optional*. :code:`True`, if the supergroup chat is a forum (has `topics `_ enabled)""" + photo: Optional[ChatPhoto] = None + """*Optional*. Chat photo""" + active_usernames: Optional[List[str]] = None + """*Optional*. If non-empty, the list of all `active chat usernames `_; for private chats, supergroups and channels""" + birthdate: Optional[Birthdate] = None + """*Optional*. For private chats, the date of birth of the user""" + business_intro: Optional[BusinessIntro] = None + """*Optional*. For private chats with business accounts, the intro of the business""" + business_location: Optional[BusinessLocation] = None + """*Optional*. For private chats with business accounts, the location of the business""" + business_opening_hours: Optional[BusinessOpeningHours] = None + """*Optional*. For private chats with business accounts, the opening hours of the business""" + personal_chat: Optional[Chat] = None + """*Optional*. For private chats, the personal channel of the user""" + available_reactions: Optional[ + List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + ] = None + """*Optional*. List of available reactions allowed in the chat. If omitted, then all `emoji reactions `_ are allowed.""" + background_custom_emoji_id: Optional[str] = None + """*Optional*. Custom emoji identifier of the emoji chosen by the chat for the reply header and link preview background""" + profile_accent_color_id: Optional[int] = None + """*Optional*. Identifier of the accent color for the chat's profile background. See `profile accent colors `_ for more details.""" + profile_background_custom_emoji_id: Optional[str] = None + """*Optional*. Custom emoji identifier of the emoji chosen by the chat for its profile background""" + emoji_status_custom_emoji_id: Optional[str] = None + """*Optional*. Custom emoji identifier of the emoji status of the chat or the other party in a private chat""" + emoji_status_expiration_date: Optional[DateTime] = None + """*Optional*. Expiration date of the emoji status of the chat or the other party in a private chat, in Unix time, if any""" + bio: Optional[str] = None + """*Optional*. Bio of the other party in a private chat""" + has_private_forwards: Optional[bool] = None + """*Optional*. :code:`True`, if privacy settings of the other party in the private chat allows to use :code:`tg://user?id=` links only in chats with the user""" + has_restricted_voice_and_video_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the privacy settings of the other party restrict sending voice and video note messages in the private chat""" + join_to_send_messages: Optional[bool] = None + """*Optional*. :code:`True`, if users need to join the supergroup before they can send messages""" + join_by_request: Optional[bool] = None + """*Optional*. :code:`True`, if all users directly joining the supergroup without using an invite link need to be approved by supergroup administrators""" + description: Optional[str] = None + """*Optional*. Description, for groups, supergroups and channel chats""" + invite_link: Optional[str] = None + """*Optional*. Primary invite link, for groups, supergroups and channel chats""" + pinned_message: Optional[Message] = None + """*Optional*. The most recent pinned message (by sending date)""" + permissions: Optional[ChatPermissions] = None + """*Optional*. Default chat member permissions, for groups and supergroups""" + can_send_paid_media: Optional[bool] = None + """*Optional*. :code:`True`, if paid media messages can be sent or forwarded to the channel chat. The field is available only for channel chats.""" + slow_mode_delay: Optional[int] = None + """*Optional*. For supergroups, the minimum allowed delay between consecutive messages sent by each unprivileged user; in seconds""" + unrestrict_boost_count: Optional[int] = None + """*Optional*. For supergroups, the minimum number of boosts that a non-administrator user needs to add in order to ignore slow mode and chat permissions""" + message_auto_delete_time: Optional[int] = None + """*Optional*. The time after which all messages sent to the chat will be automatically deleted; in seconds""" + has_aggressive_anti_spam_enabled: Optional[bool] = None + """*Optional*. :code:`True`, if aggressive anti-spam checks are enabled in the supergroup. The field is only available to chat administrators.""" + has_hidden_members: Optional[bool] = None + """*Optional*. :code:`True`, if non-administrators can only get the list of bots and administrators in the chat""" + has_protected_content: Optional[bool] = None + """*Optional*. :code:`True`, if messages from the chat can't be forwarded to other chats""" + has_visible_history: Optional[bool] = None + """*Optional*. :code:`True`, if new chat members will have access to old messages; available only to chat administrators""" + sticker_set_name: Optional[str] = None + """*Optional*. For supergroups, name of the group sticker set""" + can_set_sticker_set: Optional[bool] = None + """*Optional*. :code:`True`, if the bot can change the group sticker set""" + custom_emoji_sticker_set_name: Optional[str] = None + """*Optional*. For supergroups, the name of the group's custom emoji sticker set. Custom emoji from this set can be used by all users and bots in the group.""" + linked_chat_id: Optional[int] = None + """*Optional*. Unique identifier for the linked chat, i.e. the discussion group identifier for a channel and vice versa; for supergroups and channel chats. This identifier may be greater than 32 bits and some programming languages may have difficulty/silent defects in interpreting it. But it is smaller than 52 bits, so a signed 64 bit integer or double-precision float type are safe for storing this identifier.""" + location: Optional[ChatLocation] = None + """*Optional*. For supergroups, the location to which the supergroup is connected""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: int, + type: str, + accent_color_id: int, + max_reaction_count: int, + title: Optional[str] = None, + username: Optional[str] = None, + first_name: Optional[str] = None, + last_name: Optional[str] = None, + is_forum: Optional[bool] = None, + photo: Optional[ChatPhoto] = None, + active_usernames: Optional[List[str]] = None, + birthdate: Optional[Birthdate] = None, + business_intro: Optional[BusinessIntro] = None, + business_location: Optional[BusinessLocation] = None, + business_opening_hours: Optional[BusinessOpeningHours] = None, + personal_chat: Optional[Chat] = None, + available_reactions: Optional[ + List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + ] = None, + background_custom_emoji_id: Optional[str] = None, + profile_accent_color_id: Optional[int] = None, + profile_background_custom_emoji_id: Optional[str] = None, + emoji_status_custom_emoji_id: Optional[str] = None, + emoji_status_expiration_date: Optional[DateTime] = None, + bio: Optional[str] = None, + has_private_forwards: Optional[bool] = None, + has_restricted_voice_and_video_messages: Optional[bool] = None, + join_to_send_messages: Optional[bool] = None, + join_by_request: Optional[bool] = None, + description: Optional[str] = None, + invite_link: Optional[str] = None, + pinned_message: Optional[Message] = None, + permissions: Optional[ChatPermissions] = None, + can_send_paid_media: Optional[bool] = None, + slow_mode_delay: Optional[int] = None, + unrestrict_boost_count: Optional[int] = None, + message_auto_delete_time: Optional[int] = None, + has_aggressive_anti_spam_enabled: Optional[bool] = None, + has_hidden_members: Optional[bool] = None, + has_protected_content: Optional[bool] = None, + has_visible_history: Optional[bool] = None, + sticker_set_name: Optional[str] = None, + can_set_sticker_set: Optional[bool] = None, + custom_emoji_sticker_set_name: Optional[str] = None, + linked_chat_id: Optional[int] = None, + location: Optional[ChatLocation] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + type=type, + accent_color_id=accent_color_id, + max_reaction_count=max_reaction_count, + title=title, + username=username, + first_name=first_name, + last_name=last_name, + is_forum=is_forum, + photo=photo, + active_usernames=active_usernames, + birthdate=birthdate, + business_intro=business_intro, + business_location=business_location, + business_opening_hours=business_opening_hours, + personal_chat=personal_chat, + available_reactions=available_reactions, + background_custom_emoji_id=background_custom_emoji_id, + profile_accent_color_id=profile_accent_color_id, + profile_background_custom_emoji_id=profile_background_custom_emoji_id, + emoji_status_custom_emoji_id=emoji_status_custom_emoji_id, + emoji_status_expiration_date=emoji_status_expiration_date, + bio=bio, + has_private_forwards=has_private_forwards, + has_restricted_voice_and_video_messages=has_restricted_voice_and_video_messages, + join_to_send_messages=join_to_send_messages, + join_by_request=join_by_request, + description=description, + invite_link=invite_link, + pinned_message=pinned_message, + permissions=permissions, + can_send_paid_media=can_send_paid_media, + slow_mode_delay=slow_mode_delay, + unrestrict_boost_count=unrestrict_boost_count, + message_auto_delete_time=message_auto_delete_time, + has_aggressive_anti_spam_enabled=has_aggressive_anti_spam_enabled, + has_hidden_members=has_hidden_members, + has_protected_content=has_protected_content, + has_visible_history=has_visible_history, + sticker_set_name=sticker_set_name, + can_set_sticker_set=can_set_sticker_set, + custom_emoji_sticker_set_name=custom_emoji_sticker_set_name, + linked_chat_id=linked_chat_id, + location=location, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_invite_link.py b/env/Lib/site-packages/aiogram/types/chat_invite_link.py new file mode 100644 index 0000000..7817c23 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_invite_link.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from .user import User + + +class ChatInviteLink(TelegramObject): + """ + Represents an invite link for a chat. + + Source: https://core.telegram.org/bots/api#chatinvitelink + """ + + invite_link: str + """The invite link. If the link was created by another chat administrator, then the second part of the link will be replaced with '…'.""" + creator: User + """Creator of the link""" + creates_join_request: bool + """:code:`True`, if users joining the chat via the link need to be approved by chat administrators""" + is_primary: bool + """:code:`True`, if the link is primary""" + is_revoked: bool + """:code:`True`, if the link is revoked""" + name: Optional[str] = None + """*Optional*. Invite link name""" + expire_date: Optional[DateTime] = None + """*Optional*. Point in time (Unix timestamp) when the link will expire or has been expired""" + member_limit: Optional[int] = None + """*Optional*. The maximum number of users that can be members of the chat simultaneously after joining the chat via this invite link; 1-99999""" + pending_join_request_count: Optional[int] = None + """*Optional*. Number of pending join requests created using this link""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + invite_link: str, + creator: User, + creates_join_request: bool, + is_primary: bool, + is_revoked: bool, + name: Optional[str] = None, + expire_date: Optional[DateTime] = None, + member_limit: Optional[int] = None, + pending_join_request_count: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + invite_link=invite_link, + creator=creator, + creates_join_request=creates_join_request, + is_primary=is_primary, + is_revoked=is_revoked, + name=name, + expire_date=expire_date, + member_limit=member_limit, + pending_join_request_count=pending_join_request_count, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_join_request.py b/env/Lib/site-packages/aiogram/types/chat_join_request.py new file mode 100644 index 0000000..4a128f1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_join_request.py @@ -0,0 +1,2702 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from ..methods import ( + ApproveChatJoinRequest, + DeclineChatJoinRequest, + SendAnimation, + SendAudio, + SendContact, + SendDice, + SendDocument, + SendGame, + SendInvoice, + SendLocation, + SendMediaGroup, + SendMessage, + SendPhoto, + SendPoll, + SendSticker, + SendVenue, + SendVideo, + SendVideoNote, + SendVoice, + ) + from .chat import Chat + from .chat_invite_link import ChatInviteLink + from .force_reply import ForceReply + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_file import InputFile + from .input_media_audio import InputMediaAudio + from .input_media_document import InputMediaDocument + from .input_media_photo import InputMediaPhoto + from .input_media_video import InputMediaVideo + from .input_poll_option import InputPollOption + from .labeled_price import LabeledPrice + from .link_preview_options import LinkPreviewOptions + from .message_entity import MessageEntity + from .reply_keyboard_markup import ReplyKeyboardMarkup + from .reply_keyboard_remove import ReplyKeyboardRemove + from .reply_parameters import ReplyParameters + from .user import User + + +class ChatJoinRequest(TelegramObject): + """ + Represents a join request sent to a chat. + + Source: https://core.telegram.org/bots/api#chatjoinrequest + """ + + chat: Chat + """Chat to which the request was sent""" + from_user: User = Field(..., alias="from") + """User that sent the join request""" + user_chat_id: int + """Identifier of a private chat with the user who sent the join request. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot can use this identifier for 5 minutes to send messages until the join request is processed, assuming no other administrator contacted the user.""" + date: DateTime + """Date the request was sent in Unix time""" + bio: Optional[str] = None + """*Optional*. Bio of the user.""" + invite_link: Optional[ChatInviteLink] = None + """*Optional*. Chat invite link that was used by the user to send the join request""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat: Chat, + from_user: User, + user_chat_id: int, + date: DateTime, + bio: Optional[str] = None, + invite_link: Optional[ChatInviteLink] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat=chat, + from_user=from_user, + user_chat_id=user_chat_id, + date=date, + bio=bio, + invite_link=invite_link, + **__pydantic_kwargs, + ) + + def approve( + self, + **kwargs: Any, + ) -> ApproveChatJoinRequest: + """ + Shortcut for method :class:`aiogram.methods.approve_chat_join_request.ApproveChatJoinRequest` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`user_id` + + Use this method to approve a chat join request. The bot must be an administrator in the chat for this to work and must have the *can_invite_users* administrator right. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#approvechatjoinrequest + + :return: instance of method :class:`aiogram.methods.approve_chat_join_request.ApproveChatJoinRequest` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import ApproveChatJoinRequest + + return ApproveChatJoinRequest( + chat_id=self.chat.id, + user_id=self.from_user.id, + **kwargs, + ).as_(self._bot) + + def decline( + self, + **kwargs: Any, + ) -> DeclineChatJoinRequest: + """ + Shortcut for method :class:`aiogram.methods.decline_chat_join_request.DeclineChatJoinRequest` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`user_id` + + Use this method to decline a chat join request. The bot must be an administrator in the chat for this to work and must have the *can_invite_users* administrator right. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#declinechatjoinrequest + + :return: instance of method :class:`aiogram.methods.decline_chat_join_request.DeclineChatJoinRequest` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import DeclineChatJoinRequest + + return DeclineChatJoinRequest( + chat_id=self.chat.id, + user_id=self.from_user.id, + **kwargs, + ).as_(self._bot) + + def answer( + self, + text: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[Union[LinkPreviewOptions, Default]] = Default( + "link_preview" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendMessage: + """ + Shortcut for method :class:`aiogram.methods.send_message.SendMessage` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send text messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendmessage + + :param text: Text of the message to be sent, 1-4096 characters after entities parsing + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param parse_mode: Mode for parsing entities in the message text. See `formatting options `_ for more details. + :param entities: A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode* + :param link_preview_options: Link preview generation options for the message + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param disable_web_page_preview: Disables link previews for links in this message + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_message.SendMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMessage + + return SendMessage( + chat_id=self.chat.id, + text=text, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + disable_web_page_preview=disable_web_page_preview, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_pm( + self, + text: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[Union[LinkPreviewOptions, Default]] = Default( + "link_preview" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendMessage: + """ + Shortcut for method :class:`aiogram.methods.send_message.SendMessage` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send text messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendmessage + + :param text: Text of the message to be sent, 1-4096 characters after entities parsing + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param parse_mode: Mode for parsing entities in the message text. See `formatting options `_ for more details. + :param entities: A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode* + :param link_preview_options: Link preview generation options for the message + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param disable_web_page_preview: Disables link previews for links in this message + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_message.SendMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMessage + + return SendMessage( + chat_id=self.user_chat_id, + text=text, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + disable_web_page_preview=disable_web_page_preview, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_animation( + self, + animation: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendAnimation: + """ + Shortcut for method :class:`aiogram.methods.send_animation.SendAnimation` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendanimation + + :param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent animation in seconds + :param width: Animation width + :param height: Animation height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Animation caption (may also be used when resending animation by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the animation caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the animation needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_animation.SendAnimation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAnimation + + return SendAnimation( + chat_id=self.chat.id, + animation=animation, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_animation_pm( + self, + animation: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendAnimation: + """ + Shortcut for method :class:`aiogram.methods.send_animation.SendAnimation` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendanimation + + :param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent animation in seconds + :param width: Animation width + :param height: Animation height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Animation caption (may also be used when resending animation by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the animation caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the animation needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_animation.SendAnimation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAnimation + + return SendAnimation( + chat_id=self.user_chat_id, + animation=animation, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_audio( + self, + audio: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendAudio: + """ + Shortcut for method :class:`aiogram.methods.send_audio.SendAudio` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + For sending voice messages, use the :class:`aiogram.methods.send_voice.SendVoice` method instead. + + Source: https://core.telegram.org/bots/api#sendaudio + + :param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Audio caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the audio caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the audio in seconds + :param performer: Performer + :param title: Track name + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_audio.SendAudio` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAudio + + return SendAudio( + chat_id=self.chat.id, + audio=audio, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_audio_pm( + self, + audio: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendAudio: + """ + Shortcut for method :class:`aiogram.methods.send_audio.SendAudio` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + For sending voice messages, use the :class:`aiogram.methods.send_voice.SendVoice` method instead. + + Source: https://core.telegram.org/bots/api#sendaudio + + :param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Audio caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the audio caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the audio in seconds + :param performer: Performer + :param title: Track name + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_audio.SendAudio` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAudio + + return SendAudio( + chat_id=self.user_chat_id, + audio=audio, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_contact( + self, + phone_number: str, + first_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendContact: + """ + Shortcut for method :class:`aiogram.methods.send_contact.SendContact` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send phone contacts. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendcontact + + :param phone_number: Contact's phone number + :param first_name: Contact's first name + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param last_name: Contact's last name + :param vcard: Additional data about the contact in the form of a `vCard `_, 0-2048 bytes + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_contact.SendContact` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendContact + + return SendContact( + chat_id=self.chat.id, + phone_number=phone_number, + first_name=first_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + last_name=last_name, + vcard=vcard, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_contact_pm( + self, + phone_number: str, + first_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendContact: + """ + Shortcut for method :class:`aiogram.methods.send_contact.SendContact` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send phone contacts. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendcontact + + :param phone_number: Contact's phone number + :param first_name: Contact's first name + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param last_name: Contact's last name + :param vcard: Additional data about the contact in the form of a `vCard `_, 0-2048 bytes + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_contact.SendContact` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendContact + + return SendContact( + chat_id=self.user_chat_id, + phone_number=phone_number, + first_name=first_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + last_name=last_name, + vcard=vcard, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_document( + self, + document: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendDocument: + """ + Shortcut for method :class:`aiogram.methods.send_document.SendDocument` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send general files. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#senddocument + + :param document: File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Document caption (may also be used when resending documents by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the document caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_document.SendDocument` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDocument + + return SendDocument( + chat_id=self.chat.id, + document=document, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_document_pm( + self, + document: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendDocument: + """ + Shortcut for method :class:`aiogram.methods.send_document.SendDocument` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send general files. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#senddocument + + :param document: File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Document caption (may also be used when resending documents by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the document caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_document.SendDocument` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDocument + + return SendDocument( + chat_id=self.user_chat_id, + document=document, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_game( + self, + game_short_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendGame: + """ + Shortcut for method :class:`aiogram.methods.send_game.SendGame` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a game. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendgame + + :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via `@BotFather `_. + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_game.SendGame` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendGame + + return SendGame( + chat_id=self.chat.id, + game_short_name=game_short_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_game_pm( + self, + game_short_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendGame: + """ + Shortcut for method :class:`aiogram.methods.send_game.SendGame` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a game. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendgame + + :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via `@BotFather `_. + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_game.SendGame` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendGame + + return SendGame( + chat_id=self.user_chat_id, + game_short_name=game_short_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_invoice( + self, + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + message_thread_id: Optional[int] = None, + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + start_parameter: Optional[str] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendInvoice: + """ + Shortcut for method :class:`aiogram.methods.send_invoice.SendInvoice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send invoices. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendinvoice + + :param title: Product name, 1-32 characters + :param description: Product description, 1-255 characters + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param currency: Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_. + :param prices: Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_. + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param provider_token: Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_. + :param max_tip_amount: The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_. + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*. + :param start_parameter: Unique deep-linking parameter. If left empty, **forwarded copies** of the sent message will have a *Pay* button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a *URL* button with a deep link to the bot (instead of a *Pay* button), with the value used as the start parameter + :param provider_data: JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size in bytes + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_phone_number: Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_email: Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_shipping_address: Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_. + :param send_phone_number_to_provider: Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param send_email_to_provider: Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param is_flexible: Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Pay :code:`total price`' button will be shown. If not empty, the first button must be a Pay button. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_invoice.SendInvoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendInvoice + + return SendInvoice( + chat_id=self.chat.id, + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + message_thread_id=message_thread_id, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + start_parameter=start_parameter, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_invoice_pm( + self, + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + message_thread_id: Optional[int] = None, + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + start_parameter: Optional[str] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendInvoice: + """ + Shortcut for method :class:`aiogram.methods.send_invoice.SendInvoice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send invoices. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendinvoice + + :param title: Product name, 1-32 characters + :param description: Product description, 1-255 characters + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param currency: Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_. + :param prices: Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_. + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param provider_token: Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_. + :param max_tip_amount: The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_. + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*. + :param start_parameter: Unique deep-linking parameter. If left empty, **forwarded copies** of the sent message will have a *Pay* button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a *URL* button with a deep link to the bot (instead of a *Pay* button), with the value used as the start parameter + :param provider_data: JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size in bytes + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_phone_number: Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_email: Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_shipping_address: Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_. + :param send_phone_number_to_provider: Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param send_email_to_provider: Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param is_flexible: Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Pay :code:`total price`' button will be shown. If not empty, the first button must be a Pay button. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_invoice.SendInvoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendInvoice + + return SendInvoice( + chat_id=self.user_chat_id, + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + message_thread_id=message_thread_id, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + start_parameter=start_parameter, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_location( + self, + latitude: float, + longitude: float, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendLocation: + """ + Shortcut for method :class:`aiogram.methods.send_location.SendLocation` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send point on the map. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendlocation + + :param latitude: Latitude of the location + :param longitude: Longitude of the location + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :param live_period: Period in seconds during which the location will be updated (see `Live Locations `_, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + :param heading: For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :param proximity_alert_radius: For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_location.SendLocation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendLocation + + return SendLocation( + chat_id=self.chat.id, + latitude=latitude, + longitude=longitude, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_location_pm( + self, + latitude: float, + longitude: float, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendLocation: + """ + Shortcut for method :class:`aiogram.methods.send_location.SendLocation` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send point on the map. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendlocation + + :param latitude: Latitude of the location + :param longitude: Longitude of the location + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :param live_period: Period in seconds during which the location will be updated (see `Live Locations `_, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + :param heading: For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :param proximity_alert_radius: For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_location.SendLocation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendLocation + + return SendLocation( + chat_id=self.user_chat_id, + latitude=latitude, + longitude=longitude, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_media_group( + self, + media: List[Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendMediaGroup: + """ + Shortcut for method :class:`aiogram.methods.send_media_group.SendMediaGroup` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of `Messages `_ that were sent is returned. + + Source: https://core.telegram.org/bots/api#sendmediagroup + + :param media: A JSON-serialized array describing messages to be sent, must include 2-10 items + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends messages `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent messages from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the messages are a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_media_group.SendMediaGroup` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMediaGroup + + return SendMediaGroup( + chat_id=self.chat.id, + media=media, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_media_group_pm( + self, + media: List[Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendMediaGroup: + """ + Shortcut for method :class:`aiogram.methods.send_media_group.SendMediaGroup` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of `Messages `_ that were sent is returned. + + Source: https://core.telegram.org/bots/api#sendmediagroup + + :param media: A JSON-serialized array describing messages to be sent, must include 2-10 items + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends messages `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent messages from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the messages are a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_media_group.SendMediaGroup` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMediaGroup + + return SendMediaGroup( + chat_id=self.user_chat_id, + media=media, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_photo( + self, + photo: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendPhoto: + """ + Shortcut for method :class:`aiogram.methods.send_photo.SendPhoto` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send photos. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendphoto + + :param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Photo caption (may also be used when resending photos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the photo caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the photo needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_photo.SendPhoto` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPhoto + + return SendPhoto( + chat_id=self.chat.id, + photo=photo, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_photo_pm( + self, + photo: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendPhoto: + """ + Shortcut for method :class:`aiogram.methods.send_photo.SendPhoto` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send photos. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendphoto + + :param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Photo caption (may also be used when resending photos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the photo caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the photo needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_photo.SendPhoto` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPhoto + + return SendPhoto( + chat_id=self.user_chat_id, + photo=photo, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_poll( + self, + question: str, + options: List[Union[InputPollOption, str]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + question_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + question_entities: Optional[List[MessageEntity]] = None, + is_anonymous: Optional[bool] = None, + type: Optional[str] = None, + allows_multiple_answers: Optional[bool] = None, + correct_option_id: Optional[int] = None, + explanation: Optional[str] = None, + explanation_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + explanation_entities: Optional[List[MessageEntity]] = None, + open_period: Optional[int] = None, + close_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + is_closed: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendPoll: + """ + Shortcut for method :class:`aiogram.methods.send_poll.SendPoll` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a native poll. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpoll + + :param question: Poll question, 1-300 characters + :param options: A JSON-serialized list of 2-10 answer options + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param question_parse_mode: Mode for parsing entities in the question. See `formatting options `_ for more details. Currently, only custom emoji entities are allowed + :param question_entities: A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of *question_parse_mode* + :param is_anonymous: :code:`True`, if the poll needs to be anonymous, defaults to :code:`True` + :param type: Poll type, 'quiz' or 'regular', defaults to 'regular' + :param allows_multiple_answers: :code:`True`, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to :code:`False` + :param correct_option_id: 0-based identifier of the correct answer option, required for polls in quiz mode + :param explanation: Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing + :param explanation_parse_mode: Mode for parsing entities in the explanation. See `formatting options `_ for more details. + :param explanation_entities: A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of *explanation_parse_mode* + :param open_period: Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with *close_date*. + :param close_date: Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with *open_period*. + :param is_closed: Pass :code:`True` if the poll needs to be immediately closed. This can be useful for poll preview. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_poll.SendPoll` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPoll + + return SendPoll( + chat_id=self.chat.id, + question=question, + options=options, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + question_parse_mode=question_parse_mode, + question_entities=question_entities, + is_anonymous=is_anonymous, + type=type, + allows_multiple_answers=allows_multiple_answers, + correct_option_id=correct_option_id, + explanation=explanation, + explanation_parse_mode=explanation_parse_mode, + explanation_entities=explanation_entities, + open_period=open_period, + close_date=close_date, + is_closed=is_closed, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_poll_pm( + self, + question: str, + options: List[Union[InputPollOption, str]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + question_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + question_entities: Optional[List[MessageEntity]] = None, + is_anonymous: Optional[bool] = None, + type: Optional[str] = None, + allows_multiple_answers: Optional[bool] = None, + correct_option_id: Optional[int] = None, + explanation: Optional[str] = None, + explanation_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + explanation_entities: Optional[List[MessageEntity]] = None, + open_period: Optional[int] = None, + close_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + is_closed: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendPoll: + """ + Shortcut for method :class:`aiogram.methods.send_poll.SendPoll` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a native poll. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpoll + + :param question: Poll question, 1-300 characters + :param options: A JSON-serialized list of 2-10 answer options + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param question_parse_mode: Mode for parsing entities in the question. See `formatting options `_ for more details. Currently, only custom emoji entities are allowed + :param question_entities: A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of *question_parse_mode* + :param is_anonymous: :code:`True`, if the poll needs to be anonymous, defaults to :code:`True` + :param type: Poll type, 'quiz' or 'regular', defaults to 'regular' + :param allows_multiple_answers: :code:`True`, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to :code:`False` + :param correct_option_id: 0-based identifier of the correct answer option, required for polls in quiz mode + :param explanation: Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing + :param explanation_parse_mode: Mode for parsing entities in the explanation. See `formatting options `_ for more details. + :param explanation_entities: A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of *explanation_parse_mode* + :param open_period: Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with *close_date*. + :param close_date: Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with *open_period*. + :param is_closed: Pass :code:`True` if the poll needs to be immediately closed. This can be useful for poll preview. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_poll.SendPoll` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPoll + + return SendPoll( + chat_id=self.user_chat_id, + question=question, + options=options, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + question_parse_mode=question_parse_mode, + question_entities=question_entities, + is_anonymous=is_anonymous, + type=type, + allows_multiple_answers=allows_multiple_answers, + correct_option_id=correct_option_id, + explanation=explanation, + explanation_parse_mode=explanation_parse_mode, + explanation_entities=explanation_entities, + open_period=open_period, + close_date=close_date, + is_closed=is_closed, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_dice( + self, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendDice: + """ + Shortcut for method :class:`aiogram.methods.send_dice.SendDice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send an animated emoji that will display a random value. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#senddice + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param emoji: Emoji on which the dice throw animation is based. Currently, must be one of '🎲', '🎯', '🏀', '⚽', '🎳', or '🎰'. Dice can have values 1-6 for '🎲', '🎯' and '🎳', values 1-5 for '🏀' and '⚽', and values 1-64 for '🎰'. Defaults to '🎲' + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_dice.SendDice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDice + + return SendDice( + chat_id=self.chat.id, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_dice_pm( + self, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendDice: + """ + Shortcut for method :class:`aiogram.methods.send_dice.SendDice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send an animated emoji that will display a random value. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#senddice + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param emoji: Emoji on which the dice throw animation is based. Currently, must be one of '🎲', '🎯', '🏀', '⚽', '🎳', or '🎰'. Dice can have values 1-6 for '🎲', '🎯' and '🎳', values 1-5 for '🏀' and '⚽', and values 1-64 for '🎰'. Defaults to '🎲' + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_dice.SendDice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDice + + return SendDice( + chat_id=self.user_chat_id, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_sticker( + self, + sticker: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendSticker: + """ + Shortcut for method :class:`aiogram.methods.send_sticker.SendSticker` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send static .WEBP, `animated `_ .TGS, or `video `_ .WEBM stickers. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendsticker + + :param sticker: Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. :ref:`More information on Sending Files » `. Video and animated stickers can't be sent via an HTTP URL. + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param emoji: Emoji associated with the sticker; only for just uploaded stickers + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_sticker.SendSticker` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendSticker + + return SendSticker( + chat_id=self.chat.id, + sticker=sticker, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_sticker_pm( + self, + sticker: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendSticker: + """ + Shortcut for method :class:`aiogram.methods.send_sticker.SendSticker` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send static .WEBP, `animated `_ .TGS, or `video `_ .WEBM stickers. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendsticker + + :param sticker: Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. :ref:`More information on Sending Files » `. Video and animated stickers can't be sent via an HTTP URL. + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param emoji: Emoji associated with the sticker; only for just uploaded stickers + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_sticker.SendSticker` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendSticker + + return SendSticker( + chat_id=self.user_chat_id, + sticker=sticker, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_venue( + self, + latitude: float, + longitude: float, + title: str, + address: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVenue: + """ + Shortcut for method :class:`aiogram.methods.send_venue.SendVenue` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send information about a venue. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvenue + + :param latitude: Latitude of the venue + :param longitude: Longitude of the venue + :param title: Name of the venue + :param address: Address of the venue + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param foursquare_id: Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.) + :param google_place_id: Google Places identifier of the venue + :param google_place_type: Google Places type of the venue. (See `supported types `_.) + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_venue.SendVenue` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVenue + + return SendVenue( + chat_id=self.chat.id, + latitude=latitude, + longitude=longitude, + title=title, + address=address, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_venue_pm( + self, + latitude: float, + longitude: float, + title: str, + address: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVenue: + """ + Shortcut for method :class:`aiogram.methods.send_venue.SendVenue` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send information about a venue. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvenue + + :param latitude: Latitude of the venue + :param longitude: Longitude of the venue + :param title: Name of the venue + :param address: Address of the venue + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param foursquare_id: Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.) + :param google_place_id: Google Places identifier of the venue + :param google_place_type: Google Places type of the venue. (See `supported types `_.) + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_venue.SendVenue` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVenue + + return SendVenue( + chat_id=self.user_chat_id, + latitude=latitude, + longitude=longitude, + title=title, + address=address, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_video( + self, + video: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + supports_streaming: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVideo: + """ + Shortcut for method :class:`aiogram.methods.send_video.SendVideo` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvideo + + :param video: Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent video in seconds + :param width: Video width + :param height: Video height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Video caption (may also be used when resending videos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the video caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the video needs to be covered with a spoiler animation + :param supports_streaming: Pass :code:`True` if the uploaded video is suitable for streaming + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_video.SendVideo` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideo + + return SendVideo( + chat_id=self.chat.id, + video=video, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + supports_streaming=supports_streaming, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_video_pm( + self, + video: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + supports_streaming: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVideo: + """ + Shortcut for method :class:`aiogram.methods.send_video.SendVideo` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvideo + + :param video: Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent video in seconds + :param width: Video width + :param height: Video height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Video caption (may also be used when resending videos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the video caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the video needs to be covered with a spoiler animation + :param supports_streaming: Pass :code:`True` if the uploaded video is suitable for streaming + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_video.SendVideo` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideo + + return SendVideo( + chat_id=self.user_chat_id, + video=video, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + supports_streaming=supports_streaming, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_video_note( + self, + video_note: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + length: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVideoNote: + """ + Shortcut for method :class:`aiogram.methods.send_video_note.SendVideoNote` + will automatically fill method attributes: + + - :code:`chat_id` + + As of `v.4.0 `_, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvideonote + + :param video_note: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. :ref:`More information on Sending Files » `. Sending video notes by a URL is currently unsupported + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent video in seconds + :param length: Video width and height, i.e. diameter of the video message + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_video_note.SendVideoNote` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideoNote + + return SendVideoNote( + chat_id=self.chat.id, + video_note=video_note, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + length=length, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_video_note_pm( + self, + video_note: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + length: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVideoNote: + """ + Shortcut for method :class:`aiogram.methods.send_video_note.SendVideoNote` + will automatically fill method attributes: + + - :code:`chat_id` + + As of `v.4.0 `_, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvideonote + + :param video_note: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. :ref:`More information on Sending Files » `. Sending video notes by a URL is currently unsupported + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent video in seconds + :param length: Video width and height, i.e. diameter of the video message + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_video_note.SendVideoNote` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideoNote + + return SendVideoNote( + chat_id=self.user_chat_id, + video_note=video_note, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + length=length, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_voice( + self, + voice: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVoice: + """ + Shortcut for method :class:`aiogram.methods.send_voice.SendVoice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as :class:`aiogram.types.audio.Audio` or :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvoice + + :param voice: Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Voice message caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the voice message caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the voice message in seconds + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_voice.SendVoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVoice + + return SendVoice( + chat_id=self.chat.id, + voice=voice, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_voice_pm( + self, + voice: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVoice: + """ + Shortcut for method :class:`aiogram.methods.send_voice.SendVoice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as :class:`aiogram.types.audio.Audio` or :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvoice + + :param voice: Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Voice message caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the voice message caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the voice message in seconds + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_voice.SendVoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVoice + + return SendVoice( + chat_id=self.user_chat_id, + voice=voice, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/chat_location.py b/env/Lib/site-packages/aiogram/types/chat_location.py new file mode 100644 index 0000000..ad64a3c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_location.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + +if TYPE_CHECKING: + from .location import Location + + +class ChatLocation(TelegramObject): + """ + Represents a location to which a chat is connected. + + Source: https://core.telegram.org/bots/api#chatlocation + """ + + location: Location + """The location to which the supergroup is connected. Can't be a live location.""" + address: str + """Location address; 1-64 characters, as defined by the chat owner""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, location: Location, address: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(location=location, address=address, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_member.py b/env/Lib/site-packages/aiogram/types/chat_member.py new file mode 100644 index 0000000..018bebd --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_member.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from .base import TelegramObject + + +class ChatMember(TelegramObject): + """ + This object contains information about one member of a chat. Currently, the following 6 types of chat members are supported: + + - :class:`aiogram.types.chat_member_owner.ChatMemberOwner` + - :class:`aiogram.types.chat_member_administrator.ChatMemberAdministrator` + - :class:`aiogram.types.chat_member_member.ChatMemberMember` + - :class:`aiogram.types.chat_member_restricted.ChatMemberRestricted` + - :class:`aiogram.types.chat_member_left.ChatMemberLeft` + - :class:`aiogram.types.chat_member_banned.ChatMemberBanned` + + Source: https://core.telegram.org/bots/api#chatmember + """ diff --git a/env/Lib/site-packages/aiogram/types/chat_member_administrator.py b/env/Lib/site-packages/aiogram/types/chat_member_administrator.py new file mode 100644 index 0000000..10552f7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_member_administrator.py @@ -0,0 +1,111 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from ..enums import ChatMemberStatus +from .chat_member import ChatMember + +if TYPE_CHECKING: + from .user import User + + +class ChatMemberAdministrator(ChatMember): + """ + Represents a `chat member `_ that has some additional privileges. + + Source: https://core.telegram.org/bots/api#chatmemberadministrator + """ + + status: Literal[ChatMemberStatus.ADMINISTRATOR] = ChatMemberStatus.ADMINISTRATOR + """The member's status in the chat, always 'administrator'""" + user: User + """Information about the user""" + can_be_edited: bool + """:code:`True`, if the bot is allowed to edit administrator privileges of that user""" + is_anonymous: bool + """:code:`True`, if the user's presence in the chat is hidden""" + can_manage_chat: bool + """:code:`True`, if the administrator can access the chat event log, get boost list, see hidden supergroup and channel members, report spam messages and ignore slow mode. Implied by any other administrator privilege.""" + can_delete_messages: bool + """:code:`True`, if the administrator can delete messages of other users""" + can_manage_video_chats: bool + """:code:`True`, if the administrator can manage video chats""" + can_restrict_members: bool + """:code:`True`, if the administrator can restrict, ban or unban chat members, or access supergroup statistics""" + can_promote_members: bool + """:code:`True`, if the administrator can add new administrators with a subset of their own privileges or demote administrators that they have promoted, directly or indirectly (promoted by administrators that were appointed by the user)""" + can_change_info: bool + """:code:`True`, if the user is allowed to change the chat title, photo and other settings""" + can_invite_users: bool + """:code:`True`, if the user is allowed to invite new users to the chat""" + can_post_stories: bool + """:code:`True`, if the administrator can post stories to the chat""" + can_edit_stories: bool + """:code:`True`, if the administrator can edit stories posted by other users, post stories to the chat page, pin chat stories, and access the chat's story archive""" + can_delete_stories: bool + """:code:`True`, if the administrator can delete stories posted by other users""" + can_post_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the administrator can post messages in the channel, or access channel statistics; for channels only""" + can_edit_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the administrator can edit messages of other users and can pin messages; for channels only""" + can_pin_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to pin messages; for groups and supergroups only""" + can_manage_topics: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to create, rename, close, and reopen forum topics; for supergroups only""" + custom_title: Optional[str] = None + """*Optional*. Custom title for this user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + status: Literal[ChatMemberStatus.ADMINISTRATOR] = ChatMemberStatus.ADMINISTRATOR, + user: User, + can_be_edited: bool, + is_anonymous: bool, + can_manage_chat: bool, + can_delete_messages: bool, + can_manage_video_chats: bool, + can_restrict_members: bool, + can_promote_members: bool, + can_change_info: bool, + can_invite_users: bool, + can_post_stories: bool, + can_edit_stories: bool, + can_delete_stories: bool, + can_post_messages: Optional[bool] = None, + can_edit_messages: Optional[bool] = None, + can_pin_messages: Optional[bool] = None, + can_manage_topics: Optional[bool] = None, + custom_title: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + status=status, + user=user, + can_be_edited=can_be_edited, + is_anonymous=is_anonymous, + can_manage_chat=can_manage_chat, + can_delete_messages=can_delete_messages, + can_manage_video_chats=can_manage_video_chats, + can_restrict_members=can_restrict_members, + can_promote_members=can_promote_members, + can_change_info=can_change_info, + can_invite_users=can_invite_users, + can_post_stories=can_post_stories, + can_edit_stories=can_edit_stories, + can_delete_stories=can_delete_stories, + can_post_messages=can_post_messages, + can_edit_messages=can_edit_messages, + can_pin_messages=can_pin_messages, + can_manage_topics=can_manage_topics, + custom_title=custom_title, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_member_banned.py b/env/Lib/site-packages/aiogram/types/chat_member_banned.py new file mode 100644 index 0000000..65776c5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_member_banned.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import ChatMemberStatus +from .chat_member import ChatMember +from .custom import DateTime + +if TYPE_CHECKING: + from .user import User + + +class ChatMemberBanned(ChatMember): + """ + Represents a `chat member `_ that was banned in the chat and can't return to the chat or view chat messages. + + Source: https://core.telegram.org/bots/api#chatmemberbanned + """ + + status: Literal[ChatMemberStatus.KICKED] = ChatMemberStatus.KICKED + """The member's status in the chat, always 'kicked'""" + user: User + """Information about the user""" + until_date: DateTime + """Date when restrictions will be lifted for this user; Unix time. If 0, then the user is banned forever""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + status: Literal[ChatMemberStatus.KICKED] = ChatMemberStatus.KICKED, + user: User, + until_date: DateTime, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(status=status, user=user, until_date=until_date, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_member_left.py b/env/Lib/site-packages/aiogram/types/chat_member_left.py new file mode 100644 index 0000000..3870d17 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_member_left.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import ChatMemberStatus +from .chat_member import ChatMember + +if TYPE_CHECKING: + from .user import User + + +class ChatMemberLeft(ChatMember): + """ + Represents a `chat member `_ that isn't currently a member of the chat, but may join it themselves. + + Source: https://core.telegram.org/bots/api#chatmemberleft + """ + + status: Literal[ChatMemberStatus.LEFT] = ChatMemberStatus.LEFT + """The member's status in the chat, always 'left'""" + user: User + """Information about the user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + status: Literal[ChatMemberStatus.LEFT] = ChatMemberStatus.LEFT, + user: User, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(status=status, user=user, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_member_member.py b/env/Lib/site-packages/aiogram/types/chat_member_member.py new file mode 100644 index 0000000..12ef33e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_member_member.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from ..enums import ChatMemberStatus +from .chat_member import ChatMember +from .custom import DateTime + +if TYPE_CHECKING: + from .user import User + + +class ChatMemberMember(ChatMember): + """ + Represents a `chat member `_ that has no additional privileges or restrictions. + + Source: https://core.telegram.org/bots/api#chatmembermember + """ + + status: Literal[ChatMemberStatus.MEMBER] = ChatMemberStatus.MEMBER + """The member's status in the chat, always 'member'""" + user: User + """Information about the user""" + until_date: Optional[DateTime] = None + """*Optional*. Date when the user's subscription will expire; Unix time""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + status: Literal[ChatMemberStatus.MEMBER] = ChatMemberStatus.MEMBER, + user: User, + until_date: Optional[DateTime] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(status=status, user=user, until_date=until_date, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/chat_member_owner.py b/env/Lib/site-packages/aiogram/types/chat_member_owner.py new file mode 100644 index 0000000..1429435 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_member_owner.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from ..enums import ChatMemberStatus +from .chat_member import ChatMember + +if TYPE_CHECKING: + from .user import User + + +class ChatMemberOwner(ChatMember): + """ + Represents a `chat member `_ that owns the chat and has all administrator privileges. + + Source: https://core.telegram.org/bots/api#chatmemberowner + """ + + status: Literal[ChatMemberStatus.CREATOR] = ChatMemberStatus.CREATOR + """The member's status in the chat, always 'creator'""" + user: User + """Information about the user""" + is_anonymous: bool + """:code:`True`, if the user's presence in the chat is hidden""" + custom_title: Optional[str] = None + """*Optional*. Custom title for this user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + status: Literal[ChatMemberStatus.CREATOR] = ChatMemberStatus.CREATOR, + user: User, + is_anonymous: bool, + custom_title: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + status=status, + user=user, + is_anonymous=is_anonymous, + custom_title=custom_title, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_member_restricted.py b/env/Lib/site-packages/aiogram/types/chat_member_restricted.py new file mode 100644 index 0000000..edda75e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_member_restricted.py @@ -0,0 +1,108 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import ChatMemberStatus +from .chat_member import ChatMember +from .custom import DateTime + +if TYPE_CHECKING: + from .user import User + + +class ChatMemberRestricted(ChatMember): + """ + Represents a `chat member `_ that is under certain restrictions in the chat. Supergroups only. + + Source: https://core.telegram.org/bots/api#chatmemberrestricted + """ + + status: Literal[ChatMemberStatus.RESTRICTED] = ChatMemberStatus.RESTRICTED + """The member's status in the chat, always 'restricted'""" + user: User + """Information about the user""" + is_member: bool + """:code:`True`, if the user is a member of the chat at the moment of the request""" + can_send_messages: bool + """:code:`True`, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues""" + can_send_audios: bool + """:code:`True`, if the user is allowed to send audios""" + can_send_documents: bool + """:code:`True`, if the user is allowed to send documents""" + can_send_photos: bool + """:code:`True`, if the user is allowed to send photos""" + can_send_videos: bool + """:code:`True`, if the user is allowed to send videos""" + can_send_video_notes: bool + """:code:`True`, if the user is allowed to send video notes""" + can_send_voice_notes: bool + """:code:`True`, if the user is allowed to send voice notes""" + can_send_polls: bool + """:code:`True`, if the user is allowed to send polls""" + can_send_other_messages: bool + """:code:`True`, if the user is allowed to send animations, games, stickers and use inline bots""" + can_add_web_page_previews: bool + """:code:`True`, if the user is allowed to add web page previews to their messages""" + can_change_info: bool + """:code:`True`, if the user is allowed to change the chat title, photo and other settings""" + can_invite_users: bool + """:code:`True`, if the user is allowed to invite new users to the chat""" + can_pin_messages: bool + """:code:`True`, if the user is allowed to pin messages""" + can_manage_topics: bool + """:code:`True`, if the user is allowed to create forum topics""" + until_date: DateTime + """Date when restrictions will be lifted for this user; Unix time. If 0, then the user is restricted forever""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + status: Literal[ChatMemberStatus.RESTRICTED] = ChatMemberStatus.RESTRICTED, + user: User, + is_member: bool, + can_send_messages: bool, + can_send_audios: bool, + can_send_documents: bool, + can_send_photos: bool, + can_send_videos: bool, + can_send_video_notes: bool, + can_send_voice_notes: bool, + can_send_polls: bool, + can_send_other_messages: bool, + can_add_web_page_previews: bool, + can_change_info: bool, + can_invite_users: bool, + can_pin_messages: bool, + can_manage_topics: bool, + until_date: DateTime, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + status=status, + user=user, + is_member=is_member, + can_send_messages=can_send_messages, + can_send_audios=can_send_audios, + can_send_documents=can_send_documents, + can_send_photos=can_send_photos, + can_send_videos=can_send_videos, + can_send_video_notes=can_send_video_notes, + can_send_voice_notes=can_send_voice_notes, + can_send_polls=can_send_polls, + can_send_other_messages=can_send_other_messages, + can_add_web_page_previews=can_add_web_page_previews, + can_change_info=can_change_info, + can_invite_users=can_invite_users, + can_pin_messages=can_pin_messages, + can_manage_topics=can_manage_topics, + until_date=until_date, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_member_updated.py b/env/Lib/site-packages/aiogram/types/chat_member_updated.py new file mode 100644 index 0000000..48c3e9d --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_member_updated.py @@ -0,0 +1,1413 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from ..methods import ( + SendAnimation, + SendAudio, + SendContact, + SendDice, + SendDocument, + SendGame, + SendInvoice, + SendLocation, + SendMediaGroup, + SendMessage, + SendPhoto, + SendPoll, + SendSticker, + SendVenue, + SendVideo, + SendVideoNote, + SendVoice, + ) + from .chat import Chat + from .chat_invite_link import ChatInviteLink + from .chat_member_administrator import ChatMemberAdministrator + from .chat_member_banned import ChatMemberBanned + from .chat_member_left import ChatMemberLeft + from .chat_member_member import ChatMemberMember + from .chat_member_owner import ChatMemberOwner + from .chat_member_restricted import ChatMemberRestricted + from .force_reply import ForceReply + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_file import InputFile + from .input_media_audio import InputMediaAudio + from .input_media_document import InputMediaDocument + from .input_media_photo import InputMediaPhoto + from .input_media_video import InputMediaVideo + from .input_poll_option import InputPollOption + from .labeled_price import LabeledPrice + from .link_preview_options import LinkPreviewOptions + from .message_entity import MessageEntity + from .reply_keyboard_markup import ReplyKeyboardMarkup + from .reply_keyboard_remove import ReplyKeyboardRemove + from .reply_parameters import ReplyParameters + from .user import User + + +class ChatMemberUpdated(TelegramObject): + """ + This object represents changes in the status of a chat member. + + Source: https://core.telegram.org/bots/api#chatmemberupdated + """ + + chat: Chat + """Chat the user belongs to""" + from_user: User = Field(..., alias="from") + """Performer of the action, which resulted in the change""" + date: DateTime + """Date the change was done in Unix time""" + old_chat_member: Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ] + """Previous information about the chat member""" + new_chat_member: Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ] + """New information about the chat member""" + invite_link: Optional[ChatInviteLink] = None + """*Optional*. Chat invite link, which was used by the user to join the chat; for joining by invite link events only.""" + via_join_request: Optional[bool] = None + """*Optional*. True, if the user joined the chat after sending a direct join request without using an invite link and being approved by an administrator""" + via_chat_folder_invite_link: Optional[bool] = None + """*Optional*. True, if the user joined the chat via a chat folder invite link""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat: Chat, + from_user: User, + date: DateTime, + old_chat_member: Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ], + new_chat_member: Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, + ], + invite_link: Optional[ChatInviteLink] = None, + via_join_request: Optional[bool] = None, + via_chat_folder_invite_link: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat=chat, + from_user=from_user, + date=date, + old_chat_member=old_chat_member, + new_chat_member=new_chat_member, + invite_link=invite_link, + via_join_request=via_join_request, + via_chat_folder_invite_link=via_chat_folder_invite_link, + **__pydantic_kwargs, + ) + + def answer( + self, + text: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[Union[LinkPreviewOptions, Default]] = Default( + "link_preview" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendMessage: + """ + Shortcut for method :class:`aiogram.methods.send_message.SendMessage` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send text messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendmessage + + :param text: Text of the message to be sent, 1-4096 characters after entities parsing + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param parse_mode: Mode for parsing entities in the message text. See `formatting options `_ for more details. + :param entities: A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode* + :param link_preview_options: Link preview generation options for the message + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param disable_web_page_preview: Disables link previews for links in this message + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_message.SendMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMessage + + return SendMessage( + chat_id=self.chat.id, + text=text, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + disable_web_page_preview=disable_web_page_preview, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_animation( + self, + animation: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendAnimation: + """ + Shortcut for method :class:`aiogram.methods.send_animation.SendAnimation` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendanimation + + :param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent animation in seconds + :param width: Animation width + :param height: Animation height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Animation caption (may also be used when resending animation by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the animation caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the animation needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_animation.SendAnimation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAnimation + + return SendAnimation( + chat_id=self.chat.id, + animation=animation, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_audio( + self, + audio: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendAudio: + """ + Shortcut for method :class:`aiogram.methods.send_audio.SendAudio` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + For sending voice messages, use the :class:`aiogram.methods.send_voice.SendVoice` method instead. + + Source: https://core.telegram.org/bots/api#sendaudio + + :param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Audio caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the audio caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the audio in seconds + :param performer: Performer + :param title: Track name + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_audio.SendAudio` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAudio + + return SendAudio( + chat_id=self.chat.id, + audio=audio, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_contact( + self, + phone_number: str, + first_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendContact: + """ + Shortcut for method :class:`aiogram.methods.send_contact.SendContact` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send phone contacts. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendcontact + + :param phone_number: Contact's phone number + :param first_name: Contact's first name + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param last_name: Contact's last name + :param vcard: Additional data about the contact in the form of a `vCard `_, 0-2048 bytes + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_contact.SendContact` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendContact + + return SendContact( + chat_id=self.chat.id, + phone_number=phone_number, + first_name=first_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + last_name=last_name, + vcard=vcard, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_document( + self, + document: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendDocument: + """ + Shortcut for method :class:`aiogram.methods.send_document.SendDocument` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send general files. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#senddocument + + :param document: File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Document caption (may also be used when resending documents by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the document caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_document.SendDocument` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDocument + + return SendDocument( + chat_id=self.chat.id, + document=document, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_game( + self, + game_short_name: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendGame: + """ + Shortcut for method :class:`aiogram.methods.send_game.SendGame` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a game. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendgame + + :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via `@BotFather `_. + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_game.SendGame` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendGame + + return SendGame( + chat_id=self.chat.id, + game_short_name=game_short_name, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_invoice( + self, + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + message_thread_id: Optional[int] = None, + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + start_parameter: Optional[str] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendInvoice: + """ + Shortcut for method :class:`aiogram.methods.send_invoice.SendInvoice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send invoices. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendinvoice + + :param title: Product name, 1-32 characters + :param description: Product description, 1-255 characters + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param currency: Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_. + :param prices: Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_. + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param provider_token: Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_. + :param max_tip_amount: The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_. + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*. + :param start_parameter: Unique deep-linking parameter. If left empty, **forwarded copies** of the sent message will have a *Pay* button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a *URL* button with a deep link to the bot (instead of a *Pay* button), with the value used as the start parameter + :param provider_data: JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size in bytes + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_phone_number: Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_email: Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_shipping_address: Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_. + :param send_phone_number_to_provider: Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param send_email_to_provider: Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param is_flexible: Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Pay :code:`total price`' button will be shown. If not empty, the first button must be a Pay button. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_invoice.SendInvoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendInvoice + + return SendInvoice( + chat_id=self.chat.id, + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + message_thread_id=message_thread_id, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + start_parameter=start_parameter, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_location( + self, + latitude: float, + longitude: float, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendLocation: + """ + Shortcut for method :class:`aiogram.methods.send_location.SendLocation` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send point on the map. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendlocation + + :param latitude: Latitude of the location + :param longitude: Longitude of the location + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :param live_period: Period in seconds during which the location will be updated (see `Live Locations `_, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + :param heading: For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :param proximity_alert_radius: For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_location.SendLocation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendLocation + + return SendLocation( + chat_id=self.chat.id, + latitude=latitude, + longitude=longitude, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_media_group( + self, + media: List[Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendMediaGroup: + """ + Shortcut for method :class:`aiogram.methods.send_media_group.SendMediaGroup` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of `Messages `_ that were sent is returned. + + Source: https://core.telegram.org/bots/api#sendmediagroup + + :param media: A JSON-serialized array describing messages to be sent, must include 2-10 items + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends messages `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent messages from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the messages are a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_media_group.SendMediaGroup` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMediaGroup + + return SendMediaGroup( + chat_id=self.chat.id, + media=media, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_photo( + self, + photo: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendPhoto: + """ + Shortcut for method :class:`aiogram.methods.send_photo.SendPhoto` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send photos. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendphoto + + :param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Photo caption (may also be used when resending photos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the photo caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the photo needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_photo.SendPhoto` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPhoto + + return SendPhoto( + chat_id=self.chat.id, + photo=photo, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_poll( + self, + question: str, + options: List[Union[InputPollOption, str]], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + question_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + question_entities: Optional[List[MessageEntity]] = None, + is_anonymous: Optional[bool] = None, + type: Optional[str] = None, + allows_multiple_answers: Optional[bool] = None, + correct_option_id: Optional[int] = None, + explanation: Optional[str] = None, + explanation_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + explanation_entities: Optional[List[MessageEntity]] = None, + open_period: Optional[int] = None, + close_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + is_closed: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendPoll: + """ + Shortcut for method :class:`aiogram.methods.send_poll.SendPoll` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send a native poll. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpoll + + :param question: Poll question, 1-300 characters + :param options: A JSON-serialized list of 2-10 answer options + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param question_parse_mode: Mode for parsing entities in the question. See `formatting options `_ for more details. Currently, only custom emoji entities are allowed + :param question_entities: A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of *question_parse_mode* + :param is_anonymous: :code:`True`, if the poll needs to be anonymous, defaults to :code:`True` + :param type: Poll type, 'quiz' or 'regular', defaults to 'regular' + :param allows_multiple_answers: :code:`True`, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to :code:`False` + :param correct_option_id: 0-based identifier of the correct answer option, required for polls in quiz mode + :param explanation: Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing + :param explanation_parse_mode: Mode for parsing entities in the explanation. See `formatting options `_ for more details. + :param explanation_entities: A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of *explanation_parse_mode* + :param open_period: Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with *close_date*. + :param close_date: Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with *open_period*. + :param is_closed: Pass :code:`True` if the poll needs to be immediately closed. This can be useful for poll preview. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_poll.SendPoll` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPoll + + return SendPoll( + chat_id=self.chat.id, + question=question, + options=options, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + question_parse_mode=question_parse_mode, + question_entities=question_entities, + is_anonymous=is_anonymous, + type=type, + allows_multiple_answers=allows_multiple_answers, + correct_option_id=correct_option_id, + explanation=explanation, + explanation_parse_mode=explanation_parse_mode, + explanation_entities=explanation_entities, + open_period=open_period, + close_date=close_date, + is_closed=is_closed, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_dice( + self, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendDice: + """ + Shortcut for method :class:`aiogram.methods.send_dice.SendDice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send an animated emoji that will display a random value. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#senddice + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param emoji: Emoji on which the dice throw animation is based. Currently, must be one of '🎲', '🎯', '🏀', '⚽', '🎳', or '🎰'. Dice can have values 1-6 for '🎲', '🎯' and '🎳', values 1-5 for '🏀' and '⚽', and values 1-64 for '🎰'. Defaults to '🎲' + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_dice.SendDice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDice + + return SendDice( + chat_id=self.chat.id, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_sticker( + self, + sticker: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendSticker: + """ + Shortcut for method :class:`aiogram.methods.send_sticker.SendSticker` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send static .WEBP, `animated `_ .TGS, or `video `_ .WEBM stickers. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendsticker + + :param sticker: Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. :ref:`More information on Sending Files » `. Video and animated stickers can't be sent via an HTTP URL. + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param emoji: Emoji associated with the sticker; only for just uploaded stickers + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_sticker.SendSticker` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendSticker + + return SendSticker( + chat_id=self.chat.id, + sticker=sticker, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_venue( + self, + latitude: float, + longitude: float, + title: str, + address: str, + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVenue: + """ + Shortcut for method :class:`aiogram.methods.send_venue.SendVenue` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send information about a venue. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvenue + + :param latitude: Latitude of the venue + :param longitude: Longitude of the venue + :param title: Name of the venue + :param address: Address of the venue + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param foursquare_id: Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.) + :param google_place_id: Google Places identifier of the venue + :param google_place_type: Google Places type of the venue. (See `supported types `_.) + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_venue.SendVenue` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVenue + + return SendVenue( + chat_id=self.chat.id, + latitude=latitude, + longitude=longitude, + title=title, + address=address, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_video( + self, + video: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + supports_streaming: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVideo: + """ + Shortcut for method :class:`aiogram.methods.send_video.SendVideo` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvideo + + :param video: Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent video in seconds + :param width: Video width + :param height: Video height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Video caption (may also be used when resending videos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the video caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the video needs to be covered with a spoiler animation + :param supports_streaming: Pass :code:`True` if the uploaded video is suitable for streaming + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_video.SendVideo` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideo + + return SendVideo( + chat_id=self.chat.id, + video=video, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + supports_streaming=supports_streaming, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_video_note( + self, + video_note: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + duration: Optional[int] = None, + length: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVideoNote: + """ + Shortcut for method :class:`aiogram.methods.send_video_note.SendVideoNote` + will automatically fill method attributes: + + - :code:`chat_id` + + As of `v.4.0 `_, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvideonote + + :param video_note: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. :ref:`More information on Sending Files » `. Sending video notes by a URL is currently unsupported + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param duration: Duration of sent video in seconds + :param length: Video width and height, i.e. diameter of the video message + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_video_note.SendVideoNote` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideoNote + + return SendVideoNote( + chat_id=self.chat.id, + video_note=video_note, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + duration=duration, + length=length, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def answer_voice( + self, + voice: Union[InputFile, str], + business_connection_id: Optional[str] = None, + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVoice: + """ + Shortcut for method :class:`aiogram.methods.send_voice.SendVoice` + will automatically fill method attributes: + + - :code:`chat_id` + + Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as :class:`aiogram.types.audio.Audio` or :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvoice + + :param voice: Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be sent + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: Voice message caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the voice message caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the voice message in seconds + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_voice.SendVoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVoice + + return SendVoice( + chat_id=self.chat.id, + voice=voice, + business_connection_id=business_connection_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/chat_permissions.py b/env/Lib/site-packages/aiogram/types/chat_permissions.py new file mode 100644 index 0000000..6270cc3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_permissions.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import MutableTelegramObject + + +class ChatPermissions(MutableTelegramObject): + """ + Describes actions that a non-administrator user is allowed to take in a chat. + + Source: https://core.telegram.org/bots/api#chatpermissions + """ + + can_send_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send text messages, contacts, giveaways, giveaway winners, invoices, locations and venues""" + can_send_audios: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send audios""" + can_send_documents: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send documents""" + can_send_photos: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send photos""" + can_send_videos: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send videos""" + can_send_video_notes: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send video notes""" + can_send_voice_notes: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send voice notes""" + can_send_polls: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send polls""" + can_send_other_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to send animations, games, stickers and use inline bots""" + can_add_web_page_previews: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to add web page previews to their messages""" + can_change_info: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to change the chat title, photo and other settings. Ignored in public supergroups""" + can_invite_users: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to invite new users to the chat""" + can_pin_messages: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to pin messages. Ignored in public supergroups""" + can_manage_topics: Optional[bool] = None + """*Optional*. :code:`True`, if the user is allowed to create forum topics. If omitted defaults to the value of can_pin_messages""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + can_send_messages: Optional[bool] = None, + can_send_audios: Optional[bool] = None, + can_send_documents: Optional[bool] = None, + can_send_photos: Optional[bool] = None, + can_send_videos: Optional[bool] = None, + can_send_video_notes: Optional[bool] = None, + can_send_voice_notes: Optional[bool] = None, + can_send_polls: Optional[bool] = None, + can_send_other_messages: Optional[bool] = None, + can_add_web_page_previews: Optional[bool] = None, + can_change_info: Optional[bool] = None, + can_invite_users: Optional[bool] = None, + can_pin_messages: Optional[bool] = None, + can_manage_topics: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + can_send_messages=can_send_messages, + can_send_audios=can_send_audios, + can_send_documents=can_send_documents, + can_send_photos=can_send_photos, + can_send_videos=can_send_videos, + can_send_video_notes=can_send_video_notes, + can_send_voice_notes=can_send_voice_notes, + can_send_polls=can_send_polls, + can_send_other_messages=can_send_other_messages, + can_add_web_page_previews=can_add_web_page_previews, + can_change_info=can_change_info, + can_invite_users=can_invite_users, + can_pin_messages=can_pin_messages, + can_manage_topics=can_manage_topics, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_photo.py b/env/Lib/site-packages/aiogram/types/chat_photo.py new file mode 100644 index 0000000..1a64aeb --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_photo.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class ChatPhoto(TelegramObject): + """ + This object represents a chat photo. + + Source: https://core.telegram.org/bots/api#chatphoto + """ + + small_file_id: str + """File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.""" + small_file_unique_id: str + """Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + big_file_id: str + """File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.""" + big_file_unique_id: str + """Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + small_file_id: str, + small_file_unique_id: str, + big_file_id: str, + big_file_unique_id: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + small_file_id=small_file_id, + small_file_unique_id=small_file_unique_id, + big_file_id=big_file_id, + big_file_unique_id=big_file_unique_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chat_shared.py b/env/Lib/site-packages/aiogram/types/chat_shared.py new file mode 100644 index 0000000..92d6231 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chat_shared.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from aiogram.types import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class ChatShared(TelegramObject): + """ + This object contains information about a chat that was shared with the bot using a :class:`aiogram.types.keyboard_button_request_chat.KeyboardButtonRequestChat` button. + + Source: https://core.telegram.org/bots/api#chatshared + """ + + request_id: int + """Identifier of the request""" + chat_id: int + """Identifier of the shared chat. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot may not have access to the chat and could be unable to use this identifier, unless the chat is already known to the bot by some other means.""" + title: Optional[str] = None + """*Optional*. Title of the chat, if the title was requested by the bot.""" + username: Optional[str] = None + """*Optional*. Username of the chat, if the username was requested by the bot and available.""" + photo: Optional[List[PhotoSize]] = None + """*Optional*. Available sizes of the chat photo, if the photo was requested by the bot""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + request_id: int, + chat_id: int, + title: Optional[str] = None, + username: Optional[str] = None, + photo: Optional[List[PhotoSize]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + request_id=request_id, + chat_id=chat_id, + title=title, + username=username, + photo=photo, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/chosen_inline_result.py b/env/Lib/site-packages/aiogram/types/chosen_inline_result.py new file mode 100644 index 0000000..510a0e1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/chosen_inline_result.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from pydantic import Field + +from .base import TelegramObject + +if TYPE_CHECKING: + from .location import Location + from .user import User + + +class ChosenInlineResult(TelegramObject): + """ + Represents a `result `_ of an inline query that was chosen by the user and sent to their chat partner. + **Note:** It is necessary to enable `inline feedback `_ via `@BotFather `_ in order to receive these objects in updates. + + Source: https://core.telegram.org/bots/api#choseninlineresult + """ + + result_id: str + """The unique identifier for the result that was chosen""" + from_user: User = Field(..., alias="from") + """The user that chose the result""" + query: str + """The query that was used to obtain the result""" + location: Optional[Location] = None + """*Optional*. Sender location, only for bots that require user location""" + inline_message_id: Optional[str] = None + """*Optional*. Identifier of the sent inline message. Available only if there is an `inline keyboard `_ attached to the message. Will be also received in `callback queries `_ and can be used to `edit `_ the message.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + result_id: str, + from_user: User, + query: str, + location: Optional[Location] = None, + inline_message_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + result_id=result_id, + from_user=from_user, + query=query, + location=location, + inline_message_id=inline_message_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/contact.py b/env/Lib/site-packages/aiogram/types/contact.py new file mode 100644 index 0000000..1fb7f83 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/contact.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class Contact(TelegramObject): + """ + This object represents a phone contact. + + Source: https://core.telegram.org/bots/api#contact + """ + + phone_number: str + """Contact's phone number""" + first_name: str + """Contact's first name""" + last_name: Optional[str] = None + """*Optional*. Contact's last name""" + user_id: Optional[int] = None + """*Optional*. Contact's user identifier in Telegram. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.""" + vcard: Optional[str] = None + """*Optional*. Additional data about the contact in the form of a `vCard `_""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + phone_number: str, + first_name: str, + last_name: Optional[str] = None, + user_id: Optional[int] = None, + vcard: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + phone_number=phone_number, + first_name=first_name, + last_name=last_name, + user_id=user_id, + vcard=vcard, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/custom.py b/env/Lib/site-packages/aiogram/types/custom.py new file mode 100644 index 0000000..8617fa6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/custom.py @@ -0,0 +1,30 @@ +import sys +from datetime import datetime, timezone + +from pydantic import PlainSerializer +from typing_extensions import Annotated + +if sys.platform == "win32": # pragma: no cover + + def _datetime_serializer(value: datetime) -> int: + tz = timezone.utc if value.tzinfo else None + + # https://github.com/aiogram/aiogram/issues/349 + # https://github.com/aiogram/aiogram/pull/880 + return round((value - datetime(1970, 1, 1, tzinfo=tz)).total_seconds()) + +else: # pragma: no cover + + def _datetime_serializer(value: datetime) -> int: + return round(value.timestamp()) + + +# Make datetime compatible with Telegram Bot API (unixtime) +DateTime = Annotated[ + datetime, + PlainSerializer( + func=_datetime_serializer, + return_type=int, + when_used="unless-none", + ), +] diff --git a/env/Lib/site-packages/aiogram/types/dice.py b/env/Lib/site-packages/aiogram/types/dice.py new file mode 100644 index 0000000..56b84f4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/dice.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class Dice(TelegramObject): + """ + This object represents an animated emoji that displays a random value. + + Source: https://core.telegram.org/bots/api#dice + """ + + emoji: str + """Emoji on which the dice throw animation is based""" + value: int + """Value of the dice, 1-6 for '🎲', '🎯' and '🎳' base emoji, 1-5 for '🏀' and '⚽' base emoji, 1-64 for '🎰' base emoji""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, emoji: str, value: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(emoji=emoji, value=value, **__pydantic_kwargs) + + +class DiceEmoji: + DICE = "🎲" + DART = "🎯" + BASKETBALL = "🏀" + FOOTBALL = "⚽" + SLOT_MACHINE = "🎰" + BOWLING = "🎳" diff --git a/env/Lib/site-packages/aiogram/types/document.py b/env/Lib/site-packages/aiogram/types/document.py new file mode 100644 index 0000000..18acff7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/document.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class Document(TelegramObject): + """ + This object represents a general file (as opposed to `photos `_, `voice messages `_ and `audio files `_). + + Source: https://core.telegram.org/bots/api#document + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + thumbnail: Optional[PhotoSize] = None + """*Optional*. Document thumbnail as defined by the sender""" + file_name: Optional[str] = None + """*Optional*. Original filename as defined by the sender""" + mime_type: Optional[str] = None + """*Optional*. MIME type of the file as defined by the sender""" + file_size: Optional[int] = None + """*Optional*. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + thumbnail: Optional[PhotoSize] = None, + file_name: Optional[str] = None, + mime_type: Optional[str] = None, + file_size: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + thumbnail=thumbnail, + file_name=file_name, + mime_type=mime_type, + file_size=file_size, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/downloadable.py b/env/Lib/site-packages/aiogram/types/downloadable.py new file mode 100644 index 0000000..be80829 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/downloadable.py @@ -0,0 +1,5 @@ +from typing import Protocol + + +class Downloadable(Protocol): + file_id: str diff --git a/env/Lib/site-packages/aiogram/types/encrypted_credentials.py b/env/Lib/site-packages/aiogram/types/encrypted_credentials.py new file mode 100644 index 0000000..ca03e2a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/encrypted_credentials.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class EncryptedCredentials(TelegramObject): + """ + Describes data required for decrypting and authenticating :class:`aiogram.types.encrypted_passport_element.EncryptedPassportElement`. See the `Telegram Passport Documentation `_ for a complete description of the data decryption and authentication processes. + + Source: https://core.telegram.org/bots/api#encryptedcredentials + """ + + data: str + """Base64-encoded encrypted JSON-serialized data with unique user's payload, data hashes and secrets required for :class:`aiogram.types.encrypted_passport_element.EncryptedPassportElement` decryption and authentication""" + hash: str + """Base64-encoded data hash for data authentication""" + secret: str + """Base64-encoded secret, encrypted with the bot's public RSA key, required for data decryption""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, data: str, hash: str, secret: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(data=data, hash=hash, secret=secret, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/encrypted_passport_element.py b/env/Lib/site-packages/aiogram/types/encrypted_passport_element.py new file mode 100644 index 0000000..c1e8be1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/encrypted_passport_element.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .passport_file import PassportFile + + +class EncryptedPassportElement(TelegramObject): + """ + Describes documents or other Telegram Passport elements shared with the bot by the user. + + Source: https://core.telegram.org/bots/api#encryptedpassportelement + """ + + type: str + """Element type. One of 'personal_details', 'passport', 'driver_license', 'identity_card', 'internal_passport', 'address', 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration', 'phone_number', 'email'.""" + hash: str + """Base64-encoded element hash for using in :class:`aiogram.types.passport_element_error_unspecified.PassportElementErrorUnspecified`""" + data: Optional[str] = None + """*Optional*. Base64-encoded encrypted Telegram Passport element data provided by the user; available only for 'personal_details', 'passport', 'driver_license', 'identity_card', 'internal_passport' and 'address' types. Can be decrypted and verified using the accompanying :class:`aiogram.types.encrypted_credentials.EncryptedCredentials`.""" + phone_number: Optional[str] = None + """*Optional*. User's verified phone number; available only for 'phone_number' type""" + email: Optional[str] = None + """*Optional*. User's verified email address; available only for 'email' type""" + files: Optional[List[PassportFile]] = None + """*Optional*. Array of encrypted files with documents provided by the user; available only for 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration' and 'temporary_registration' types. Files can be decrypted and verified using the accompanying :class:`aiogram.types.encrypted_credentials.EncryptedCredentials`.""" + front_side: Optional[PassportFile] = None + """*Optional*. Encrypted file with the front side of the document, provided by the user; available only for 'passport', 'driver_license', 'identity_card' and 'internal_passport'. The file can be decrypted and verified using the accompanying :class:`aiogram.types.encrypted_credentials.EncryptedCredentials`.""" + reverse_side: Optional[PassportFile] = None + """*Optional*. Encrypted file with the reverse side of the document, provided by the user; available only for 'driver_license' and 'identity_card'. The file can be decrypted and verified using the accompanying :class:`aiogram.types.encrypted_credentials.EncryptedCredentials`.""" + selfie: Optional[PassportFile] = None + """*Optional*. Encrypted file with the selfie of the user holding a document, provided by the user; available if requested for 'passport', 'driver_license', 'identity_card' and 'internal_passport'. The file can be decrypted and verified using the accompanying :class:`aiogram.types.encrypted_credentials.EncryptedCredentials`.""" + translation: Optional[List[PassportFile]] = None + """*Optional*. Array of encrypted files with translated versions of documents provided by the user; available if requested for 'passport', 'driver_license', 'identity_card', 'internal_passport', 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration' and 'temporary_registration' types. Files can be decrypted and verified using the accompanying :class:`aiogram.types.encrypted_credentials.EncryptedCredentials`.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: str, + hash: str, + data: Optional[str] = None, + phone_number: Optional[str] = None, + email: Optional[str] = None, + files: Optional[List[PassportFile]] = None, + front_side: Optional[PassportFile] = None, + reverse_side: Optional[PassportFile] = None, + selfie: Optional[PassportFile] = None, + translation: Optional[List[PassportFile]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + hash=hash, + data=data, + phone_number=phone_number, + email=email, + files=files, + front_side=front_side, + reverse_side=reverse_side, + selfie=selfie, + translation=translation, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/error_event.py b/env/Lib/site-packages/aiogram/types/error_event.py new file mode 100644 index 0000000..e5eafc9 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/error_event.py @@ -0,0 +1,28 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from aiogram.types.base import TelegramObject + +if TYPE_CHECKING: + from .update import Update + + +class ErrorEvent(TelegramObject): + """ + Internal event, should be used to receive errors while processing Updates from Telegram + + Source: https://core.telegram.org/bots/api#error-event + """ + + update: Update + """Received update""" + exception: Exception + """Exception""" + + if TYPE_CHECKING: + + def __init__( + __pydantic_self__, *, update: Update, exception: Exception, **__pydantic_kwargs: Any + ) -> None: + super().__init__(update=update, exception=exception, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/external_reply_info.py b/env/Lib/site-packages/aiogram/types/external_reply_info.py new file mode 100644 index 0000000..0f13a85 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/external_reply_info.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from .base import TelegramObject + +if TYPE_CHECKING: + from .animation import Animation + from .audio import Audio + from .chat import Chat + from .contact import Contact + from .dice import Dice + from .document import Document + from .game import Game + from .giveaway import Giveaway + from .giveaway_winners import GiveawayWinners + from .invoice import Invoice + from .link_preview_options import LinkPreviewOptions + from .location import Location + from .message_origin_channel import MessageOriginChannel + from .message_origin_chat import MessageOriginChat + from .message_origin_hidden_user import MessageOriginHiddenUser + from .message_origin_user import MessageOriginUser + from .paid_media_info import PaidMediaInfo + from .photo_size import PhotoSize + from .poll import Poll + from .sticker import Sticker + from .story import Story + from .venue import Venue + from .video import Video + from .video_note import VideoNote + from .voice import Voice + + +class ExternalReplyInfo(TelegramObject): + """ + This object contains information about a message that is being replied to, which may come from another chat or forum topic. + + Source: https://core.telegram.org/bots/api#externalreplyinfo + """ + + origin: Union[ + MessageOriginUser, MessageOriginHiddenUser, MessageOriginChat, MessageOriginChannel + ] + """Origin of the message replied to by the given message""" + chat: Optional[Chat] = None + """*Optional*. Chat the original message belongs to. Available only if the chat is a supergroup or a channel.""" + message_id: Optional[int] = None + """*Optional*. Unique message identifier inside the original chat. Available only if the original chat is a supergroup or a channel.""" + link_preview_options: Optional[LinkPreviewOptions] = None + """*Optional*. Options used for link preview generation for the original message, if it is a text message""" + animation: Optional[Animation] = None + """*Optional*. Message is an animation, information about the animation""" + audio: Optional[Audio] = None + """*Optional*. Message is an audio file, information about the file""" + document: Optional[Document] = None + """*Optional*. Message is a general file, information about the file""" + paid_media: Optional[PaidMediaInfo] = None + """*Optional*. Message contains paid media; information about the paid media""" + photo: Optional[List[PhotoSize]] = None + """*Optional*. Message is a photo, available sizes of the photo""" + sticker: Optional[Sticker] = None + """*Optional*. Message is a sticker, information about the sticker""" + story: Optional[Story] = None + """*Optional*. Message is a forwarded story""" + video: Optional[Video] = None + """*Optional*. Message is a video, information about the video""" + video_note: Optional[VideoNote] = None + """*Optional*. Message is a `video note `_, information about the video message""" + voice: Optional[Voice] = None + """*Optional*. Message is a voice message, information about the file""" + has_media_spoiler: Optional[bool] = None + """*Optional*. :code:`True`, if the message media is covered by a spoiler animation""" + contact: Optional[Contact] = None + """*Optional*. Message is a shared contact, information about the contact""" + dice: Optional[Dice] = None + """*Optional*. Message is a dice with random value""" + game: Optional[Game] = None + """*Optional*. Message is a game, information about the game. `More about games » `_""" + giveaway: Optional[Giveaway] = None + """*Optional*. Message is a scheduled giveaway, information about the giveaway""" + giveaway_winners: Optional[GiveawayWinners] = None + """*Optional*. A giveaway with public winners was completed""" + invoice: Optional[Invoice] = None + """*Optional*. Message is an invoice for a `payment `_, information about the invoice. `More about payments » `_""" + location: Optional[Location] = None + """*Optional*. Message is a shared location, information about the location""" + poll: Optional[Poll] = None + """*Optional*. Message is a native poll, information about the poll""" + venue: Optional[Venue] = None + """*Optional*. Message is a venue, information about the venue""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + origin: Union[ + MessageOriginUser, MessageOriginHiddenUser, MessageOriginChat, MessageOriginChannel + ], + chat: Optional[Chat] = None, + message_id: Optional[int] = None, + link_preview_options: Optional[LinkPreviewOptions] = None, + animation: Optional[Animation] = None, + audio: Optional[Audio] = None, + document: Optional[Document] = None, + paid_media: Optional[PaidMediaInfo] = None, + photo: Optional[List[PhotoSize]] = None, + sticker: Optional[Sticker] = None, + story: Optional[Story] = None, + video: Optional[Video] = None, + video_note: Optional[VideoNote] = None, + voice: Optional[Voice] = None, + has_media_spoiler: Optional[bool] = None, + contact: Optional[Contact] = None, + dice: Optional[Dice] = None, + game: Optional[Game] = None, + giveaway: Optional[Giveaway] = None, + giveaway_winners: Optional[GiveawayWinners] = None, + invoice: Optional[Invoice] = None, + location: Optional[Location] = None, + poll: Optional[Poll] = None, + venue: Optional[Venue] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + origin=origin, + chat=chat, + message_id=message_id, + link_preview_options=link_preview_options, + animation=animation, + audio=audio, + document=document, + paid_media=paid_media, + photo=photo, + sticker=sticker, + story=story, + video=video, + video_note=video_note, + voice=voice, + has_media_spoiler=has_media_spoiler, + contact=contact, + dice=dice, + game=game, + giveaway=giveaway, + giveaway_winners=giveaway_winners, + invoice=invoice, + location=location, + poll=poll, + venue=venue, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/file.py b/env/Lib/site-packages/aiogram/types/file.py new file mode 100644 index 0000000..252c230 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/file.py @@ -0,0 +1,49 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class File(TelegramObject): + """ + This object represents a file ready to be downloaded. The file can be downloaded via the link :code:`https://api.telegram.org/file/bot/`. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling :class:`aiogram.methods.get_file.GetFile`. + + The maximum file size to download is 20 MB + + Source: https://core.telegram.org/bots/api#file + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + file_size: Optional[int] = None + """*Optional*. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.""" + file_path: Optional[str] = None + """*Optional*. File path. Use :code:`https://api.telegram.org/file/bot/` to get the file.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + file_size: Optional[int] = None, + file_path: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + file_size=file_size, + file_path=file_path, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/force_reply.py b/env/Lib/site-packages/aiogram/types/force_reply.py new file mode 100644 index 0000000..14b9c1c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/force_reply.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from .base import MutableTelegramObject + + +class ForceReply(MutableTelegramObject): + """ + Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot's message and tapped 'Reply'). This can be extremely useful if you want to create user-friendly step-by-step interfaces without having to sacrifice `privacy mode `_. Not supported in channels and for messages sent on behalf of a Telegram Business account. + + **Example:** A `poll bot `_ for groups runs in privacy mode (only receives commands, replies to its messages and mentions). There could be two ways to create a new poll: + + - Explain the user how to send a command with parameters (e.g. /newpoll question answer1 answer2). May be appealing for hardcore users but lacks modern day polish. + - Guide the user through a step-by-step process. 'Please send me your question', 'Cool, now let's add the first answer option', 'Great. Keep adding answer options, then send /done when you're ready'. + + The last option is definitely more attractive. And if you use :class:`aiogram.types.force_reply.ForceReply` in your bot's questions, it will receive the user's answers even if it only receives replies, commands and mentions - without any extra work for the user. + + Source: https://core.telegram.org/bots/api#forcereply + """ + + force_reply: Literal[True] = True + """Shows reply interface to the user, as if they manually selected the bot's message and tapped 'Reply'""" + input_field_placeholder: Optional[str] = None + """*Optional*. The placeholder to be shown in the input field when the reply is active; 1-64 characters""" + selective: Optional[bool] = None + """*Optional*. Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the *text* of the :class:`aiogram.types.message.Message` object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + force_reply: Literal[True] = True, + input_field_placeholder: Optional[str] = None, + selective: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + force_reply=force_reply, + input_field_placeholder=input_field_placeholder, + selective=selective, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/forum_topic.py b/env/Lib/site-packages/aiogram/types/forum_topic.py new file mode 100644 index 0000000..a6464bc --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/forum_topic.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class ForumTopic(TelegramObject): + """ + This object represents a forum topic. + + Source: https://core.telegram.org/bots/api#forumtopic + """ + + message_thread_id: int + """Unique identifier of the forum topic""" + name: str + """Name of the topic""" + icon_color: int + """Color of the topic icon in RGB format""" + icon_custom_emoji_id: Optional[str] = None + """*Optional*. Unique identifier of the custom emoji shown as the topic icon""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + message_thread_id: int, + name: str, + icon_color: int, + icon_custom_emoji_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + message_thread_id=message_thread_id, + name=name, + icon_color=icon_color, + icon_custom_emoji_id=icon_custom_emoji_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/forum_topic_closed.py b/env/Lib/site-packages/aiogram/types/forum_topic_closed.py new file mode 100644 index 0000000..390b331 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/forum_topic_closed.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from .base import TelegramObject + + +class ForumTopicClosed(TelegramObject): + """ + This object represents a service message about a forum topic closed in the chat. Currently holds no information. + + Source: https://core.telegram.org/bots/api#forumtopicclosed + """ diff --git a/env/Lib/site-packages/aiogram/types/forum_topic_created.py b/env/Lib/site-packages/aiogram/types/forum_topic_created.py new file mode 100644 index 0000000..513df95 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/forum_topic_created.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class ForumTopicCreated(TelegramObject): + """ + This object represents a service message about a new forum topic created in the chat. + + Source: https://core.telegram.org/bots/api#forumtopiccreated + """ + + name: str + """Name of the topic""" + icon_color: int + """Color of the topic icon in RGB format""" + icon_custom_emoji_id: Optional[str] = None + """*Optional*. Unique identifier of the custom emoji shown as the topic icon""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + name: str, + icon_color: int, + icon_custom_emoji_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + name=name, + icon_color=icon_color, + icon_custom_emoji_id=icon_custom_emoji_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/forum_topic_edited.py b/env/Lib/site-packages/aiogram/types/forum_topic_edited.py new file mode 100644 index 0000000..b7b6196 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/forum_topic_edited.py @@ -0,0 +1,35 @@ +from typing import TYPE_CHECKING, Any, Optional + +from aiogram.types import TelegramObject + + +class ForumTopicEdited(TelegramObject): + """ + This object represents a service message about an edited forum topic. + + Source: https://core.telegram.org/bots/api#forumtopicedited + """ + + name: Optional[str] = None + """*Optional*. New name of the topic, if it was edited""" + icon_custom_emoji_id: Optional[str] = None + """*Optional*. New identifier of the custom emoji shown as the topic icon, if it was edited; an empty string if the icon was removed""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + name: Optional[str] = None, + icon_custom_emoji_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + name=name, icon_custom_emoji_id=icon_custom_emoji_id, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/forum_topic_reopened.py b/env/Lib/site-packages/aiogram/types/forum_topic_reopened.py new file mode 100644 index 0000000..e02fbaf --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/forum_topic_reopened.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from .base import TelegramObject + + +class ForumTopicReopened(TelegramObject): + """ + This object represents a service message about a forum topic reopened in the chat. Currently holds no information. + + Source: https://core.telegram.org/bots/api#forumtopicreopened + """ diff --git a/env/Lib/site-packages/aiogram/types/game.py b/env/Lib/site-packages/aiogram/types/game.py new file mode 100644 index 0000000..294f26b --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/game.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .animation import Animation + from .message_entity import MessageEntity + from .photo_size import PhotoSize + + +class Game(TelegramObject): + """ + This object represents a game. Use BotFather to create and edit games, their short names will act as unique identifiers. + + Source: https://core.telegram.org/bots/api#game + """ + + title: str + """Title of the game""" + description: str + """Description of the game""" + photo: List[PhotoSize] + """Photo that will be displayed in the game message in chats.""" + text: Optional[str] = None + """*Optional*. Brief description of the game or high scores included in the game message. Can be automatically edited to include current high scores for the game when the bot calls :class:`aiogram.methods.set_game_score.SetGameScore`, or manually edited using :class:`aiogram.methods.edit_message_text.EditMessageText`. 0-4096 characters.""" + text_entities: Optional[List[MessageEntity]] = None + """*Optional*. Special entities that appear in *text*, such as usernames, URLs, bot commands, etc.""" + animation: Optional[Animation] = None + """*Optional*. Animation that will be displayed in the game message in chats. Upload via `BotFather `_""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + title: str, + description: str, + photo: List[PhotoSize], + text: Optional[str] = None, + text_entities: Optional[List[MessageEntity]] = None, + animation: Optional[Animation] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + title=title, + description=description, + photo=photo, + text=text, + text_entities=text_entities, + animation=animation, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/game_high_score.py b/env/Lib/site-packages/aiogram/types/game_high_score.py new file mode 100644 index 0000000..5364be6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/game_high_score.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + +if TYPE_CHECKING: + from .user import User + + +class GameHighScore(TelegramObject): + """ + This object represents one row of the high scores table for a game. + And that's about all we've got for now. + + If you've got any questions, please check out our `https://core.telegram.org/bots/faq `_ **Bot FAQ »** + + Source: https://core.telegram.org/bots/api#gamehighscore + """ + + position: int + """Position in high score table for the game""" + user: User + """User""" + score: int + """Score""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, position: int, user: User, score: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(position=position, user=user, score=score, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/general_forum_topic_hidden.py b/env/Lib/site-packages/aiogram/types/general_forum_topic_hidden.py new file mode 100644 index 0000000..136a275 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/general_forum_topic_hidden.py @@ -0,0 +1,9 @@ +from aiogram.types import TelegramObject + + +class GeneralForumTopicHidden(TelegramObject): + """ + This object represents a service message about General forum topic hidden in the chat. Currently holds no information. + + Source: https://core.telegram.org/bots/api#generalforumtopichidden + """ diff --git a/env/Lib/site-packages/aiogram/types/general_forum_topic_unhidden.py b/env/Lib/site-packages/aiogram/types/general_forum_topic_unhidden.py new file mode 100644 index 0000000..9637a02 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/general_forum_topic_unhidden.py @@ -0,0 +1,9 @@ +from aiogram.types import TelegramObject + + +class GeneralForumTopicUnhidden(TelegramObject): + """ + This object represents a service message about General forum topic unhidden in the chat. Currently holds no information. + + Source: https://core.telegram.org/bots/api#generalforumtopicunhidden + """ diff --git a/env/Lib/site-packages/aiogram/types/giveaway.py b/env/Lib/site-packages/aiogram/types/giveaway.py new file mode 100644 index 0000000..1fa4f50 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/giveaway.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat import Chat + from .custom import DateTime + + +class Giveaway(TelegramObject): + """ + This object represents a message about a scheduled giveaway. + + Source: https://core.telegram.org/bots/api#giveaway + """ + + chats: List[Chat] + """The list of chats which the user must join to participate in the giveaway""" + winners_selection_date: DateTime + """Point in time (Unix timestamp) when winners of the giveaway will be selected""" + winner_count: int + """The number of users which are supposed to be selected as winners of the giveaway""" + only_new_members: Optional[bool] = None + """*Optional*. :code:`True`, if only users who join the chats after the giveaway started should be eligible to win""" + has_public_winners: Optional[bool] = None + """*Optional*. :code:`True`, if the list of giveaway winners will be visible to everyone""" + prize_description: Optional[str] = None + """*Optional*. Description of additional giveaway prize""" + country_codes: Optional[List[str]] = None + """*Optional*. A list of two-letter `ISO 3166-1 alpha-2 `_ country codes indicating the countries from which eligible users for the giveaway must come. If empty, then all users can participate in the giveaway. Users with a phone number that was bought on Fragment can always participate in giveaways.""" + premium_subscription_month_count: Optional[int] = None + """*Optional*. The number of months the Telegram Premium subscription won from the giveaway will be active for""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chats: List[Chat], + winners_selection_date: DateTime, + winner_count: int, + only_new_members: Optional[bool] = None, + has_public_winners: Optional[bool] = None, + prize_description: Optional[str] = None, + country_codes: Optional[List[str]] = None, + premium_subscription_month_count: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chats=chats, + winners_selection_date=winners_selection_date, + winner_count=winner_count, + only_new_members=only_new_members, + has_public_winners=has_public_winners, + prize_description=prize_description, + country_codes=country_codes, + premium_subscription_month_count=premium_subscription_month_count, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/giveaway_completed.py b/env/Lib/site-packages/aiogram/types/giveaway_completed.py new file mode 100644 index 0000000..71d525a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/giveaway_completed.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .message import Message + + +class GiveawayCompleted(TelegramObject): + """ + This object represents a service message about the completion of a giveaway without public winners. + + Source: https://core.telegram.org/bots/api#giveawaycompleted + """ + + winner_count: int + """Number of winners in the giveaway""" + unclaimed_prize_count: Optional[int] = None + """*Optional*. Number of undistributed prizes""" + giveaway_message: Optional[Message] = None + """*Optional*. Message with the giveaway that was completed, if it wasn't deleted""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + winner_count: int, + unclaimed_prize_count: Optional[int] = None, + giveaway_message: Optional[Message] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + winner_count=winner_count, + unclaimed_prize_count=unclaimed_prize_count, + giveaway_message=giveaway_message, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/giveaway_created.py b/env/Lib/site-packages/aiogram/types/giveaway_created.py new file mode 100644 index 0000000..cd66d75 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/giveaway_created.py @@ -0,0 +1,9 @@ +from .base import TelegramObject + + +class GiveawayCreated(TelegramObject): + """ + This object represents a service message about the creation of a scheduled giveaway. Currently holds no information. + + Source: https://core.telegram.org/bots/api#giveawaycreated + """ diff --git a/env/Lib/site-packages/aiogram/types/giveaway_winners.py b/env/Lib/site-packages/aiogram/types/giveaway_winners.py new file mode 100644 index 0000000..8a501f8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/giveaway_winners.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat import Chat + from .custom import DateTime + from .user import User + + +class GiveawayWinners(TelegramObject): + """ + This object represents a message about the completion of a giveaway with public winners. + + Source: https://core.telegram.org/bots/api#giveawaywinners + """ + + chat: Chat + """The chat that created the giveaway""" + giveaway_message_id: int + """Identifier of the message with the giveaway in the chat""" + winners_selection_date: DateTime + """Point in time (Unix timestamp) when winners of the giveaway were selected""" + winner_count: int + """Total number of winners in the giveaway""" + winners: List[User] + """List of up to 100 winners of the giveaway""" + additional_chat_count: Optional[int] = None + """*Optional*. The number of other chats the user had to join in order to be eligible for the giveaway""" + premium_subscription_month_count: Optional[int] = None + """*Optional*. The number of months the Telegram Premium subscription won from the giveaway will be active for""" + unclaimed_prize_count: Optional[int] = None + """*Optional*. Number of undistributed prizes""" + only_new_members: Optional[bool] = None + """*Optional*. :code:`True`, if only users who had joined the chats after the giveaway started were eligible to win""" + was_refunded: Optional[bool] = None + """*Optional*. :code:`True`, if the giveaway was canceled because the payment for it was refunded""" + prize_description: Optional[str] = None + """*Optional*. Description of additional giveaway prize""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat: Chat, + giveaway_message_id: int, + winners_selection_date: DateTime, + winner_count: int, + winners: List[User], + additional_chat_count: Optional[int] = None, + premium_subscription_month_count: Optional[int] = None, + unclaimed_prize_count: Optional[int] = None, + only_new_members: Optional[bool] = None, + was_refunded: Optional[bool] = None, + prize_description: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat=chat, + giveaway_message_id=giveaway_message_id, + winners_selection_date=winners_selection_date, + winner_count=winner_count, + winners=winners, + additional_chat_count=additional_chat_count, + premium_subscription_month_count=premium_subscription_month_count, + unclaimed_prize_count=unclaimed_prize_count, + only_new_members=only_new_members, + was_refunded=was_refunded, + prize_description=prize_description, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inaccessible_message.py b/env/Lib/site-packages/aiogram/types/inaccessible_message.py new file mode 100644 index 0000000..6ed38fe --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inaccessible_message.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from .maybe_inaccessible_message import MaybeInaccessibleMessage + +if TYPE_CHECKING: + from .chat import Chat + + +class InaccessibleMessage(MaybeInaccessibleMessage): + """ + This object describes a message that was deleted or is otherwise inaccessible to the bot. + + Source: https://core.telegram.org/bots/api#inaccessiblemessage + """ + + chat: Chat + """Chat the message belonged to""" + message_id: int + """Unique message identifier inside the chat""" + date: Literal[0] = 0 + """Always 0. The field can be used to differentiate regular and inaccessible messages.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat: Chat, + message_id: int, + date: Literal[0] = 0, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat=chat, message_id=message_id, date=date, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/inline_keyboard_button.py b/env/Lib/site-packages/aiogram/types/inline_keyboard_button.py new file mode 100644 index 0000000..fa801f2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_keyboard_button.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import MutableTelegramObject + +if TYPE_CHECKING: + from .callback_game import CallbackGame + from .login_url import LoginUrl + from .switch_inline_query_chosen_chat import SwitchInlineQueryChosenChat + from .web_app_info import WebAppInfo + + +class InlineKeyboardButton(MutableTelegramObject): + """ + This object represents one button of an inline keyboard. Exactly one of the optional fields must be used to specify type of the button. + + Source: https://core.telegram.org/bots/api#inlinekeyboardbutton + """ + + text: str + """Label text on the button""" + url: Optional[str] = None + """*Optional*. HTTP or tg:// URL to be opened when the button is pressed. Links :code:`tg://user?id=` can be used to mention a user by their identifier without using a username, if this is allowed by their privacy settings.""" + callback_data: Optional[str] = None + """*Optional*. Data to be sent in a `callback query `_ to the bot when the button is pressed, 1-64 bytes""" + web_app: Optional[WebAppInfo] = None + """*Optional*. Description of the `Web App `_ that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method :class:`aiogram.methods.answer_web_app_query.AnswerWebAppQuery`. Available only in private chats between a user and the bot. Not supported for messages sent on behalf of a Telegram Business account.""" + login_url: Optional[LoginUrl] = None + """*Optional*. An HTTPS URL used to automatically authorize the user. Can be used as a replacement for the `Telegram Login Widget `_.""" + switch_inline_query: Optional[str] = None + """*Optional*. If set, pressing the button will prompt the user to select one of their chats, open that chat and insert the bot's username and the specified inline query in the input field. May be empty, in which case just the bot's username will be inserted. Not supported for messages sent on behalf of a Telegram Business account.""" + switch_inline_query_current_chat: Optional[str] = None + """*Optional*. If set, pressing the button will insert the bot's username and the specified inline query in the current chat's input field. May be empty, in which case only the bot's username will be inserted.""" + switch_inline_query_chosen_chat: Optional[SwitchInlineQueryChosenChat] = None + """*Optional*. If set, pressing the button will prompt the user to select one of their chats of the specified type, open that chat and insert the bot's username and the specified inline query in the input field. Not supported for messages sent on behalf of a Telegram Business account.""" + callback_game: Optional[CallbackGame] = None + """*Optional*. Description of the game that will be launched when the user presses the button.""" + pay: Optional[bool] = None + """*Optional*. Specify :code:`True`, to send a `Pay button `_. Substrings '⭐' and 'XTR' in the buttons's text will be replaced with a Telegram Star icon.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + text: str, + url: Optional[str] = None, + callback_data: Optional[str] = None, + web_app: Optional[WebAppInfo] = None, + login_url: Optional[LoginUrl] = None, + switch_inline_query: Optional[str] = None, + switch_inline_query_current_chat: Optional[str] = None, + switch_inline_query_chosen_chat: Optional[SwitchInlineQueryChosenChat] = None, + callback_game: Optional[CallbackGame] = None, + pay: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + text=text, + url=url, + callback_data=callback_data, + web_app=web_app, + login_url=login_url, + switch_inline_query=switch_inline_query, + switch_inline_query_current_chat=switch_inline_query_current_chat, + switch_inline_query_chosen_chat=switch_inline_query_chosen_chat, + callback_game=callback_game, + pay=pay, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_keyboard_markup.py b/env/Lib/site-packages/aiogram/types/inline_keyboard_markup.py new file mode 100644 index 0000000..e5b8967 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_keyboard_markup.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import MutableTelegramObject + +if TYPE_CHECKING: + from .inline_keyboard_button import InlineKeyboardButton + + +class InlineKeyboardMarkup(MutableTelegramObject): + """ + This object represents an `inline keyboard `_ that appears right next to the message it belongs to. + + Source: https://core.telegram.org/bots/api#inlinekeyboardmarkup + """ + + inline_keyboard: List[List[InlineKeyboardButton]] + """Array of button rows, each represented by an Array of :class:`aiogram.types.inline_keyboard_button.InlineKeyboardButton` objects""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + inline_keyboard: List[List[InlineKeyboardButton]], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(inline_keyboard=inline_keyboard, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/inline_query.py b/env/Lib/site-packages/aiogram/types/inline_query.py new file mode 100644 index 0000000..a0cad31 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from .base import TelegramObject + +if TYPE_CHECKING: + from ..methods import AnswerInlineQuery + from .inline_query_result_article import InlineQueryResultArticle + from .inline_query_result_audio import InlineQueryResultAudio + from .inline_query_result_cached_audio import InlineQueryResultCachedAudio + from .inline_query_result_cached_document import InlineQueryResultCachedDocument + from .inline_query_result_cached_gif import InlineQueryResultCachedGif + from .inline_query_result_cached_mpeg4_gif import InlineQueryResultCachedMpeg4Gif + from .inline_query_result_cached_photo import InlineQueryResultCachedPhoto + from .inline_query_result_cached_sticker import InlineQueryResultCachedSticker + from .inline_query_result_cached_video import InlineQueryResultCachedVideo + from .inline_query_result_cached_voice import InlineQueryResultCachedVoice + from .inline_query_result_contact import InlineQueryResultContact + from .inline_query_result_document import InlineQueryResultDocument + from .inline_query_result_game import InlineQueryResultGame + from .inline_query_result_gif import InlineQueryResultGif + from .inline_query_result_location import InlineQueryResultLocation + from .inline_query_result_mpeg4_gif import InlineQueryResultMpeg4Gif + from .inline_query_result_photo import InlineQueryResultPhoto + from .inline_query_result_venue import InlineQueryResultVenue + from .inline_query_result_video import InlineQueryResultVideo + from .inline_query_result_voice import InlineQueryResultVoice + from .inline_query_results_button import InlineQueryResultsButton + from .location import Location + from .user import User + + +class InlineQuery(TelegramObject): + """ + This object represents an incoming inline query. When the user sends an empty query, your bot could return some default or trending results. + + Source: https://core.telegram.org/bots/api#inlinequery + """ + + id: str + """Unique identifier for this query""" + from_user: User = Field(..., alias="from") + """Sender""" + query: str + """Text of the query (up to 256 characters)""" + offset: str + """Offset of the results to be returned, can be controlled by the bot""" + chat_type: Optional[str] = None + """*Optional*. Type of the chat from which the inline query was sent. Can be either 'sender' for a private chat with the inline query sender, 'private', 'group', 'supergroup', or 'channel'. The chat type should be always known for requests sent from official clients and most third-party clients, unless the request was sent from a secret chat""" + location: Optional[Location] = None + """*Optional*. Sender location, only for bots that request user location""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: str, + from_user: User, + query: str, + offset: str, + chat_type: Optional[str] = None, + location: Optional[Location] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + from_user=from_user, + query=query, + offset=offset, + chat_type=chat_type, + location=location, + **__pydantic_kwargs, + ) + + def answer( + self, + results: List[ + Union[ + InlineQueryResultCachedAudio, + InlineQueryResultCachedDocument, + InlineQueryResultCachedGif, + InlineQueryResultCachedMpeg4Gif, + InlineQueryResultCachedPhoto, + InlineQueryResultCachedSticker, + InlineQueryResultCachedVideo, + InlineQueryResultCachedVoice, + InlineQueryResultArticle, + InlineQueryResultAudio, + InlineQueryResultContact, + InlineQueryResultGame, + InlineQueryResultDocument, + InlineQueryResultGif, + InlineQueryResultLocation, + InlineQueryResultMpeg4Gif, + InlineQueryResultPhoto, + InlineQueryResultVenue, + InlineQueryResultVideo, + InlineQueryResultVoice, + ] + ], + cache_time: Optional[int] = None, + is_personal: Optional[bool] = None, + next_offset: Optional[str] = None, + button: Optional[InlineQueryResultsButton] = None, + switch_pm_parameter: Optional[str] = None, + switch_pm_text: Optional[str] = None, + **kwargs: Any, + ) -> AnswerInlineQuery: + """ + Shortcut for method :class:`aiogram.methods.answer_inline_query.AnswerInlineQuery` + will automatically fill method attributes: + + - :code:`inline_query_id` + + Use this method to send answers to an inline query. On success, :code:`True` is returned. + + No more than **50** results per query are allowed. + + Source: https://core.telegram.org/bots/api#answerinlinequery + + :param results: A JSON-serialized array of results for the inline query + :param cache_time: The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. + :param is_personal: Pass :code:`True` if results may be cached on the server side only for the user that sent the query. By default, results may be returned to any user who sends the same query. + :param next_offset: Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don't support pagination. Offset length can't exceed 64 bytes. + :param button: A JSON-serialized object describing a button to be shown above inline query results + :param switch_pm_parameter: `Deep-linking `_ parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only :code:`A-Z`, :code:`a-z`, :code:`0-9`, :code:`_` and :code:`-` are allowed. + :param switch_pm_text: If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter *switch_pm_parameter* + :return: instance of method :class:`aiogram.methods.answer_inline_query.AnswerInlineQuery` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import AnswerInlineQuery + + return AnswerInlineQuery( + inline_query_id=self.id, + results=results, + cache_time=cache_time, + is_personal=is_personal, + next_offset=next_offset, + button=button, + switch_pm_parameter=switch_pm_parameter, + switch_pm_text=switch_pm_text, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result.py b/env/Lib/site-packages/aiogram/types/inline_query_result.py new file mode 100644 index 0000000..b615aa2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from .base import MutableTelegramObject + + +class InlineQueryResult(MutableTelegramObject): + """ + This object represents one result of an inline query. Telegram clients currently support results of the following 20 types: + + - :class:`aiogram.types.inline_query_result_cached_audio.InlineQueryResultCachedAudio` + - :class:`aiogram.types.inline_query_result_cached_document.InlineQueryResultCachedDocument` + - :class:`aiogram.types.inline_query_result_cached_gif.InlineQueryResultCachedGif` + - :class:`aiogram.types.inline_query_result_cached_mpeg4_gif.InlineQueryResultCachedMpeg4Gif` + - :class:`aiogram.types.inline_query_result_cached_photo.InlineQueryResultCachedPhoto` + - :class:`aiogram.types.inline_query_result_cached_sticker.InlineQueryResultCachedSticker` + - :class:`aiogram.types.inline_query_result_cached_video.InlineQueryResultCachedVideo` + - :class:`aiogram.types.inline_query_result_cached_voice.InlineQueryResultCachedVoice` + - :class:`aiogram.types.inline_query_result_article.InlineQueryResultArticle` + - :class:`aiogram.types.inline_query_result_audio.InlineQueryResultAudio` + - :class:`aiogram.types.inline_query_result_contact.InlineQueryResultContact` + - :class:`aiogram.types.inline_query_result_game.InlineQueryResultGame` + - :class:`aiogram.types.inline_query_result_document.InlineQueryResultDocument` + - :class:`aiogram.types.inline_query_result_gif.InlineQueryResultGif` + - :class:`aiogram.types.inline_query_result_location.InlineQueryResultLocation` + - :class:`aiogram.types.inline_query_result_mpeg4_gif.InlineQueryResultMpeg4Gif` + - :class:`aiogram.types.inline_query_result_photo.InlineQueryResultPhoto` + - :class:`aiogram.types.inline_query_result_venue.InlineQueryResultVenue` + - :class:`aiogram.types.inline_query_result_video.InlineQueryResultVideo` + - :class:`aiogram.types.inline_query_result_voice.InlineQueryResultVoice` + + **Note:** All URLs passed in inline query results will be available to end users and therefore must be assumed to be **public**. + + Source: https://core.telegram.org/bots/api#inlinequeryresult + """ diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_article.py b/env/Lib/site-packages/aiogram/types/inline_query_result_article.py new file mode 100644 index 0000000..c998738 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_article.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + + +class InlineQueryResultArticle(InlineQueryResult): + """ + Represents a link to an article or web page. + + Source: https://core.telegram.org/bots/api#inlinequeryresultarticle + """ + + type: Literal[InlineQueryResultType.ARTICLE] = InlineQueryResultType.ARTICLE + """Type of the result, must be *article*""" + id: str + """Unique identifier for this result, 1-64 Bytes""" + title: str + """Title of the result""" + input_message_content: Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + """Content of the message to be sent""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + url: Optional[str] = None + """*Optional*. URL of the result""" + hide_url: Optional[bool] = None + """*Optional*. Pass :code:`True` if you don't want the URL to be shown in the message""" + description: Optional[str] = None + """*Optional*. Short description of the result""" + thumbnail_url: Optional[str] = None + """*Optional*. Url of the thumbnail for the result""" + thumbnail_width: Optional[int] = None + """*Optional*. Thumbnail width""" + thumbnail_height: Optional[int] = None + """*Optional*. Thumbnail height""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.ARTICLE] = InlineQueryResultType.ARTICLE, + id: str, + title: str, + input_message_content: Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ], + reply_markup: Optional[InlineKeyboardMarkup] = None, + url: Optional[str] = None, + hide_url: Optional[bool] = None, + description: Optional[str] = None, + thumbnail_url: Optional[str] = None, + thumbnail_width: Optional[int] = None, + thumbnail_height: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + title=title, + input_message_content=input_message_content, + reply_markup=reply_markup, + url=url, + hide_url=hide_url, + description=description, + thumbnail_url=thumbnail_url, + thumbnail_width=thumbnail_width, + thumbnail_height=thumbnail_height, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_audio.py b/env/Lib/site-packages/aiogram/types/inline_query_result_audio.py new file mode 100644 index 0000000..56ef5f5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_audio.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultAudio(InlineQueryResult): + """ + Represents a link to an MP3 audio file. By default, this audio file will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the audio. + + Source: https://core.telegram.org/bots/api#inlinequeryresultaudio + """ + + type: Literal[InlineQueryResultType.AUDIO] = InlineQueryResultType.AUDIO + """Type of the result, must be *audio*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + audio_url: str + """A valid URL for the audio file""" + title: str + """Title""" + caption: Optional[str] = None + """*Optional*. Caption, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the audio caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + performer: Optional[str] = None + """*Optional*. Performer""" + audio_duration: Optional[int] = None + """*Optional*. Audio duration in seconds""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the audio""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.AUDIO] = InlineQueryResultType.AUDIO, + id: str, + audio_url: str, + title: str, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + performer: Optional[str] = None, + audio_duration: Optional[int] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + audio_url=audio_url, + title=title, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + performer=performer, + audio_duration=audio_duration, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_cached_audio.py b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_audio.py new file mode 100644 index 0000000..27d923f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_audio.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultCachedAudio(InlineQueryResult): + """ + Represents a link to an MP3 audio file stored on the Telegram servers. By default, this audio file will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the audio. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedaudio + """ + + type: Literal[InlineQueryResultType.AUDIO] = InlineQueryResultType.AUDIO + """Type of the result, must be *audio*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + audio_file_id: str + """A valid file identifier for the audio file""" + caption: Optional[str] = None + """*Optional*. Caption, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the audio caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the audio""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.AUDIO] = InlineQueryResultType.AUDIO, + id: str, + audio_file_id: str, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + audio_file_id=audio_file_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_cached_document.py b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_document.py new file mode 100644 index 0000000..8e0355e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_document.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultCachedDocument(InlineQueryResult): + """ + Represents a link to a file stored on the Telegram servers. By default, this file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the file. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcacheddocument + """ + + type: Literal[InlineQueryResultType.DOCUMENT] = InlineQueryResultType.DOCUMENT + """Type of the result, must be *document*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + title: str + """Title for the result""" + document_file_id: str + """A valid file identifier for the file""" + description: Optional[str] = None + """*Optional*. Short description of the result""" + caption: Optional[str] = None + """*Optional*. Caption of the document to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the document caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the file""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.DOCUMENT] = InlineQueryResultType.DOCUMENT, + id: str, + title: str, + document_file_id: str, + description: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + title=title, + document_file_id=document_file_id, + description=description, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_cached_gif.py b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_gif.py new file mode 100644 index 0000000..277454c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_gif.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultCachedGif(InlineQueryResult): + """ + Represents a link to an animated GIF file stored on the Telegram servers. By default, this animated GIF file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with specified content instead of the animation. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedgif + """ + + type: Literal[InlineQueryResultType.GIF] = InlineQueryResultType.GIF + """Type of the result, must be *gif*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + gif_file_id: str + """A valid file identifier for the GIF file""" + title: Optional[str] = None + """*Optional*. Title for the result""" + caption: Optional[str] = None + """*Optional*. Caption of the GIF file to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the GIF animation""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.GIF] = InlineQueryResultType.GIF, + id: str, + gif_file_id: str, + title: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + gif_file_id=gif_file_id, + title=title, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_cached_mpeg4_gif.py b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_mpeg4_gif.py new file mode 100644 index 0000000..ec04386 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_mpeg4_gif.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultCachedMpeg4Gif(InlineQueryResult): + """ + Represents a link to a video animation (H.264/MPEG-4 AVC video without sound) stored on the Telegram servers. By default, this animated MPEG-4 file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the animation. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedmpeg4gif + """ + + type: Literal[InlineQueryResultType.MPEG4_GIF] = InlineQueryResultType.MPEG4_GIF + """Type of the result, must be *mpeg4_gif*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + mpeg4_file_id: str + """A valid file identifier for the MPEG4 file""" + title: Optional[str] = None + """*Optional*. Title for the result""" + caption: Optional[str] = None + """*Optional*. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the video animation""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.MPEG4_GIF] = InlineQueryResultType.MPEG4_GIF, + id: str, + mpeg4_file_id: str, + title: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + mpeg4_file_id=mpeg4_file_id, + title=title, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_cached_photo.py b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_photo.py new file mode 100644 index 0000000..f40b203 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_photo.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultCachedPhoto(InlineQueryResult): + """ + Represents a link to a photo stored on the Telegram servers. By default, this photo will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the photo. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedphoto + """ + + type: Literal[InlineQueryResultType.PHOTO] = InlineQueryResultType.PHOTO + """Type of the result, must be *photo*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + photo_file_id: str + """A valid file identifier of the photo""" + title: Optional[str] = None + """*Optional*. Title for the result""" + description: Optional[str] = None + """*Optional*. Short description of the result""" + caption: Optional[str] = None + """*Optional*. Caption of the photo to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the photo caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the photo""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.PHOTO] = InlineQueryResultType.PHOTO, + id: str, + photo_file_id: str, + title: Optional[str] = None, + description: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + photo_file_id=photo_file_id, + title=title, + description=description, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_cached_sticker.py b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_sticker.py new file mode 100644 index 0000000..4300023 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_sticker.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + + +class InlineQueryResultCachedSticker(InlineQueryResult): + """ + Represents a link to a sticker stored on the Telegram servers. By default, this sticker will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the sticker. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedsticker + """ + + type: Literal[InlineQueryResultType.STICKER] = InlineQueryResultType.STICKER + """Type of the result, must be *sticker*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + sticker_file_id: str + """A valid file identifier of the sticker""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the sticker""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.STICKER] = InlineQueryResultType.STICKER, + id: str, + sticker_file_id: str, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + sticker_file_id=sticker_file_id, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_cached_video.py b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_video.py new file mode 100644 index 0000000..4095ab9 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_video.py @@ -0,0 +1,104 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultCachedVideo(InlineQueryResult): + """ + Represents a link to a video file stored on the Telegram servers. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the video. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedvideo + """ + + type: Literal[InlineQueryResultType.VIDEO] = InlineQueryResultType.VIDEO + """Type of the result, must be *video*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + video_file_id: str + """A valid file identifier for the video file""" + title: str + """Title for the result""" + description: Optional[str] = None + """*Optional*. Short description of the result""" + caption: Optional[str] = None + """*Optional*. Caption of the video to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the video caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the video""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.VIDEO] = InlineQueryResultType.VIDEO, + id: str, + video_file_id: str, + title: str, + description: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + video_file_id=video_file_id, + title=title, + description=description, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_cached_voice.py b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_voice.py new file mode 100644 index 0000000..4cff896 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_cached_voice.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultCachedVoice(InlineQueryResult): + """ + Represents a link to a voice message stored on the Telegram servers. By default, this voice message will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the voice message. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcachedvoice + """ + + type: Literal[InlineQueryResultType.VOICE] = InlineQueryResultType.VOICE + """Type of the result, must be *voice*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + voice_file_id: str + """A valid file identifier for the voice message""" + title: str + """Voice message title""" + caption: Optional[str] = None + """*Optional*. Caption, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the voice message caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the voice message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.VOICE] = InlineQueryResultType.VOICE, + id: str, + voice_file_id: str, + title: str, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + voice_file_id=voice_file_id, + title=title, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_contact.py b/env/Lib/site-packages/aiogram/types/inline_query_result_contact.py new file mode 100644 index 0000000..cc2900c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_contact.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + + +class InlineQueryResultContact(InlineQueryResult): + """ + Represents a contact with a phone number. By default, this contact will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the contact. + + Source: https://core.telegram.org/bots/api#inlinequeryresultcontact + """ + + type: Literal[InlineQueryResultType.CONTACT] = InlineQueryResultType.CONTACT + """Type of the result, must be *contact*""" + id: str + """Unique identifier for this result, 1-64 Bytes""" + phone_number: str + """Contact's phone number""" + first_name: str + """Contact's first name""" + last_name: Optional[str] = None + """*Optional*. Contact's last name""" + vcard: Optional[str] = None + """*Optional*. Additional data about the contact in the form of a `vCard `_, 0-2048 bytes""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the contact""" + thumbnail_url: Optional[str] = None + """*Optional*. Url of the thumbnail for the result""" + thumbnail_width: Optional[int] = None + """*Optional*. Thumbnail width""" + thumbnail_height: Optional[int] = None + """*Optional*. Thumbnail height""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.CONTACT] = InlineQueryResultType.CONTACT, + id: str, + phone_number: str, + first_name: str, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + thumbnail_url: Optional[str] = None, + thumbnail_width: Optional[int] = None, + thumbnail_height: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + phone_number=phone_number, + first_name=first_name, + last_name=last_name, + vcard=vcard, + reply_markup=reply_markup, + input_message_content=input_message_content, + thumbnail_url=thumbnail_url, + thumbnail_width=thumbnail_width, + thumbnail_height=thumbnail_height, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_document.py b/env/Lib/site-packages/aiogram/types/inline_query_result_document.py new file mode 100644 index 0000000..86ae993 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_document.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultDocument(InlineQueryResult): + """ + Represents a link to a file. By default, this file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the file. Currently, only **.PDF** and **.ZIP** files can be sent using this method. + + Source: https://core.telegram.org/bots/api#inlinequeryresultdocument + """ + + type: Literal[InlineQueryResultType.DOCUMENT] = InlineQueryResultType.DOCUMENT + """Type of the result, must be *document*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + title: str + """Title for the result""" + document_url: str + """A valid URL for the file""" + mime_type: str + """MIME type of the content of the file, either 'application/pdf' or 'application/zip'""" + caption: Optional[str] = None + """*Optional*. Caption of the document to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the document caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + description: Optional[str] = None + """*Optional*. Short description of the result""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. Inline keyboard attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the file""" + thumbnail_url: Optional[str] = None + """*Optional*. URL of the thumbnail (JPEG only) for the file""" + thumbnail_width: Optional[int] = None + """*Optional*. Thumbnail width""" + thumbnail_height: Optional[int] = None + """*Optional*. Thumbnail height""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.DOCUMENT] = InlineQueryResultType.DOCUMENT, + id: str, + title: str, + document_url: str, + mime_type: str, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + description: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + thumbnail_url: Optional[str] = None, + thumbnail_width: Optional[int] = None, + thumbnail_height: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + title=title, + document_url=document_url, + mime_type=mime_type, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + description=description, + reply_markup=reply_markup, + input_message_content=input_message_content, + thumbnail_url=thumbnail_url, + thumbnail_width=thumbnail_width, + thumbnail_height=thumbnail_height, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_game.py b/env/Lib/site-packages/aiogram/types/inline_query_result_game.py new file mode 100644 index 0000000..3c7dcde --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_game.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + + +class InlineQueryResultGame(InlineQueryResult): + """ + Represents a `Game `_. + + Source: https://core.telegram.org/bots/api#inlinequeryresultgame + """ + + type: Literal[InlineQueryResultType.GAME] = InlineQueryResultType.GAME + """Type of the result, must be *game*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + game_short_name: str + """Short name of the game""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.GAME] = InlineQueryResultType.GAME, + id: str, + game_short_name: str, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + game_short_name=game_short_name, + reply_markup=reply_markup, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_gif.py b/env/Lib/site-packages/aiogram/types/inline_query_result_gif.py new file mode 100644 index 0000000..3ad0eef --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_gif.py @@ -0,0 +1,121 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .base import UNSET_PARSE_MODE +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultGif(InlineQueryResult): + """ + Represents a link to an animated GIF file. By default, this animated GIF file will be sent by the user with optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the animation. + + Source: https://core.telegram.org/bots/api#inlinequeryresultgif + """ + + type: Literal[InlineQueryResultType.GIF] = InlineQueryResultType.GIF + """Type of the result, must be *gif*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + gif_url: str + """A valid URL for the GIF file. File size must not exceed 1MB""" + thumbnail_url: str + """URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result""" + gif_width: Optional[int] = None + """*Optional*. Width of the GIF""" + gif_height: Optional[int] = None + """*Optional*. Height of the GIF""" + gif_duration: Optional[int] = None + """*Optional*. Duration of the GIF in seconds""" + thumbnail_mime_type: Optional[str] = None + """*Optional*. MIME type of the thumbnail, must be one of 'image/jpeg', 'image/gif', or 'video/mp4'. Defaults to 'image/jpeg'""" + title: Optional[str] = None + """*Optional*. Title for the result""" + caption: Optional[str] = None + """*Optional*. Caption of the GIF file to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the GIF animation""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.GIF] = InlineQueryResultType.GIF, + id: str, + gif_url: str, + thumbnail_url: str, + gif_width: Optional[int] = None, + gif_height: Optional[int] = None, + gif_duration: Optional[int] = None, + thumbnail_mime_type: Optional[str] = None, + title: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + gif_url=gif_url, + thumbnail_url=thumbnail_url, + gif_width=gif_width, + gif_height=gif_height, + gif_duration=gif_duration, + thumbnail_mime_type=thumbnail_mime_type, + title=title, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_location.py b/env/Lib/site-packages/aiogram/types/inline_query_result_location.py new file mode 100644 index 0000000..50b3ed8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_location.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + + +class InlineQueryResultLocation(InlineQueryResult): + """ + Represents a location on a map. By default, the location will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the location. + + Source: https://core.telegram.org/bots/api#inlinequeryresultlocation + """ + + type: Literal[InlineQueryResultType.LOCATION] = InlineQueryResultType.LOCATION + """Type of the result, must be *location*""" + id: str + """Unique identifier for this result, 1-64 Bytes""" + latitude: float + """Location latitude in degrees""" + longitude: float + """Location longitude in degrees""" + title: str + """Location title""" + horizontal_accuracy: Optional[float] = None + """*Optional*. The radius of uncertainty for the location, measured in meters; 0-1500""" + live_period: Optional[int] = None + """*Optional*. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely.""" + heading: Optional[int] = None + """*Optional*. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.""" + proximity_alert_radius: Optional[int] = None + """*Optional*. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the location""" + thumbnail_url: Optional[str] = None + """*Optional*. Url of the thumbnail for the result""" + thumbnail_width: Optional[int] = None + """*Optional*. Thumbnail width""" + thumbnail_height: Optional[int] = None + """*Optional*. Thumbnail height""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.LOCATION] = InlineQueryResultType.LOCATION, + id: str, + latitude: float, + longitude: float, + title: str, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + thumbnail_url: Optional[str] = None, + thumbnail_width: Optional[int] = None, + thumbnail_height: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + latitude=latitude, + longitude=longitude, + title=title, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + reply_markup=reply_markup, + input_message_content=input_message_content, + thumbnail_url=thumbnail_url, + thumbnail_width=thumbnail_width, + thumbnail_height=thumbnail_height, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_mpeg4_gif.py b/env/Lib/site-packages/aiogram/types/inline_query_result_mpeg4_gif.py new file mode 100644 index 0000000..6ca282e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_mpeg4_gif.py @@ -0,0 +1,120 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultMpeg4Gif(InlineQueryResult): + """ + Represents a link to a video animation (H.264/MPEG-4 AVC video without sound). By default, this animated MPEG-4 file will be sent by the user with optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the animation. + + Source: https://core.telegram.org/bots/api#inlinequeryresultmpeg4gif + """ + + type: Literal[InlineQueryResultType.MPEG4_GIF] = InlineQueryResultType.MPEG4_GIF + """Type of the result, must be *mpeg4_gif*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + mpeg4_url: str + """A valid URL for the MPEG4 file. File size must not exceed 1MB""" + thumbnail_url: str + """URL of the static (JPEG or GIF) or animated (MPEG4) thumbnail for the result""" + mpeg4_width: Optional[int] = None + """*Optional*. Video width""" + mpeg4_height: Optional[int] = None + """*Optional*. Video height""" + mpeg4_duration: Optional[int] = None + """*Optional*. Video duration in seconds""" + thumbnail_mime_type: Optional[str] = None + """*Optional*. MIME type of the thumbnail, must be one of 'image/jpeg', 'image/gif', or 'video/mp4'. Defaults to 'image/jpeg'""" + title: Optional[str] = None + """*Optional*. Title for the result""" + caption: Optional[str] = None + """*Optional*. Caption of the MPEG-4 file to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the video animation""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.MPEG4_GIF] = InlineQueryResultType.MPEG4_GIF, + id: str, + mpeg4_url: str, + thumbnail_url: str, + mpeg4_width: Optional[int] = None, + mpeg4_height: Optional[int] = None, + mpeg4_duration: Optional[int] = None, + thumbnail_mime_type: Optional[str] = None, + title: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + mpeg4_url=mpeg4_url, + thumbnail_url=thumbnail_url, + mpeg4_width=mpeg4_width, + mpeg4_height=mpeg4_height, + mpeg4_duration=mpeg4_duration, + thumbnail_mime_type=thumbnail_mime_type, + title=title, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_photo.py b/env/Lib/site-packages/aiogram/types/inline_query_result_photo.py new file mode 100644 index 0000000..02f6841 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_photo.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultPhoto(InlineQueryResult): + """ + Represents a link to a photo. By default, this photo will be sent by the user with optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the photo. + + Source: https://core.telegram.org/bots/api#inlinequeryresultphoto + """ + + type: Literal[InlineQueryResultType.PHOTO] = InlineQueryResultType.PHOTO + """Type of the result, must be *photo*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + photo_url: str + """A valid URL of the photo. Photo must be in **JPEG** format. Photo size must not exceed 5MB""" + thumbnail_url: str + """URL of the thumbnail for the photo""" + photo_width: Optional[int] = None + """*Optional*. Width of the photo""" + photo_height: Optional[int] = None + """*Optional*. Height of the photo""" + title: Optional[str] = None + """*Optional*. Title for the result""" + description: Optional[str] = None + """*Optional*. Short description of the result""" + caption: Optional[str] = None + """*Optional*. Caption of the photo to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the photo caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the photo""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.PHOTO] = InlineQueryResultType.PHOTO, + id: str, + photo_url: str, + thumbnail_url: str, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + title: Optional[str] = None, + description: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + photo_url=photo_url, + thumbnail_url=thumbnail_url, + photo_width=photo_width, + photo_height=photo_height, + title=title, + description=description, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_venue.py b/env/Lib/site-packages/aiogram/types/inline_query_result_venue.py new file mode 100644 index 0000000..b8775b6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_venue.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + + +class InlineQueryResultVenue(InlineQueryResult): + """ + Represents a venue. By default, the venue will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the venue. + + Source: https://core.telegram.org/bots/api#inlinequeryresultvenue + """ + + type: Literal[InlineQueryResultType.VENUE] = InlineQueryResultType.VENUE + """Type of the result, must be *venue*""" + id: str + """Unique identifier for this result, 1-64 Bytes""" + latitude: float + """Latitude of the venue location in degrees""" + longitude: float + """Longitude of the venue location in degrees""" + title: str + """Title of the venue""" + address: str + """Address of the venue""" + foursquare_id: Optional[str] = None + """*Optional*. Foursquare identifier of the venue if known""" + foursquare_type: Optional[str] = None + """*Optional*. Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.)""" + google_place_id: Optional[str] = None + """*Optional*. Google Places identifier of the venue""" + google_place_type: Optional[str] = None + """*Optional*. Google Places type of the venue. (See `supported types `_.)""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the venue""" + thumbnail_url: Optional[str] = None + """*Optional*. Url of the thumbnail for the result""" + thumbnail_width: Optional[int] = None + """*Optional*. Thumbnail width""" + thumbnail_height: Optional[int] = None + """*Optional*. Thumbnail height""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.VENUE] = InlineQueryResultType.VENUE, + id: str, + latitude: float, + longitude: float, + title: str, + address: str, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + thumbnail_url: Optional[str] = None, + thumbnail_width: Optional[int] = None, + thumbnail_height: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + latitude=latitude, + longitude=longitude, + title=title, + address=address, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + reply_markup=reply_markup, + input_message_content=input_message_content, + thumbnail_url=thumbnail_url, + thumbnail_width=thumbnail_width, + thumbnail_height=thumbnail_height, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_video.py b/env/Lib/site-packages/aiogram/types/inline_query_result_video.py new file mode 100644 index 0000000..52332fd --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_video.py @@ -0,0 +1,126 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultVideo(InlineQueryResult): + """ + Represents a link to a page containing an embedded video player or a video file. By default, this video file will be sent by the user with an optional caption. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the video. + + If an InlineQueryResultVideo message contains an embedded video (e.g., YouTube), you **must** replace its content using *input_message_content*. + + Source: https://core.telegram.org/bots/api#inlinequeryresultvideo + """ + + type: Literal[InlineQueryResultType.VIDEO] = InlineQueryResultType.VIDEO + """Type of the result, must be *video*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + video_url: str + """A valid URL for the embedded video player or video file""" + mime_type: str + """MIME type of the content of the video URL, 'text/html' or 'video/mp4'""" + thumbnail_url: str + """URL of the thumbnail (JPEG only) for the video""" + title: str + """Title for the result""" + caption: Optional[str] = None + """*Optional*. Caption of the video to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the video caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + video_width: Optional[int] = None + """*Optional*. Video width""" + video_height: Optional[int] = None + """*Optional*. Video height""" + video_duration: Optional[int] = None + """*Optional*. Video duration in seconds""" + description: Optional[str] = None + """*Optional*. Short description of the result""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the video. This field is **required** if InlineQueryResultVideo is used to send an HTML-page as a result (e.g., a YouTube video).""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.VIDEO] = InlineQueryResultType.VIDEO, + id: str, + video_url: str, + mime_type: str, + thumbnail_url: str, + title: str, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + video_width: Optional[int] = None, + video_height: Optional[int] = None, + video_duration: Optional[int] = None, + description: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + video_url=video_url, + mime_type=mime_type, + thumbnail_url=thumbnail_url, + title=title, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + video_width=video_width, + video_height=video_height, + video_duration=video_duration, + description=description, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_result_voice.py b/env/Lib/site-packages/aiogram/types/inline_query_result_voice.py new file mode 100644 index 0000000..a781fc6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_result_voice.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InlineQueryResultType +from .inline_query_result import InlineQueryResult + +if TYPE_CHECKING: + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_contact_message_content import InputContactMessageContent + from .input_invoice_message_content import InputInvoiceMessageContent + from .input_location_message_content import InputLocationMessageContent + from .input_text_message_content import InputTextMessageContent + from .input_venue_message_content import InputVenueMessageContent + from .message_entity import MessageEntity + + +class InlineQueryResultVoice(InlineQueryResult): + """ + Represents a link to a voice recording in an .OGG container encoded with OPUS. By default, this voice recording will be sent by the user. Alternatively, you can use *input_message_content* to send a message with the specified content instead of the the voice message. + + Source: https://core.telegram.org/bots/api#inlinequeryresultvoice + """ + + type: Literal[InlineQueryResultType.VOICE] = InlineQueryResultType.VOICE + """Type of the result, must be *voice*""" + id: str + """Unique identifier for this result, 1-64 bytes""" + voice_url: str + """A valid URL for the voice recording""" + title: str + """Recording title""" + caption: Optional[str] = None + """*Optional*. Caption, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the voice message caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + voice_duration: Optional[int] = None + """*Optional*. Recording duration in seconds""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. `Inline keyboard `_ attached to the message""" + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None + """*Optional*. Content of the message to be sent instead of the voice recording""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InlineQueryResultType.VOICE] = InlineQueryResultType.VOICE, + id: str, + voice_url: str, + title: str, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + voice_duration: Optional[int] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + input_message_content: Optional[ + Union[ + InputTextMessageContent, + InputLocationMessageContent, + InputVenueMessageContent, + InputContactMessageContent, + InputInvoiceMessageContent, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + id=id, + voice_url=voice_url, + title=title, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + voice_duration=voice_duration, + reply_markup=reply_markup, + input_message_content=input_message_content, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/inline_query_results_button.py b/env/Lib/site-packages/aiogram/types/inline_query_results_button.py new file mode 100644 index 0000000..6943fb8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/inline_query_results_button.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .web_app_info import WebAppInfo + + +class InlineQueryResultsButton(TelegramObject): + """ + This object represents a button to be shown above inline query results. You **must** use exactly one of the optional fields. + + Source: https://core.telegram.org/bots/api#inlinequeryresultsbutton + """ + + text: str + """Label text on the button""" + web_app: Optional[WebAppInfo] = None + """*Optional*. Description of the `Web App `_ that will be launched when the user presses the button. The Web App will be able to switch back to the inline mode using the method `switchInlineQuery `_ inside the Web App.""" + start_parameter: Optional[str] = None + """*Optional*. `Deep-linking `_ parameter for the /start message sent to the bot when a user presses the button. 1-64 characters, only :code:`A-Z`, :code:`a-z`, :code:`0-9`, :code:`_` and :code:`-` are allowed.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + text: str, + web_app: Optional[WebAppInfo] = None, + start_parameter: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + text=text, web_app=web_app, start_parameter=start_parameter, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/input_contact_message_content.py b/env/Lib/site-packages/aiogram/types/input_contact_message_content.py new file mode 100644 index 0000000..8bcb581 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_contact_message_content.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .input_message_content import InputMessageContent + + +class InputContactMessageContent(InputMessageContent): + """ + Represents the `content `_ of a contact message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputcontactmessagecontent + """ + + phone_number: str + """Contact's phone number""" + first_name: str + """Contact's first name""" + last_name: Optional[str] = None + """*Optional*. Contact's last name""" + vcard: Optional[str] = None + """*Optional*. Additional data about the contact in the form of a `vCard `_, 0-2048 bytes""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + phone_number: str, + first_name: str, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + phone_number=phone_number, + first_name=first_name, + last_name=last_name, + vcard=vcard, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_file.py b/env/Lib/site-packages/aiogram/types/input_file.py new file mode 100644 index 0000000..5b73059 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_file.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import io +import os +from abc import ABC, abstractmethod +from pathlib import Path +from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, Optional, Union + +import aiofiles + +if TYPE_CHECKING: + from aiogram.client.bot import Bot + +DEFAULT_CHUNK_SIZE = 64 * 1024 # 64 kb + + +class InputFile(ABC): + """ + This object represents the contents of a file to be uploaded. Must be posted using multipart/form-data in the usual way that files are uploaded via the browser. + + Source: https://core.telegram.org/bots/api#inputfile + """ + + def __init__(self, filename: Optional[str] = None, chunk_size: int = DEFAULT_CHUNK_SIZE): + """ + Base class for input files. Should not be used directly. + Look at :class:`BufferedInputFile`, :class:`FSInputFile` :class:`URLInputFile` + + :param filename: name of the given file + :param chunk_size: reader chunks size + """ + self.filename = filename + self.chunk_size = chunk_size + + @abstractmethod + async def read(self, bot: "Bot") -> AsyncGenerator[bytes, None]: # pragma: no cover + yield b"" + + +class BufferedInputFile(InputFile): + def __init__(self, file: bytes, filename: str, chunk_size: int = DEFAULT_CHUNK_SIZE): + """ + Represents object for uploading files from filesystem + + :param file: Bytes + :param filename: Filename to be propagated to telegram. + :param chunk_size: Uploading chunk size + """ + super().__init__(filename=filename, chunk_size=chunk_size) + + self.data = file + + @classmethod + def from_file( + cls, + path: Union[str, Path], + filename: Optional[str] = None, + chunk_size: int = DEFAULT_CHUNK_SIZE, + ) -> BufferedInputFile: + """ + Create buffer from file + + :param path: Path to file + :param filename: Filename to be propagated to telegram. + By default, will be parsed from path + :param chunk_size: Uploading chunk size + :return: instance of :obj:`BufferedInputFile` + """ + if filename is None: + filename = os.path.basename(path) + with open(path, "rb") as f: + data = f.read() + return cls(data, filename=filename, chunk_size=chunk_size) + + async def read(self, bot: "Bot") -> AsyncGenerator[bytes, None]: + buffer = io.BytesIO(self.data) + while chunk := buffer.read(self.chunk_size): + yield chunk + + +class FSInputFile(InputFile): + def __init__( + self, + path: Union[str, Path], + filename: Optional[str] = None, + chunk_size: int = DEFAULT_CHUNK_SIZE, + ): + """ + Represents object for uploading files from filesystem + + :param path: Path to file + :param filename: Filename to be propagated to telegram. + By default, will be parsed from path + :param chunk_size: Uploading chunk size + """ + if filename is None: + filename = os.path.basename(path) + super().__init__(filename=filename, chunk_size=chunk_size) + + self.path = path + + async def read(self, bot: "Bot") -> AsyncGenerator[bytes, None]: + async with aiofiles.open(self.path, "rb") as f: + while chunk := await f.read(self.chunk_size): + yield chunk + + +class URLInputFile(InputFile): + def __init__( + self, + url: str, + headers: Optional[Dict[str, Any]] = None, + filename: Optional[str] = None, + chunk_size: int = DEFAULT_CHUNK_SIZE, + timeout: int = 30, + bot: Optional["Bot"] = None, + ): + """ + Represents object for streaming files from internet + + :param url: URL in internet + :param headers: HTTP Headers + :param filename: Filename to be propagated to telegram. + :param chunk_size: Uploading chunk size + :param timeout: Timeout for downloading + :param bot: Bot instance to use HTTP session from. + If not specified, will be used current bot + """ + super().__init__(filename=filename, chunk_size=chunk_size) + if headers is None: + headers = {} + + self.url = url + self.headers = headers + self.timeout = timeout + self.bot = bot + + async def read(self, bot: "Bot") -> AsyncGenerator[bytes, None]: + bot = self.bot or bot + stream = bot.session.stream_content( + url=self.url, + headers=self.headers, + timeout=self.timeout, + chunk_size=self.chunk_size, + raise_for_status=True, + ) + + async for chunk in stream: + yield chunk diff --git a/env/Lib/site-packages/aiogram/types/input_invoice_message_content.py b/env/Lib/site-packages/aiogram/types/input_invoice_message_content.py new file mode 100644 index 0000000..0dbb6d2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_invoice_message_content.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .input_message_content import InputMessageContent + +if TYPE_CHECKING: + from .labeled_price import LabeledPrice + + +class InputInvoiceMessageContent(InputMessageContent): + """ + Represents the `content `_ of an invoice message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputinvoicemessagecontent + """ + + title: str + """Product name, 1-32 characters""" + description: str + """Product description, 1-255 characters""" + payload: str + """Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes.""" + currency: str + """Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_.""" + prices: List[LabeledPrice] + """Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_.""" + provider_token: Optional[str] = None + """*Optional*. Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_.""" + max_tip_amount: Optional[int] = None + """*Optional*. The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_.""" + suggested_tip_amounts: Optional[List[int]] = None + """*Optional*. A JSON-serialized array of suggested amounts of tip in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*.""" + provider_data: Optional[str] = None + """*Optional*. A JSON-serialized object for data about the invoice, which will be shared with the payment provider. A detailed description of the required fields should be provided by the payment provider.""" + photo_url: Optional[str] = None + """*Optional*. URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service.""" + photo_size: Optional[int] = None + """*Optional*. Photo size in bytes""" + photo_width: Optional[int] = None + """*Optional*. Photo width""" + photo_height: Optional[int] = None + """*Optional*. Photo height""" + need_name: Optional[bool] = None + """*Optional*. Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_phone_number: Optional[bool] = None + """*Optional*. Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_email: Optional[bool] = None + """*Optional*. Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_.""" + need_shipping_address: Optional[bool] = None + """*Optional*. Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_.""" + send_phone_number_to_provider: Optional[bool] = None + """*Optional*. Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_.""" + send_email_to_provider: Optional[bool] = None + """*Optional*. Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_.""" + is_flexible: Optional[bool] = None + """*Optional*. Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_location_message_content.py b/env/Lib/site-packages/aiogram/types/input_location_message_content.py new file mode 100644 index 0000000..83400c1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_location_message_content.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .input_message_content import InputMessageContent + + +class InputLocationMessageContent(InputMessageContent): + """ + Represents the `content `_ of a location message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputlocationmessagecontent + """ + + latitude: float + """Latitude of the location in degrees""" + longitude: float + """Longitude of the location in degrees""" + horizontal_accuracy: Optional[float] = None + """*Optional*. The radius of uncertainty for the location, measured in meters; 0-1500""" + live_period: Optional[int] = None + """*Optional*. Period in seconds during which the location can be updated, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely.""" + heading: Optional[int] = None + """*Optional*. For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified.""" + proximity_alert_radius: Optional[int] = None + """*Optional*. For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + latitude: float, + longitude: float, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + latitude=latitude, + longitude=longitude, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_media.py b/env/Lib/site-packages/aiogram/types/input_media.py new file mode 100644 index 0000000..f7523c9 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_media.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from .base import MutableTelegramObject + + +class InputMedia(MutableTelegramObject): + """ + This object represents the content of a media message to be sent. It should be one of + + - :class:`aiogram.types.input_media_animation.InputMediaAnimation` + - :class:`aiogram.types.input_media_document.InputMediaDocument` + - :class:`aiogram.types.input_media_audio.InputMediaAudio` + - :class:`aiogram.types.input_media_photo.InputMediaPhoto` + - :class:`aiogram.types.input_media_video.InputMediaVideo` + + Source: https://core.telegram.org/bots/api#inputmedia + """ diff --git a/env/Lib/site-packages/aiogram/types/input_media_animation.py b/env/Lib/site-packages/aiogram/types/input_media_animation.py new file mode 100644 index 0000000..a0251f2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_media_animation.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InputMediaType +from .input_media import InputMedia + +if TYPE_CHECKING: + from .input_file import InputFile + from .message_entity import MessageEntity + + +class InputMediaAnimation(InputMedia): + """ + Represents an animation file (GIF or H.264/MPEG-4 AVC video without sound) to be sent. + + Source: https://core.telegram.org/bots/api#inputmediaanimation + """ + + type: Literal[InputMediaType.ANIMATION] = InputMediaType.ANIMATION + """Type of the result, must be *animation*""" + media: Union[str, InputFile] + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name. :ref:`More information on Sending Files » `""" + thumbnail: Optional[InputFile] = None + """*Optional*. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + caption: Optional[str] = None + """*Optional*. Caption of the animation to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the animation caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + width: Optional[int] = None + """*Optional*. Animation width""" + height: Optional[int] = None + """*Optional*. Animation height""" + duration: Optional[int] = None + """*Optional*. Animation duration in seconds""" + has_spoiler: Optional[bool] = None + """*Optional*. Pass :code:`True` if the animation needs to be covered with a spoiler animation""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InputMediaType.ANIMATION] = InputMediaType.ANIMATION, + media: Union[str, InputFile], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + width: Optional[int] = None, + height: Optional[int] = None, + duration: Optional[int] = None, + has_spoiler: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + media=media, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + width=width, + height=height, + duration=duration, + has_spoiler=has_spoiler, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_media_audio.py b/env/Lib/site-packages/aiogram/types/input_media_audio.py new file mode 100644 index 0000000..c372201 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_media_audio.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InputMediaType +from .input_media import InputMedia + +if TYPE_CHECKING: + from .input_file import InputFile + from .message_entity import MessageEntity + + +class InputMediaAudio(InputMedia): + """ + Represents an audio file to be treated as music to be sent. + + Source: https://core.telegram.org/bots/api#inputmediaaudio + """ + + type: Literal[InputMediaType.AUDIO] = InputMediaType.AUDIO + """Type of the result, must be *audio*""" + media: Union[str, InputFile] + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name. :ref:`More information on Sending Files » `""" + thumbnail: Optional[InputFile] = None + """*Optional*. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + caption: Optional[str] = None + """*Optional*. Caption of the audio to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the audio caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + duration: Optional[int] = None + """*Optional*. Duration of the audio in seconds""" + performer: Optional[str] = None + """*Optional*. Performer of the audio""" + title: Optional[str] = None + """*Optional*. Title of the audio""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InputMediaType.AUDIO] = InputMediaType.AUDIO, + media: Union[str, InputFile], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + media=media, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_media_document.py b/env/Lib/site-packages/aiogram/types/input_media_document.py new file mode 100644 index 0000000..7c24b92 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_media_document.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InputMediaType +from .input_media import InputMedia + +if TYPE_CHECKING: + from .input_file import InputFile + from .message_entity import MessageEntity + + +class InputMediaDocument(InputMedia): + """ + Represents a general file to be sent. + + Source: https://core.telegram.org/bots/api#inputmediadocument + """ + + type: Literal[InputMediaType.DOCUMENT] = InputMediaType.DOCUMENT + """Type of the result, must be *document*""" + media: Union[str, InputFile] + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name. :ref:`More information on Sending Files » `""" + thumbnail: Optional[InputFile] = None + """*Optional*. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + caption: Optional[str] = None + """*Optional*. Caption of the document to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the document caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + disable_content_type_detection: Optional[bool] = None + """*Optional*. Disables automatic server-side content type detection for files uploaded using multipart/form-data. Always :code:`True`, if the document is sent as part of an album.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InputMediaType.DOCUMENT] = InputMediaType.DOCUMENT, + media: Union[str, InputFile], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + media=media, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_media_photo.py b/env/Lib/site-packages/aiogram/types/input_media_photo.py new file mode 100644 index 0000000..19daa26 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_media_photo.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InputMediaType +from .input_media import InputMedia + +if TYPE_CHECKING: + from .input_file import InputFile + from .message_entity import MessageEntity + + +class InputMediaPhoto(InputMedia): + """ + Represents a photo to be sent. + + Source: https://core.telegram.org/bots/api#inputmediaphoto + """ + + type: Literal[InputMediaType.PHOTO] = InputMediaType.PHOTO + """Type of the result, must be *photo*""" + media: Union[str, InputFile] + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name. :ref:`More information on Sending Files » `""" + caption: Optional[str] = None + """*Optional*. Caption of the photo to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the photo caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + has_spoiler: Optional[bool] = None + """*Optional*. Pass :code:`True` if the photo needs to be covered with a spoiler animation""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InputMediaType.PHOTO] = InputMediaType.PHOTO, + media: Union[str, InputFile], + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + media=media, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_media_video.py b/env/Lib/site-packages/aiogram/types/input_media_video.py new file mode 100644 index 0000000..6f1e326 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_media_video.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..client.default import Default +from ..enums import InputMediaType +from .input_media import InputMedia + +if TYPE_CHECKING: + from .input_file import InputFile + from .message_entity import MessageEntity + + +class InputMediaVideo(InputMedia): + """ + Represents a video to be sent. + + Source: https://core.telegram.org/bots/api#inputmediavideo + """ + + type: Literal[InputMediaType.VIDEO] = InputMediaType.VIDEO + """Type of the result, must be *video*""" + media: Union[str, InputFile] + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name. :ref:`More information on Sending Files » `""" + thumbnail: Optional[InputFile] = None + """*Optional*. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + caption: Optional[str] = None + """*Optional*. Caption of the video to be sent, 0-1024 characters after entities parsing""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the video caption. See `formatting options `_ for more details.""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in the caption, which can be specified instead of *parse_mode*""" + show_caption_above_media: Optional[Union[bool, Default]] = Default("show_caption_above_media") + """*Optional*. Pass :code:`True`, if the caption must be shown above the message media""" + width: Optional[int] = None + """*Optional*. Video width""" + height: Optional[int] = None + """*Optional*. Video height""" + duration: Optional[int] = None + """*Optional*. Video duration in seconds""" + supports_streaming: Optional[bool] = None + """*Optional*. Pass :code:`True` if the uploaded video is suitable for streaming""" + has_spoiler: Optional[bool] = None + """*Optional*. Pass :code:`True` if the video needs to be covered with a spoiler animation""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InputMediaType.VIDEO] = InputMediaType.VIDEO, + media: Union[str, InputFile], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + width: Optional[int] = None, + height: Optional[int] = None, + duration: Optional[int] = None, + supports_streaming: Optional[bool] = None, + has_spoiler: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + media=media, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + width=width, + height=height, + duration=duration, + supports_streaming=supports_streaming, + has_spoiler=has_spoiler, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_message_content.py b/env/Lib/site-packages/aiogram/types/input_message_content.py new file mode 100644 index 0000000..858524a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_message_content.py @@ -0,0 +1,17 @@ +from __future__ import annotations + +from .base import MutableTelegramObject + + +class InputMessageContent(MutableTelegramObject): + """ + This object represents the content of a message to be sent as a result of an inline query. Telegram clients currently support the following 5 types: + + - :class:`aiogram.types.input_text_message_content.InputTextMessageContent` + - :class:`aiogram.types.input_location_message_content.InputLocationMessageContent` + - :class:`aiogram.types.input_venue_message_content.InputVenueMessageContent` + - :class:`aiogram.types.input_contact_message_content.InputContactMessageContent` + - :class:`aiogram.types.input_invoice_message_content.InputInvoiceMessageContent` + + Source: https://core.telegram.org/bots/api#inputmessagecontent + """ diff --git a/env/Lib/site-packages/aiogram/types/input_paid_media.py b/env/Lib/site-packages/aiogram/types/input_paid_media.py new file mode 100644 index 0000000..9d3193d --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_paid_media.py @@ -0,0 +1,12 @@ +from .base import TelegramObject + + +class InputPaidMedia(TelegramObject): + """ + This object describes the paid media to be sent. Currently, it can be one of + + - :class:`aiogram.types.input_paid_media_photo.InputPaidMediaPhoto` + - :class:`aiogram.types.input_paid_media_video.InputPaidMediaVideo` + + Source: https://core.telegram.org/bots/api#inputpaidmedia + """ diff --git a/env/Lib/site-packages/aiogram/types/input_paid_media_photo.py b/env/Lib/site-packages/aiogram/types/input_paid_media_photo.py new file mode 100644 index 0000000..1756db5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_paid_media_photo.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Union + +from ..enums import InputPaidMediaType +from .input_file import InputFile +from .input_paid_media import InputPaidMedia + + +class InputPaidMediaPhoto(InputPaidMedia): + """ + The paid media to send is a photo. + + Source: https://core.telegram.org/bots/api#inputpaidmediaphoto + """ + + type: Literal[InputPaidMediaType.PHOTO] = InputPaidMediaType.PHOTO + """Type of the media, must be *photo*""" + media: Union[str, InputFile] + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name. :ref:`More information on Sending Files » `""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InputPaidMediaType.PHOTO] = InputPaidMediaType.PHOTO, + media: Union[str, InputFile], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, media=media, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/input_paid_media_video.py b/env/Lib/site-packages/aiogram/types/input_paid_media_video.py new file mode 100644 index 0000000..4511afb --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_paid_media_video.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from ..enums import InputPaidMediaType +from .input_file import InputFile +from .input_paid_media import InputPaidMedia + + +class InputPaidMediaVideo(InputPaidMedia): + """ + The paid media to send is a video. + + Source: https://core.telegram.org/bots/api#inputpaidmediavideo + """ + + type: Literal[InputPaidMediaType.VIDEO] = InputPaidMediaType.VIDEO + """Type of the media, must be *video*""" + media: Union[str, InputFile] + """File to send. Pass a file_id to send a file that exists on the Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from the Internet, or pass 'attach://' to upload a new one using multipart/form-data under name. :ref:`More information on Sending Files » `""" + thumbnail: Optional[Union[InputFile, str]] = None + """*Optional*. Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » `""" + width: Optional[int] = None + """*Optional*. Video width""" + height: Optional[int] = None + """*Optional*. Video height""" + duration: Optional[int] = None + """*Optional*. Video duration in seconds""" + supports_streaming: Optional[bool] = None + """*Optional*. Pass :code:`True` if the uploaded video is suitable for streaming""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[InputPaidMediaType.VIDEO] = InputPaidMediaType.VIDEO, + media: Union[str, InputFile], + thumbnail: Optional[Union[InputFile, str]] = None, + width: Optional[int] = None, + height: Optional[int] = None, + duration: Optional[int] = None, + supports_streaming: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + media=media, + thumbnail=thumbnail, + width=width, + height=height, + duration=duration, + supports_streaming=supports_streaming, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_poll_option.py b/env/Lib/site-packages/aiogram/types/input_poll_option.py new file mode 100644 index 0000000..7bca9f6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_poll_option.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..client.default import Default +from .base import TelegramObject + +if TYPE_CHECKING: + from .message_entity import MessageEntity + + +class InputPollOption(TelegramObject): + """ + This object contains information about one answer option in a poll to be sent. + + Source: https://core.telegram.org/bots/api#inputpolloption + """ + + text: str + """Option text, 1-100 characters""" + text_parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the text. See `formatting options `_ for more details. Currently, only custom emoji entities are allowed""" + text_entities: Optional[List[MessageEntity]] = None + """*Optional*. A JSON-serialized list of special entities that appear in the poll option text. It can be specified instead of *text_parse_mode*""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + text: str, + text_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + text_entities: Optional[List[MessageEntity]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + text=text, + text_parse_mode=text_parse_mode, + text_entities=text_entities, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_sticker.py b/env/Lib/site-packages/aiogram/types/input_sticker.py new file mode 100644 index 0000000..85f6686 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_sticker.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from .base import TelegramObject + +if TYPE_CHECKING: + from .input_file import InputFile + from .mask_position import MaskPosition + + +class InputSticker(TelegramObject): + """ + This object describes a sticker to be added to a sticker set. + + Source: https://core.telegram.org/bots/api#inputsticker + """ + + sticker: Union[InputFile, str] + """The added sticker. Pass a *file_id* as a String to send a file that already exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a file from the Internet, upload a new one using multipart/form-data, or pass 'attach://' to upload a new one using multipart/form-data under name. Animated and video stickers can't be uploaded via HTTP URL. :ref:`More information on Sending Files » `""" + format: str + """Format of the added sticker, must be one of 'static' for a **.WEBP** or **.PNG** image, 'animated' for a **.TGS** animation, 'video' for a **WEBM** video""" + emoji_list: List[str] + """List of 1-20 emoji associated with the sticker""" + mask_position: Optional[MaskPosition] = None + """*Optional*. Position where the mask should be placed on faces. For 'mask' stickers only.""" + keywords: Optional[List[str]] = None + """*Optional*. List of 0-20 search keywords for the sticker with total length of up to 64 characters. For 'regular' and 'custom_emoji' stickers only.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + sticker: Union[InputFile, str], + format: str, + emoji_list: List[str], + mask_position: Optional[MaskPosition] = None, + keywords: Optional[List[str]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + sticker=sticker, + format=format, + emoji_list=emoji_list, + mask_position=mask_position, + keywords=keywords, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_text_message_content.py b/env/Lib/site-packages/aiogram/types/input_text_message_content.py new file mode 100644 index 0000000..5048757 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_text_message_content.py @@ -0,0 +1,65 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from pydantic import Field + +from ..client.default import Default +from .input_message_content import InputMessageContent + +if TYPE_CHECKING: + from .link_preview_options import LinkPreviewOptions + from .message_entity import MessageEntity + + +class InputTextMessageContent(InputMessageContent): + """ + Represents the `content `_ of a text message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputtextmessagecontent + """ + + message_text: str + """Text of the message to be sent, 1-4096 characters""" + parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the message text. See `formatting options `_ for more details.""" + entities: Optional[List[MessageEntity]] = None + """*Optional*. List of special entities that appear in message text, which can be specified instead of *parse_mode*""" + link_preview_options: Optional[LinkPreviewOptions] = None + """*Optional*. Link preview generation options for the message""" + disable_web_page_preview: Optional[Union[bool, Default]] = Field( + Default("disable_web_page_preview"), json_schema_extra={"deprecated": True} + ) + """*Optional*. Disables link previews for links in the sent message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + message_text: str, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[LinkPreviewOptions] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "disable_web_page_preview" + ), + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + message_text=message_text, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + disable_web_page_preview=disable_web_page_preview, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/input_venue_message_content.py b/env/Lib/site-packages/aiogram/types/input_venue_message_content.py new file mode 100644 index 0000000..48dd5c4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/input_venue_message_content.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .input_message_content import InputMessageContent + + +class InputVenueMessageContent(InputMessageContent): + """ + Represents the `content `_ of a venue message to be sent as the result of an inline query. + + Source: https://core.telegram.org/bots/api#inputvenuemessagecontent + """ + + latitude: float + """Latitude of the venue in degrees""" + longitude: float + """Longitude of the venue in degrees""" + title: str + """Name of the venue""" + address: str + """Address of the venue""" + foursquare_id: Optional[str] = None + """*Optional*. Foursquare identifier of the venue, if known""" + foursquare_type: Optional[str] = None + """*Optional*. Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.)""" + google_place_id: Optional[str] = None + """*Optional*. Google Places identifier of the venue""" + google_place_type: Optional[str] = None + """*Optional*. Google Places type of the venue. (See `supported types `_.)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + latitude: float, + longitude: float, + title: str, + address: str, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + latitude=latitude, + longitude=longitude, + title=title, + address=address, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/invoice.py b/env/Lib/site-packages/aiogram/types/invoice.py new file mode 100644 index 0000000..7c70f0b --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/invoice.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class Invoice(TelegramObject): + """ + This object contains basic information about an invoice. + + Source: https://core.telegram.org/bots/api#invoice + """ + + title: str + """Product name""" + description: str + """Product description""" + start_parameter: str + """Unique bot deep-linking parameter that can be used to generate this invoice""" + currency: str + """Three-letter ISO 4217 `currency `_ code, or 'XTR' for payments in `Telegram Stars `_""" + total_amount: int + """Total price in the *smallest units* of the currency (integer, **not** float/double). For example, for a price of :code:`US$ 1.45` pass :code:`amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + title: str, + description: str, + start_parameter: str, + currency: str, + total_amount: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + title=title, + description=description, + start_parameter=start_parameter, + currency=currency, + total_amount=total_amount, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/keyboard_button.py b/env/Lib/site-packages/aiogram/types/keyboard_button.py new file mode 100644 index 0000000..0cf7d58 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/keyboard_button.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from pydantic import Field + +from .base import MutableTelegramObject + +if TYPE_CHECKING: + from .keyboard_button_poll_type import KeyboardButtonPollType + from .keyboard_button_request_chat import KeyboardButtonRequestChat + from .keyboard_button_request_user import KeyboardButtonRequestUser + from .keyboard_button_request_users import KeyboardButtonRequestUsers + from .web_app_info import WebAppInfo + + +class KeyboardButton(MutableTelegramObject): + """ + This object represents one button of the reply keyboard. At most one of the optional fields must be used to specify type of the button. For simple text buttons, *String* can be used instead of this object to specify the button text. + **Note:** *request_users* and *request_chat* options will only work in Telegram versions released after 3 February, 2023. Older clients will display *unsupported message*. + + Source: https://core.telegram.org/bots/api#keyboardbutton + """ + + text: str + """Text of the button. If none of the optional fields are used, it will be sent as a message when the button is pressed""" + request_users: Optional[KeyboardButtonRequestUsers] = None + """*Optional.* If specified, pressing the button will open a list of suitable users. Identifiers of selected users will be sent to the bot in a 'users_shared' service message. Available in private chats only.""" + request_chat: Optional[KeyboardButtonRequestChat] = None + """*Optional.* If specified, pressing the button will open a list of suitable chats. Tapping on a chat will send its identifier to the bot in a 'chat_shared' service message. Available in private chats only.""" + request_contact: Optional[bool] = None + """*Optional*. If :code:`True`, the user's phone number will be sent as a contact when the button is pressed. Available in private chats only.""" + request_location: Optional[bool] = None + """*Optional*. If :code:`True`, the user's current location will be sent when the button is pressed. Available in private chats only.""" + request_poll: Optional[KeyboardButtonPollType] = None + """*Optional*. If specified, the user will be asked to create a poll and send it to the bot when the button is pressed. Available in private chats only.""" + web_app: Optional[WebAppInfo] = None + """*Optional*. If specified, the described `Web App `_ will be launched when the button is pressed. The Web App will be able to send a 'web_app_data' service message. Available in private chats only.""" + request_user: Optional[KeyboardButtonRequestUser] = Field( + None, json_schema_extra={"deprecated": True} + ) + """*Optional.* If specified, pressing the button will open a list of suitable users. Tapping on any user will send their identifier to the bot in a 'user_shared' service message. Available in private chats only. + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + text: str, + request_users: Optional[KeyboardButtonRequestUsers] = None, + request_chat: Optional[KeyboardButtonRequestChat] = None, + request_contact: Optional[bool] = None, + request_location: Optional[bool] = None, + request_poll: Optional[KeyboardButtonPollType] = None, + web_app: Optional[WebAppInfo] = None, + request_user: Optional[KeyboardButtonRequestUser] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + text=text, + request_users=request_users, + request_chat=request_chat, + request_contact=request_contact, + request_location=request_location, + request_poll=request_poll, + web_app=web_app, + request_user=request_user, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/keyboard_button_poll_type.py b/env/Lib/site-packages/aiogram/types/keyboard_button_poll_type.py new file mode 100644 index 0000000..07eadb7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/keyboard_button_poll_type.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import MutableTelegramObject + + +class KeyboardButtonPollType(MutableTelegramObject): + """ + This object represents type of a poll, which is allowed to be created and sent when the corresponding button is pressed. + + Source: https://core.telegram.org/bots/api#keyboardbuttonpolltype + """ + + type: Optional[str] = None + """*Optional*. If *quiz* is passed, the user will be allowed to create only polls in the quiz mode. If *regular* is passed, only regular polls will be allowed. Otherwise, the user will be allowed to create a poll of any type.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, type: Optional[str] = None, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/keyboard_button_request_chat.py b/env/Lib/site-packages/aiogram/types/keyboard_button_request_chat.py new file mode 100644 index 0000000..018edcf --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/keyboard_button_request_chat.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from aiogram.types import TelegramObject + +if TYPE_CHECKING: + from .chat_administrator_rights import ChatAdministratorRights + + +class KeyboardButtonRequestChat(TelegramObject): + """ + This object defines the criteria used to request a suitable chat. Information about the selected chat will be shared with the bot when the corresponding button is pressed. The bot will be granted requested rights in the chat if appropriate. `More about requesting chats » `_. + + Source: https://core.telegram.org/bots/api#keyboardbuttonrequestchat + """ + + request_id: int + """Signed 32-bit identifier of the request, which will be received back in the :class:`aiogram.types.chat_shared.ChatShared` object. Must be unique within the message""" + chat_is_channel: bool + """Pass :code:`True` to request a channel chat, pass :code:`False` to request a group or a supergroup chat.""" + chat_is_forum: Optional[bool] = None + """*Optional*. Pass :code:`True` to request a forum supergroup, pass :code:`False` to request a non-forum chat. If not specified, no additional restrictions are applied.""" + chat_has_username: Optional[bool] = None + """*Optional*. Pass :code:`True` to request a supergroup or a channel with a username, pass :code:`False` to request a chat without a username. If not specified, no additional restrictions are applied.""" + chat_is_created: Optional[bool] = None + """*Optional*. Pass :code:`True` to request a chat owned by the user. Otherwise, no additional restrictions are applied.""" + user_administrator_rights: Optional[ChatAdministratorRights] = None + """*Optional*. A JSON-serialized object listing the required administrator rights of the user in the chat. The rights must be a superset of *bot_administrator_rights*. If not specified, no additional restrictions are applied.""" + bot_administrator_rights: Optional[ChatAdministratorRights] = None + """*Optional*. A JSON-serialized object listing the required administrator rights of the bot in the chat. The rights must be a subset of *user_administrator_rights*. If not specified, no additional restrictions are applied.""" + bot_is_member: Optional[bool] = None + """*Optional*. Pass :code:`True` to request a chat with the bot as a member. Otherwise, no additional restrictions are applied.""" + request_title: Optional[bool] = None + """*Optional*. Pass :code:`True` to request the chat's title""" + request_username: Optional[bool] = None + """*Optional*. Pass :code:`True` to request the chat's username""" + request_photo: Optional[bool] = None + """*Optional*. Pass :code:`True` to request the chat's photo""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + request_id: int, + chat_is_channel: bool, + chat_is_forum: Optional[bool] = None, + chat_has_username: Optional[bool] = None, + chat_is_created: Optional[bool] = None, + user_administrator_rights: Optional[ChatAdministratorRights] = None, + bot_administrator_rights: Optional[ChatAdministratorRights] = None, + bot_is_member: Optional[bool] = None, + request_title: Optional[bool] = None, + request_username: Optional[bool] = None, + request_photo: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + request_id=request_id, + chat_is_channel=chat_is_channel, + chat_is_forum=chat_is_forum, + chat_has_username=chat_has_username, + chat_is_created=chat_is_created, + user_administrator_rights=user_administrator_rights, + bot_administrator_rights=bot_administrator_rights, + bot_is_member=bot_is_member, + request_title=request_title, + request_username=request_username, + request_photo=request_photo, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/keyboard_button_request_user.py b/env/Lib/site-packages/aiogram/types/keyboard_button_request_user.py new file mode 100644 index 0000000..ab44ab2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/keyboard_button_request_user.py @@ -0,0 +1,44 @@ +from typing import TYPE_CHECKING, Any, Optional + +from aiogram.types import TelegramObject + + +class KeyboardButtonRequestUser(TelegramObject): + """ + This object defines the criteria used to request a suitable user. The identifier of the selected user will be shared with the bot when the corresponding button is pressed. `More about requesting users » `_ + + .. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023 + + Source: https://core.telegram.org/bots/api#keyboardbuttonrequestuser + """ + + request_id: int + """Signed 32-bit identifier of the request, which will be received back in the :class:`aiogram.types.user_shared.UserShared` object. Must be unique within the message""" + user_is_bot: Optional[bool] = None + """*Optional*. Pass :code:`True` to request a bot, pass :code:`False` to request a regular user. If not specified, no additional restrictions are applied.""" + user_is_premium: Optional[bool] = None + """*Optional*. Pass :code:`True` to request a premium user, pass :code:`False` to request a non-premium user. If not specified, no additional restrictions are applied.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + request_id: int, + user_is_bot: Optional[bool] = None, + user_is_premium: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + request_id=request_id, + user_is_bot=user_is_bot, + user_is_premium=user_is_premium, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/keyboard_button_request_users.py b/env/Lib/site-packages/aiogram/types/keyboard_button_request_users.py new file mode 100644 index 0000000..631f04b --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/keyboard_button_request_users.py @@ -0,0 +1,57 @@ +from typing import TYPE_CHECKING, Any, Optional + +from aiogram.types import TelegramObject + + +class KeyboardButtonRequestUsers(TelegramObject): + """ + This object defines the criteria used to request suitable users. Information about the selected users will be shared with the bot when the corresponding button is pressed. `More about requesting users » `_ + + Source: https://core.telegram.org/bots/api#keyboardbuttonrequestusers + """ + + request_id: int + """Signed 32-bit identifier of the request that will be received back in the :class:`aiogram.types.users_shared.UsersShared` object. Must be unique within the message""" + user_is_bot: Optional[bool] = None + """*Optional*. Pass :code:`True` to request bots, pass :code:`False` to request regular users. If not specified, no additional restrictions are applied.""" + user_is_premium: Optional[bool] = None + """*Optional*. Pass :code:`True` to request premium users, pass :code:`False` to request non-premium users. If not specified, no additional restrictions are applied.""" + max_quantity: Optional[int] = None + """*Optional*. The maximum number of users to be selected; 1-10. Defaults to 1.""" + request_name: Optional[bool] = None + """*Optional*. Pass :code:`True` to request the users' first and last names""" + request_username: Optional[bool] = None + """*Optional*. Pass :code:`True` to request the users' usernames""" + request_photo: Optional[bool] = None + """*Optional*. Pass :code:`True` to request the users' photos""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + request_id: int, + user_is_bot: Optional[bool] = None, + user_is_premium: Optional[bool] = None, + max_quantity: Optional[int] = None, + request_name: Optional[bool] = None, + request_username: Optional[bool] = None, + request_photo: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + request_id=request_id, + user_is_bot=user_is_bot, + user_is_premium=user_is_premium, + max_quantity=max_quantity, + request_name=request_name, + request_username=request_username, + request_photo=request_photo, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/labeled_price.py b/env/Lib/site-packages/aiogram/types/labeled_price.py new file mode 100644 index 0000000..42d97af --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/labeled_price.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import MutableTelegramObject + + +class LabeledPrice(MutableTelegramObject): + """ + This object represents a portion of the price for goods or services. + + Source: https://core.telegram.org/bots/api#labeledprice + """ + + label: str + """Portion label""" + amount: int + """Price of the product in the *smallest units* of the `currency `_ (integer, **not** float/double). For example, for a price of :code:`US$ 1.45` pass :code:`amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, label: str, amount: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(label=label, amount=amount, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/link_preview_options.py b/env/Lib/site-packages/aiogram/types/link_preview_options.py new file mode 100644 index 0000000..8964c5e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/link_preview_options.py @@ -0,0 +1,56 @@ +from typing import TYPE_CHECKING, Any, Optional, Union + +from ..client.default import Default +from .base import TelegramObject + + +class LinkPreviewOptions(TelegramObject): + """ + Describes the options used for link preview generation. + + Source: https://core.telegram.org/bots/api#linkpreviewoptions + """ + + is_disabled: Optional[Union[bool, Default]] = Default("link_preview_is_disabled") + """*Optional*. :code:`True`, if the link preview is disabled""" + url: Optional[str] = None + """*Optional*. URL to use for the link preview. If empty, then the first URL found in the message text will be used""" + prefer_small_media: Optional[Union[bool, Default]] = Default("link_preview_prefer_small_media") + """*Optional*. :code:`True`, if the media in the link preview is supposed to be shrunk; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview""" + prefer_large_media: Optional[Union[bool, Default]] = Default("link_preview_prefer_large_media") + """*Optional*. :code:`True`, if the media in the link preview is supposed to be enlarged; ignored if the URL isn't explicitly specified or media size change isn't supported for the preview""" + show_above_text: Optional[Union[bool, Default]] = Default("link_preview_show_above_text") + """*Optional*. :code:`True`, if the link preview must be shown above the message text; otherwise, the link preview will be shown below the message text""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + is_disabled: Optional[Union[bool, Default]] = Default("link_preview_is_disabled"), + url: Optional[str] = None, + prefer_small_media: Optional[Union[bool, Default]] = Default( + "link_preview_prefer_small_media" + ), + prefer_large_media: Optional[Union[bool, Default]] = Default( + "link_preview_prefer_large_media" + ), + show_above_text: Optional[Union[bool, Default]] = Default( + "link_preview_show_above_text" + ), + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + is_disabled=is_disabled, + url=url, + prefer_small_media=prefer_small_media, + prefer_large_media=prefer_large_media, + show_above_text=show_above_text, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/location.py b/env/Lib/site-packages/aiogram/types/location.py new file mode 100644 index 0000000..32673da --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/location.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class Location(TelegramObject): + """ + This object represents a point on the map. + + Source: https://core.telegram.org/bots/api#location + """ + + latitude: float + """Latitude as defined by the sender""" + longitude: float + """Longitude as defined by the sender""" + horizontal_accuracy: Optional[float] = None + """*Optional*. The radius of uncertainty for the location, measured in meters; 0-1500""" + live_period: Optional[int] = None + """*Optional*. Time relative to the message sending date, during which the location can be updated; in seconds. For active live locations only.""" + heading: Optional[int] = None + """*Optional*. The direction in which user is moving, in degrees; 1-360. For active live locations only.""" + proximity_alert_radius: Optional[int] = None + """*Optional*. The maximum distance for proximity alerts about approaching another chat member, in meters. For sent live locations only.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + latitude: float, + longitude: float, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + latitude=latitude, + longitude=longitude, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/login_url.py b/env/Lib/site-packages/aiogram/types/login_url.py new file mode 100644 index 0000000..6f6c94a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/login_url.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class LoginUrl(TelegramObject): + """ + This object represents a parameter of the inline keyboard button used to automatically authorize a user. Serves as a great replacement for the `Telegram Login Widget `_ when the user is coming from Telegram. All the user needs to do is tap/click a button and confirm that they want to log in: + Telegram apps support these buttons as of `version 5.7 `_. + + Sample bot: `@discussbot `_ + + Source: https://core.telegram.org/bots/api#loginurl + """ + + url: str + """An HTTPS URL to be opened with user authorization data added to the query string when the button is pressed. If the user refuses to provide authorization data, the original URL without information about the user will be opened. The data added is the same as described in `Receiving authorization data `_.""" + forward_text: Optional[str] = None + """*Optional*. New text of the button in forwarded messages.""" + bot_username: Optional[str] = None + """*Optional*. Username of a bot, which will be used for user authorization. See `Setting up a bot `_ for more details. If not specified, the current bot's username will be assumed. The *url*'s domain must be the same as the domain linked with the bot. See `Linking your domain to the bot `_ for more details.""" + request_write_access: Optional[bool] = None + """*Optional*. Pass :code:`True` to request the permission for your bot to send messages to the user.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + url: str, + forward_text: Optional[str] = None, + bot_username: Optional[str] = None, + request_write_access: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + url=url, + forward_text=forward_text, + bot_username=bot_username, + request_write_access=request_write_access, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/mask_position.py b/env/Lib/site-packages/aiogram/types/mask_position.py new file mode 100644 index 0000000..d02852a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/mask_position.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class MaskPosition(TelegramObject): + """ + This object describes the position on faces where a mask should be placed by default. + + Source: https://core.telegram.org/bots/api#maskposition + """ + + point: str + """The part of the face relative to which the mask should be placed. One of 'forehead', 'eyes', 'mouth', or 'chin'.""" + x_shift: float + """Shift by X-axis measured in widths of the mask scaled to the face size, from left to right. For example, choosing -1.0 will place mask just to the left of the default mask position.""" + y_shift: float + """Shift by Y-axis measured in heights of the mask scaled to the face size, from top to bottom. For example, 1.0 will place the mask just below the default mask position.""" + scale: float + """Mask scaling coefficient. For example, 2.0 means double size.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + point: str, + x_shift: float, + y_shift: float, + scale: float, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + point=point, x_shift=x_shift, y_shift=y_shift, scale=scale, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/maybe_inaccessible_message.py b/env/Lib/site-packages/aiogram/types/maybe_inaccessible_message.py new file mode 100644 index 0000000..fe95ced --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/maybe_inaccessible_message.py @@ -0,0 +1,12 @@ +from aiogram.types import TelegramObject + + +class MaybeInaccessibleMessage(TelegramObject): + """ + This object describes a message that can be inaccessible to the bot. It can be one of + + - :class:`aiogram.types.message.Message` + - :class:`aiogram.types.inaccessible_message.InaccessibleMessage` + + Source: https://core.telegram.org/bots/api#maybeinaccessiblemessage + """ diff --git a/env/Lib/site-packages/aiogram/types/menu_button.py b/env/Lib/site-packages/aiogram/types/menu_button.py new file mode 100644 index 0000000..4c4fbf3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/menu_button.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import MutableTelegramObject + +if TYPE_CHECKING: + from .web_app_info import WebAppInfo + + +class MenuButton(MutableTelegramObject): + """ + This object describes the bot's menu button in a private chat. It should be one of + + - :class:`aiogram.types.menu_button_commands.MenuButtonCommands` + - :class:`aiogram.types.menu_button_web_app.MenuButtonWebApp` + - :class:`aiogram.types.menu_button_default.MenuButtonDefault` + + If a menu button other than :class:`aiogram.types.menu_button_default.MenuButtonDefault` is set for a private chat, then it is applied in the chat. Otherwise the default menu button is applied. By default, the menu button opens the list of bot commands. + + Source: https://core.telegram.org/bots/api#menubutton + """ + + type: str + """Type of the button""" + text: Optional[str] = None + """*Optional*. Text on the button""" + web_app: Optional[WebAppInfo] = None + """*Optional*. Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method :class:`aiogram.methods.answer_web_app_query.AnswerWebAppQuery`. Alternatively, a :code:`t.me` link to a Web App of the bot can be specified in the object instead of the Web App's URL, in which case the Web App will be opened as if the user pressed the link.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: str, + text: Optional[str] = None, + web_app: Optional[WebAppInfo] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, text=text, web_app=web_app, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/menu_button_commands.py b/env/Lib/site-packages/aiogram/types/menu_button_commands.py new file mode 100644 index 0000000..54ed20b --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/menu_button_commands.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import MenuButtonType +from .menu_button import MenuButton + + +class MenuButtonCommands(MenuButton): + """ + Represents a menu button, which opens the bot's list of commands. + + Source: https://core.telegram.org/bots/api#menubuttoncommands + """ + + type: Literal[MenuButtonType.COMMANDS] = MenuButtonType.COMMANDS + """Type of the button, must be *commands*""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[MenuButtonType.COMMANDS] = MenuButtonType.COMMANDS, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/menu_button_default.py b/env/Lib/site-packages/aiogram/types/menu_button_default.py new file mode 100644 index 0000000..12ce30e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/menu_button_default.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import MenuButtonType +from .menu_button import MenuButton + + +class MenuButtonDefault(MenuButton): + """ + Describes that no specific value for the menu button was set. + + Source: https://core.telegram.org/bots/api#menubuttondefault + """ + + type: Literal[MenuButtonType.DEFAULT] = MenuButtonType.DEFAULT + """Type of the button, must be *default*""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[MenuButtonType.DEFAULT] = MenuButtonType.DEFAULT, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/menu_button_web_app.py b/env/Lib/site-packages/aiogram/types/menu_button_web_app.py new file mode 100644 index 0000000..0fc9e41 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/menu_button_web_app.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import MenuButtonType +from .menu_button import MenuButton + +if TYPE_CHECKING: + from .web_app_info import WebAppInfo + + +class MenuButtonWebApp(MenuButton): + """ + Represents a menu button, which launches a `Web App `_. + + Source: https://core.telegram.org/bots/api#menubuttonwebapp + """ + + type: Literal[MenuButtonType.WEB_APP] = MenuButtonType.WEB_APP + """Type of the button, must be *web_app*""" + text: str + """Text on the button""" + web_app: WebAppInfo + """Description of the Web App that will be launched when the user presses the button. The Web App will be able to send an arbitrary message on behalf of the user using the method :class:`aiogram.methods.answer_web_app_query.AnswerWebAppQuery`. Alternatively, a :code:`t.me` link to a Web App of the bot can be specified in the object instead of the Web App's URL, in which case the Web App will be opened as if the user pressed the link.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[MenuButtonType.WEB_APP] = MenuButtonType.WEB_APP, + text: str, + web_app: WebAppInfo, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, text=text, web_app=web_app, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/message.py b/env/Lib/site-packages/aiogram/types/message.py new file mode 100644 index 0000000..57defef --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message.py @@ -0,0 +1,4229 @@ +from __future__ import annotations + +import datetime +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union + +from pydantic import Field + +from aiogram.utils.text_decorations import ( + TextDecoration, + html_decoration, + markdown_decoration, +) + +from ..client.default import Default +from ..enums import ContentType +from .custom import DateTime +from .maybe_inaccessible_message import MaybeInaccessibleMessage +from .reply_parameters import ReplyParameters + +if TYPE_CHECKING: + from ..methods import ( + CopyMessage, + DeleteMessage, + EditMessageCaption, + EditMessageLiveLocation, + EditMessageMedia, + EditMessageReplyMarkup, + EditMessageText, + ForwardMessage, + PinChatMessage, + SendAnimation, + SendAudio, + SendContact, + SendDice, + SendDocument, + SendGame, + SendInvoice, + SendLocation, + SendMediaGroup, + SendMessage, + SendPaidMedia, + SendPhoto, + SendPoll, + SendSticker, + SendVenue, + SendVideo, + SendVideoNote, + SendVoice, + SetMessageReaction, + StopMessageLiveLocation, + UnpinChatMessage, + ) + from .animation import Animation + from .audio import Audio + from .chat import Chat + from .chat_background import ChatBackground + from .chat_boost_added import ChatBoostAdded + from .chat_shared import ChatShared + from .contact import Contact + from .dice import Dice + from .document import Document + from .external_reply_info import ExternalReplyInfo + from .force_reply import ForceReply + from .forum_topic_closed import ForumTopicClosed + from .forum_topic_created import ForumTopicCreated + from .forum_topic_edited import ForumTopicEdited + from .forum_topic_reopened import ForumTopicReopened + from .game import Game + from .general_forum_topic_hidden import GeneralForumTopicHidden + from .general_forum_topic_unhidden import GeneralForumTopicUnhidden + from .giveaway import Giveaway + from .giveaway_completed import GiveawayCompleted + from .giveaway_created import GiveawayCreated + from .giveaway_winners import GiveawayWinners + from .inaccessible_message import InaccessibleMessage + from .inline_keyboard_markup import InlineKeyboardMarkup + from .input_file import InputFile + from .input_media_animation import InputMediaAnimation + from .input_media_audio import InputMediaAudio + from .input_media_document import InputMediaDocument + from .input_media_photo import InputMediaPhoto + from .input_media_video import InputMediaVideo + from .input_paid_media_photo import InputPaidMediaPhoto + from .input_paid_media_video import InputPaidMediaVideo + from .input_poll_option import InputPollOption + from .invoice import Invoice + from .labeled_price import LabeledPrice + from .link_preview_options import LinkPreviewOptions + from .location import Location + from .message_auto_delete_timer_changed import MessageAutoDeleteTimerChanged + from .message_entity import MessageEntity + from .message_origin_channel import MessageOriginChannel + from .message_origin_chat import MessageOriginChat + from .message_origin_hidden_user import MessageOriginHiddenUser + from .message_origin_user import MessageOriginUser + from .paid_media_info import PaidMediaInfo + from .passport_data import PassportData + from .photo_size import PhotoSize + from .poll import Poll + from .proximity_alert_triggered import ProximityAlertTriggered + from .reaction_type_custom_emoji import ReactionTypeCustomEmoji + from .reaction_type_emoji import ReactionTypeEmoji + from .reaction_type_paid import ReactionTypePaid + from .refunded_payment import RefundedPayment + from .reply_keyboard_markup import ReplyKeyboardMarkup + from .reply_keyboard_remove import ReplyKeyboardRemove + from .sticker import Sticker + from .story import Story + from .successful_payment import SuccessfulPayment + from .text_quote import TextQuote + from .user import User + from .user_shared import UserShared + from .users_shared import UsersShared + from .venue import Venue + from .video import Video + from .video_chat_ended import VideoChatEnded + from .video_chat_participants_invited import VideoChatParticipantsInvited + from .video_chat_scheduled import VideoChatScheduled + from .video_chat_started import VideoChatStarted + from .video_note import VideoNote + from .voice import Voice + from .web_app_data import WebAppData + from .write_access_allowed import WriteAccessAllowed + + +class Message(MaybeInaccessibleMessage): + """ + This object represents a message. + + Source: https://core.telegram.org/bots/api#message + """ + + message_id: int + """Unique message identifier inside this chat""" + date: DateTime + """Date the message was sent in Unix time. It is always a positive number, representing a valid date.""" + chat: Chat + """Chat the message belongs to""" + message_thread_id: Optional[int] = None + """*Optional*. Unique identifier of a message thread to which the message belongs; for supergroups only""" + from_user: Optional[User] = Field(None, alias="from") + """*Optional*. Sender of the message; may be empty for messages sent to channels. For backward compatibility, if the message was sent on behalf of a chat, the field contains a fake sender user in non-channel chats""" + sender_chat: Optional[Chat] = None + """*Optional*. Sender of the message when sent on behalf of a chat. For example, the supergroup itself for messages sent by its anonymous administrators or a linked channel for messages automatically forwarded to the channel's discussion group. For backward compatibility, if the message was sent on behalf of a chat, the field *from* contains a fake sender user in non-channel chats.""" + sender_boost_count: Optional[int] = None + """*Optional*. If the sender of the message boosted the chat, the number of boosts added by the user""" + sender_business_bot: Optional[User] = None + """*Optional*. The bot that actually sent the message on behalf of the business account. Available only for outgoing messages sent on behalf of the connected business account.""" + business_connection_id: Optional[str] = None + """*Optional*. Unique identifier of the business connection from which the message was received. If non-empty, the message belongs to a chat of the corresponding business account that is independent from any potential bot chat which might share the same identifier.""" + forward_origin: Optional[ + Union[MessageOriginUser, MessageOriginHiddenUser, MessageOriginChat, MessageOriginChannel] + ] = None + """*Optional*. Information about the original message for forwarded messages""" + is_topic_message: Optional[bool] = None + """*Optional*. :code:`True`, if the message is sent to a forum topic""" + is_automatic_forward: Optional[bool] = None + """*Optional*. :code:`True`, if the message is a channel post that was automatically forwarded to the connected discussion group""" + reply_to_message: Optional[Message] = None + """*Optional*. For replies in the same chat and message thread, the original message. Note that the Message object in this field will not contain further *reply_to_message* fields even if it itself is a reply.""" + external_reply: Optional[ExternalReplyInfo] = None + """*Optional*. Information about the message that is being replied to, which may come from another chat or forum topic""" + quote: Optional[TextQuote] = None + """*Optional*. For replies that quote part of the original message, the quoted part of the message""" + reply_to_story: Optional[Story] = None + """*Optional*. For replies to a story, the original story""" + via_bot: Optional[User] = None + """*Optional*. Bot through which the message was sent""" + edit_date: Optional[int] = None + """*Optional*. Date the message was last edited in Unix time""" + has_protected_content: Optional[bool] = None + """*Optional*. :code:`True`, if the message can't be forwarded""" + is_from_offline: Optional[bool] = None + """*Optional*. True, if the message was sent by an implicit action, for example, as an away or a greeting business message, or as a scheduled message""" + media_group_id: Optional[str] = None + """*Optional*. The unique identifier of a media message group this message belongs to""" + author_signature: Optional[str] = None + """*Optional*. Signature of the post author for messages in channels, or the custom title of an anonymous group administrator""" + text: Optional[str] = None + """*Optional*. For text messages, the actual UTF-8 text of the message""" + entities: Optional[List[MessageEntity]] = None + """*Optional*. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text""" + link_preview_options: Optional[LinkPreviewOptions] = None + """*Optional*. Options used for link preview generation for the message, if it is a text message and link preview options were changed""" + effect_id: Optional[str] = None + """*Optional*. Unique identifier of the message effect added to the message""" + animation: Optional[Animation] = None + """*Optional*. Message is an animation, information about the animation. For backward compatibility, when this field is set, the *document* field will also be set""" + audio: Optional[Audio] = None + """*Optional*. Message is an audio file, information about the file""" + document: Optional[Document] = None + """*Optional*. Message is a general file, information about the file""" + paid_media: Optional[PaidMediaInfo] = None + """*Optional*. Message contains paid media; information about the paid media""" + photo: Optional[List[PhotoSize]] = None + """*Optional*. Message is a photo, available sizes of the photo""" + sticker: Optional[Sticker] = None + """*Optional*. Message is a sticker, information about the sticker""" + story: Optional[Story] = None + """*Optional*. Message is a forwarded story""" + video: Optional[Video] = None + """*Optional*. Message is a video, information about the video""" + video_note: Optional[VideoNote] = None + """*Optional*. Message is a `video note `_, information about the video message""" + voice: Optional[Voice] = None + """*Optional*. Message is a voice message, information about the file""" + caption: Optional[str] = None + """*Optional*. Caption for the animation, audio, document, paid media, photo, video or voice""" + caption_entities: Optional[List[MessageEntity]] = None + """*Optional*. For messages with a caption, special entities like usernames, URLs, bot commands, etc. that appear in the caption""" + show_caption_above_media: Optional[bool] = None + """*Optional*. True, if the caption must be shown above the message media""" + has_media_spoiler: Optional[bool] = None + """*Optional*. :code:`True`, if the message media is covered by a spoiler animation""" + contact: Optional[Contact] = None + """*Optional*. Message is a shared contact, information about the contact""" + dice: Optional[Dice] = None + """*Optional*. Message is a dice with random value""" + game: Optional[Game] = None + """*Optional*. Message is a game, information about the game. `More about games » `_""" + poll: Optional[Poll] = None + """*Optional*. Message is a native poll, information about the poll""" + venue: Optional[Venue] = None + """*Optional*. Message is a venue, information about the venue. For backward compatibility, when this field is set, the *location* field will also be set""" + location: Optional[Location] = None + """*Optional*. Message is a shared location, information about the location""" + new_chat_members: Optional[List[User]] = None + """*Optional*. New members that were added to the group or supergroup and information about them (the bot itself may be one of these members)""" + left_chat_member: Optional[User] = None + """*Optional*. A member was removed from the group, information about them (this member may be the bot itself)""" + new_chat_title: Optional[str] = None + """*Optional*. A chat title was changed to this value""" + new_chat_photo: Optional[List[PhotoSize]] = None + """*Optional*. A chat photo was change to this value""" + delete_chat_photo: Optional[bool] = None + """*Optional*. Service message: the chat photo was deleted""" + group_chat_created: Optional[bool] = None + """*Optional*. Service message: the group has been created""" + supergroup_chat_created: Optional[bool] = None + """*Optional*. Service message: the supergroup has been created. This field can't be received in a message coming through updates, because bot can't be a member of a supergroup when it is created. It can only be found in reply_to_message if someone replies to a very first message in a directly created supergroup.""" + channel_chat_created: Optional[bool] = None + """*Optional*. Service message: the channel has been created. This field can't be received in a message coming through updates, because bot can't be a member of a channel when it is created. It can only be found in reply_to_message if someone replies to a very first message in a channel.""" + message_auto_delete_timer_changed: Optional[MessageAutoDeleteTimerChanged] = None + """*Optional*. Service message: auto-delete timer settings changed in the chat""" + migrate_to_chat_id: Optional[int] = None + """*Optional*. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.""" + migrate_from_chat_id: Optional[int] = None + """*Optional*. The supergroup has been migrated from a group with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.""" + pinned_message: Optional[Union[Message, InaccessibleMessage]] = None + """*Optional*. Specified message was pinned. Note that the Message object in this field will not contain further *reply_to_message* fields even if it itself is a reply.""" + invoice: Optional[Invoice] = None + """*Optional*. Message is an invoice for a `payment `_, information about the invoice. `More about payments » `_""" + successful_payment: Optional[SuccessfulPayment] = None + """*Optional*. Message is a service message about a successful payment, information about the payment. `More about payments » `_""" + refunded_payment: Optional[RefundedPayment] = None + """*Optional*. Message is a service message about a refunded payment, information about the payment. `More about payments » `_""" + users_shared: Optional[UsersShared] = None + """*Optional*. Service message: users were shared with the bot""" + chat_shared: Optional[ChatShared] = None + """*Optional*. Service message: a chat was shared with the bot""" + connected_website: Optional[str] = None + """*Optional*. The domain name of the website on which the user has logged in. `More about Telegram Login » `_""" + write_access_allowed: Optional[WriteAccessAllowed] = None + """*Optional*. Service message: the user allowed the bot to write messages after adding it to the attachment or side menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method `requestWriteAccess `_""" + passport_data: Optional[PassportData] = None + """*Optional*. Telegram Passport data""" + proximity_alert_triggered: Optional[ProximityAlertTriggered] = None + """*Optional*. Service message. A user in the chat triggered another user's proximity alert while sharing Live Location.""" + boost_added: Optional[ChatBoostAdded] = None + """*Optional*. Service message: user boosted the chat""" + chat_background_set: Optional[ChatBackground] = None + """*Optional*. Service message: chat background set""" + forum_topic_created: Optional[ForumTopicCreated] = None + """*Optional*. Service message: forum topic created""" + forum_topic_edited: Optional[ForumTopicEdited] = None + """*Optional*. Service message: forum topic edited""" + forum_topic_closed: Optional[ForumTopicClosed] = None + """*Optional*. Service message: forum topic closed""" + forum_topic_reopened: Optional[ForumTopicReopened] = None + """*Optional*. Service message: forum topic reopened""" + general_forum_topic_hidden: Optional[GeneralForumTopicHidden] = None + """*Optional*. Service message: the 'General' forum topic hidden""" + general_forum_topic_unhidden: Optional[GeneralForumTopicUnhidden] = None + """*Optional*. Service message: the 'General' forum topic unhidden""" + giveaway_created: Optional[GiveawayCreated] = None + """*Optional*. Service message: a scheduled giveaway was created""" + giveaway: Optional[Giveaway] = None + """*Optional*. The message is a scheduled giveaway message""" + giveaway_winners: Optional[GiveawayWinners] = None + """*Optional*. A giveaway with public winners was completed""" + giveaway_completed: Optional[GiveawayCompleted] = None + """*Optional*. Service message: a giveaway without public winners was completed""" + video_chat_scheduled: Optional[VideoChatScheduled] = None + """*Optional*. Service message: video chat scheduled""" + video_chat_started: Optional[VideoChatStarted] = None + """*Optional*. Service message: video chat started""" + video_chat_ended: Optional[VideoChatEnded] = None + """*Optional*. Service message: video chat ended""" + video_chat_participants_invited: Optional[VideoChatParticipantsInvited] = None + """*Optional*. Service message: new participants invited to a video chat""" + web_app_data: Optional[WebAppData] = None + """*Optional*. Service message: data sent by a Web App""" + reply_markup: Optional[InlineKeyboardMarkup] = None + """*Optional*. Inline keyboard attached to the message. :code:`login_url` buttons are represented as ordinary :code:`url` buttons.""" + forward_date: Optional[DateTime] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For forwarded messages, date the original message was sent in Unix time + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + forward_from: Optional[User] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For forwarded messages, sender of the original message + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + forward_from_chat: Optional[Chat] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For messages forwarded from channels or from anonymous administrators, information about the original sender chat + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + forward_from_message_id: Optional[int] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For messages forwarded from channels, identifier of the original message in the channel + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + forward_sender_name: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Sender's name for messages forwarded from users who disallow adding a link to their account in forwarded messages + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + forward_signature: Optional[str] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. For forwarded messages that were originally sent in channels or by an anonymous chat administrator, signature of the message sender if present + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + user_shared: Optional[UserShared] = Field(None, json_schema_extra={"deprecated": True}) + """*Optional*. Service message: a user was shared with the bot + +.. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + message_id: int, + date: DateTime, + chat: Chat, + message_thread_id: Optional[int] = None, + from_user: Optional[User] = None, + sender_chat: Optional[Chat] = None, + sender_boost_count: Optional[int] = None, + sender_business_bot: Optional[User] = None, + business_connection_id: Optional[str] = None, + forward_origin: Optional[ + Union[ + MessageOriginUser, + MessageOriginHiddenUser, + MessageOriginChat, + MessageOriginChannel, + ] + ] = None, + is_topic_message: Optional[bool] = None, + is_automatic_forward: Optional[bool] = None, + reply_to_message: Optional[Message] = None, + external_reply: Optional[ExternalReplyInfo] = None, + quote: Optional[TextQuote] = None, + reply_to_story: Optional[Story] = None, + via_bot: Optional[User] = None, + edit_date: Optional[int] = None, + has_protected_content: Optional[bool] = None, + is_from_offline: Optional[bool] = None, + media_group_id: Optional[str] = None, + author_signature: Optional[str] = None, + text: Optional[str] = None, + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[LinkPreviewOptions] = None, + effect_id: Optional[str] = None, + animation: Optional[Animation] = None, + audio: Optional[Audio] = None, + document: Optional[Document] = None, + paid_media: Optional[PaidMediaInfo] = None, + photo: Optional[List[PhotoSize]] = None, + sticker: Optional[Sticker] = None, + story: Optional[Story] = None, + video: Optional[Video] = None, + video_note: Optional[VideoNote] = None, + voice: Optional[Voice] = None, + caption: Optional[str] = None, + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[bool] = None, + has_media_spoiler: Optional[bool] = None, + contact: Optional[Contact] = None, + dice: Optional[Dice] = None, + game: Optional[Game] = None, + poll: Optional[Poll] = None, + venue: Optional[Venue] = None, + location: Optional[Location] = None, + new_chat_members: Optional[List[User]] = None, + left_chat_member: Optional[User] = None, + new_chat_title: Optional[str] = None, + new_chat_photo: Optional[List[PhotoSize]] = None, + delete_chat_photo: Optional[bool] = None, + group_chat_created: Optional[bool] = None, + supergroup_chat_created: Optional[bool] = None, + channel_chat_created: Optional[bool] = None, + message_auto_delete_timer_changed: Optional[MessageAutoDeleteTimerChanged] = None, + migrate_to_chat_id: Optional[int] = None, + migrate_from_chat_id: Optional[int] = None, + pinned_message: Optional[Union[Message, InaccessibleMessage]] = None, + invoice: Optional[Invoice] = None, + successful_payment: Optional[SuccessfulPayment] = None, + refunded_payment: Optional[RefundedPayment] = None, + users_shared: Optional[UsersShared] = None, + chat_shared: Optional[ChatShared] = None, + connected_website: Optional[str] = None, + write_access_allowed: Optional[WriteAccessAllowed] = None, + passport_data: Optional[PassportData] = None, + proximity_alert_triggered: Optional[ProximityAlertTriggered] = None, + boost_added: Optional[ChatBoostAdded] = None, + chat_background_set: Optional[ChatBackground] = None, + forum_topic_created: Optional[ForumTopicCreated] = None, + forum_topic_edited: Optional[ForumTopicEdited] = None, + forum_topic_closed: Optional[ForumTopicClosed] = None, + forum_topic_reopened: Optional[ForumTopicReopened] = None, + general_forum_topic_hidden: Optional[GeneralForumTopicHidden] = None, + general_forum_topic_unhidden: Optional[GeneralForumTopicUnhidden] = None, + giveaway_created: Optional[GiveawayCreated] = None, + giveaway: Optional[Giveaway] = None, + giveaway_winners: Optional[GiveawayWinners] = None, + giveaway_completed: Optional[GiveawayCompleted] = None, + video_chat_scheduled: Optional[VideoChatScheduled] = None, + video_chat_started: Optional[VideoChatStarted] = None, + video_chat_ended: Optional[VideoChatEnded] = None, + video_chat_participants_invited: Optional[VideoChatParticipantsInvited] = None, + web_app_data: Optional[WebAppData] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + forward_date: Optional[DateTime] = None, + forward_from: Optional[User] = None, + forward_from_chat: Optional[Chat] = None, + forward_from_message_id: Optional[int] = None, + forward_sender_name: Optional[str] = None, + forward_signature: Optional[str] = None, + user_shared: Optional[UserShared] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + message_id=message_id, + date=date, + chat=chat, + message_thread_id=message_thread_id, + from_user=from_user, + sender_chat=sender_chat, + sender_boost_count=sender_boost_count, + sender_business_bot=sender_business_bot, + business_connection_id=business_connection_id, + forward_origin=forward_origin, + is_topic_message=is_topic_message, + is_automatic_forward=is_automatic_forward, + reply_to_message=reply_to_message, + external_reply=external_reply, + quote=quote, + reply_to_story=reply_to_story, + via_bot=via_bot, + edit_date=edit_date, + has_protected_content=has_protected_content, + is_from_offline=is_from_offline, + media_group_id=media_group_id, + author_signature=author_signature, + text=text, + entities=entities, + link_preview_options=link_preview_options, + effect_id=effect_id, + animation=animation, + audio=audio, + document=document, + paid_media=paid_media, + photo=photo, + sticker=sticker, + story=story, + video=video, + video_note=video_note, + voice=voice, + caption=caption, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_media_spoiler=has_media_spoiler, + contact=contact, + dice=dice, + game=game, + poll=poll, + venue=venue, + location=location, + new_chat_members=new_chat_members, + left_chat_member=left_chat_member, + new_chat_title=new_chat_title, + new_chat_photo=new_chat_photo, + delete_chat_photo=delete_chat_photo, + group_chat_created=group_chat_created, + supergroup_chat_created=supergroup_chat_created, + channel_chat_created=channel_chat_created, + message_auto_delete_timer_changed=message_auto_delete_timer_changed, + migrate_to_chat_id=migrate_to_chat_id, + migrate_from_chat_id=migrate_from_chat_id, + pinned_message=pinned_message, + invoice=invoice, + successful_payment=successful_payment, + refunded_payment=refunded_payment, + users_shared=users_shared, + chat_shared=chat_shared, + connected_website=connected_website, + write_access_allowed=write_access_allowed, + passport_data=passport_data, + proximity_alert_triggered=proximity_alert_triggered, + boost_added=boost_added, + chat_background_set=chat_background_set, + forum_topic_created=forum_topic_created, + forum_topic_edited=forum_topic_edited, + forum_topic_closed=forum_topic_closed, + forum_topic_reopened=forum_topic_reopened, + general_forum_topic_hidden=general_forum_topic_hidden, + general_forum_topic_unhidden=general_forum_topic_unhidden, + giveaway_created=giveaway_created, + giveaway=giveaway, + giveaway_winners=giveaway_winners, + giveaway_completed=giveaway_completed, + video_chat_scheduled=video_chat_scheduled, + video_chat_started=video_chat_started, + video_chat_ended=video_chat_ended, + video_chat_participants_invited=video_chat_participants_invited, + web_app_data=web_app_data, + reply_markup=reply_markup, + forward_date=forward_date, + forward_from=forward_from, + forward_from_chat=forward_from_chat, + forward_from_message_id=forward_from_message_id, + forward_sender_name=forward_sender_name, + forward_signature=forward_signature, + user_shared=user_shared, + **__pydantic_kwargs, + ) + + @property + def content_type(self) -> str: + if self.text: + return ContentType.TEXT + if self.audio: + return ContentType.AUDIO + if self.animation: + return ContentType.ANIMATION + if self.document: + return ContentType.DOCUMENT + if self.game: + return ContentType.GAME + if self.photo: + return ContentType.PHOTO + if self.sticker: + return ContentType.STICKER + if self.video: + return ContentType.VIDEO + if self.video_note: + return ContentType.VIDEO_NOTE + if self.voice: + return ContentType.VOICE + if self.contact: + return ContentType.CONTACT + if self.venue: + return ContentType.VENUE + if self.location: + return ContentType.LOCATION + if self.new_chat_members: + return ContentType.NEW_CHAT_MEMBERS + if self.left_chat_member: + return ContentType.LEFT_CHAT_MEMBER + if self.invoice: + return ContentType.INVOICE + if self.successful_payment: + return ContentType.SUCCESSFUL_PAYMENT + if self.users_shared: + return ContentType.USERS_SHARED + if self.connected_website: + return ContentType.CONNECTED_WEBSITE + if self.migrate_from_chat_id: + return ContentType.MIGRATE_FROM_CHAT_ID + if self.migrate_to_chat_id: + return ContentType.MIGRATE_TO_CHAT_ID + if self.pinned_message: + return ContentType.PINNED_MESSAGE + if self.new_chat_title: + return ContentType.NEW_CHAT_TITLE + if self.new_chat_photo: + return ContentType.NEW_CHAT_PHOTO + if self.delete_chat_photo: + return ContentType.DELETE_CHAT_PHOTO + if self.group_chat_created: + return ContentType.GROUP_CHAT_CREATED + if self.supergroup_chat_created: + return ContentType.SUPERGROUP_CHAT_CREATED + if self.channel_chat_created: + return ContentType.CHANNEL_CHAT_CREATED + if self.paid_media: + return ContentType.PAID_MEDIA + if self.passport_data: + return ContentType.PASSPORT_DATA + if self.proximity_alert_triggered: + return ContentType.PROXIMITY_ALERT_TRIGGERED + if self.poll: + return ContentType.POLL + if self.dice: + return ContentType.DICE + if self.message_auto_delete_timer_changed: + return ContentType.MESSAGE_AUTO_DELETE_TIMER_CHANGED + if self.forum_topic_created: + return ContentType.FORUM_TOPIC_CREATED + if self.forum_topic_edited: + return ContentType.FORUM_TOPIC_EDITED + if self.forum_topic_closed: + return ContentType.FORUM_TOPIC_CLOSED + if self.forum_topic_reopened: + return ContentType.FORUM_TOPIC_REOPENED + if self.general_forum_topic_hidden: + return ContentType.GENERAL_FORUM_TOPIC_HIDDEN + if self.general_forum_topic_unhidden: + return ContentType.GENERAL_FORUM_TOPIC_UNHIDDEN + if self.giveaway_created: + return ContentType.GIVEAWAY_CREATED + if self.giveaway: + return ContentType.GIVEAWAY + if self.giveaway_completed: + return ContentType.GIVEAWAY_COMPLETED + if self.giveaway_winners: + return ContentType.GIVEAWAY_WINNERS + if self.video_chat_scheduled: + return ContentType.VIDEO_CHAT_SCHEDULED + if self.video_chat_started: + return ContentType.VIDEO_CHAT_STARTED + if self.video_chat_ended: + return ContentType.VIDEO_CHAT_ENDED + if self.video_chat_participants_invited: + return ContentType.VIDEO_CHAT_PARTICIPANTS_INVITED + if self.web_app_data: + return ContentType.WEB_APP_DATA + if self.user_shared: + return ContentType.USER_SHARED + if self.chat_shared: + return ContentType.CHAT_SHARED + if self.story: + return ContentType.STORY + if self.write_access_allowed: + return ContentType.WRITE_ACCESS_ALLOWED + if self.chat_background_set: + return ContentType.CHAT_BACKGROUND_SET + if self.boost_added: + return ContentType.BOOST_ADDED + if self.refunded_payment: + return ContentType.REFUNDED_PAYMENT + + return ContentType.UNKNOWN + + def _unparse_entities(self, text_decoration: TextDecoration) -> str: + text = self.text or self.caption or "" + entities = self.entities or self.caption_entities or [] + return text_decoration.unparse(text=text, entities=entities) + + @property + def html_text(self) -> str: + return self._unparse_entities(html_decoration) + + @property + def md_text(self) -> str: + return self._unparse_entities(markdown_decoration) + + def as_reply_parameters( + self, + allow_sending_without_reply: Optional[Union[bool, Default]] = Default( + "allow_sending_without_reply" + ), + quote: Optional[str] = None, + quote_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + quote_entities: Optional[List[MessageEntity]] = None, + quote_position: Optional[int] = None, + ) -> ReplyParameters: + return ReplyParameters( + message_id=self.message_id, + chat_id=self.chat.id, + allow_sending_without_reply=allow_sending_without_reply, + quote=quote, + quote_parse_mode=quote_parse_mode, + quote_entities=quote_entities, + quote_position=quote_position, + ) + + def reply_animation( + self, + animation: Union[InputFile, str], + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendAnimation: + """ + Shortcut for method :class:`aiogram.methods.send_animation.SendAnimation` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendanimation + + :param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. :ref:`More information on Sending Files » ` + :param duration: Duration of sent animation in seconds + :param width: Animation width + :param height: Animation height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Animation caption (may also be used when resending animation by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the animation caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the animation needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_animation.SendAnimation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAnimation + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendAnimation( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + animation=animation, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_animation( + self, + animation: Union[InputFile, str], + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendAnimation: + """ + Shortcut for method :class:`aiogram.methods.send_animation.SendAnimation` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send animation files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendanimation + + :param animation: Animation to send. Pass a file_id as String to send an animation that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an animation from the Internet, or upload a new animation using multipart/form-data. :ref:`More information on Sending Files » ` + :param duration: Duration of sent animation in seconds + :param width: Animation width + :param height: Animation height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Animation caption (may also be used when resending animation by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the animation caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the animation needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_animation.SendAnimation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAnimation + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendAnimation( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + animation=animation, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_audio( + self, + audio: Union[InputFile, str], + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendAudio: + """ + Shortcut for method :class:`aiogram.methods.send_audio.SendAudio` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + For sending voice messages, use the :class:`aiogram.methods.send_voice.SendVoice` method instead. + + Source: https://core.telegram.org/bots/api#sendaudio + + :param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param caption: Audio caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the audio caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the audio in seconds + :param performer: Performer + :param title: Track name + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_audio.SendAudio` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAudio + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendAudio( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + audio=audio, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_audio( + self, + audio: Union[InputFile, str], + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendAudio: + """ + Shortcut for method :class:`aiogram.methods.send_audio.SendAudio` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send audio files, if you want Telegram clients to display them in the music player. Your audio must be in the .MP3 or .M4A format. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future. + For sending voice messages, use the :class:`aiogram.methods.send_voice.SendVoice` method instead. + + Source: https://core.telegram.org/bots/api#sendaudio + + :param audio: Audio file to send. Pass a file_id as String to send an audio file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get an audio file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param caption: Audio caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the audio caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the audio in seconds + :param performer: Performer + :param title: Track name + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_audio.SendAudio` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendAudio + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendAudio( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + audio=audio, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_contact( + self, + phone_number: str, + first_name: str, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendContact: + """ + Shortcut for method :class:`aiogram.methods.send_contact.SendContact` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send phone contacts. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendcontact + + :param phone_number: Contact's phone number + :param first_name: Contact's first name + :param last_name: Contact's last name + :param vcard: Additional data about the contact in the form of a `vCard `_, 0-2048 bytes + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_contact.SendContact` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendContact + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendContact( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + phone_number=phone_number, + first_name=first_name, + last_name=last_name, + vcard=vcard, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_contact( + self, + phone_number: str, + first_name: str, + last_name: Optional[str] = None, + vcard: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendContact: + """ + Shortcut for method :class:`aiogram.methods.send_contact.SendContact` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send phone contacts. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendcontact + + :param phone_number: Contact's phone number + :param first_name: Contact's first name + :param last_name: Contact's last name + :param vcard: Additional data about the contact in the form of a `vCard `_, 0-2048 bytes + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_contact.SendContact` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendContact + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendContact( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + phone_number=phone_number, + first_name=first_name, + last_name=last_name, + vcard=vcard, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_document( + self, + document: Union[InputFile, str], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendDocument: + """ + Shortcut for method :class:`aiogram.methods.send_document.SendDocument` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send general files. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#senddocument + + :param document: File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Document caption (may also be used when resending documents by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the document caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_document.SendDocument` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDocument + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendDocument( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + document=document, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_document( + self, + document: Union[InputFile, str], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendDocument: + """ + Shortcut for method :class:`aiogram.methods.send_document.SendDocument` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send general files. On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send files of any type of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#senddocument + + :param document: File to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Document caption (may also be used when resending documents by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the document caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param disable_content_type_detection: Disables automatic server-side content type detection for files uploaded using multipart/form-data + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_document.SendDocument` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDocument + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendDocument( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + document=document, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_game( + self, + game_short_name: str, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendGame: + """ + Shortcut for method :class:`aiogram.methods.send_game.SendGame` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send a game. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendgame + + :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via `@BotFather `_. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_game.SendGame` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendGame + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendGame( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + game_short_name=game_short_name, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_game( + self, + game_short_name: str, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendGame: + """ + Shortcut for method :class:`aiogram.methods.send_game.SendGame` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send a game. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendgame + + :param game_short_name: Short name of the game, serves as the unique identifier for the game. Set up your games via `@BotFather `_. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Play game_title' button will be shown. If not empty, the first button must launch the game. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_game.SendGame` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendGame + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendGame( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + game_short_name=game_short_name, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_invoice( + self, + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + start_parameter: Optional[str] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendInvoice: + """ + Shortcut for method :class:`aiogram.methods.send_invoice.SendInvoice` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send invoices. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendinvoice + + :param title: Product name, 1-32 characters + :param description: Product description, 1-255 characters + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param currency: Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_. + :param prices: Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_. + :param provider_token: Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_. + :param max_tip_amount: The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_. + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*. + :param start_parameter: Unique deep-linking parameter. If left empty, **forwarded copies** of the sent message will have a *Pay* button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a *URL* button with a deep link to the bot (instead of a *Pay* button), with the value used as the start parameter + :param provider_data: JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size in bytes + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_phone_number: Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_email: Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_shipping_address: Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_. + :param send_phone_number_to_provider: Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param send_email_to_provider: Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param is_flexible: Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Pay :code:`total price`' button will be shown. If not empty, the first button must be a Pay button. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_invoice.SendInvoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendInvoice + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendInvoice( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + start_parameter=start_parameter, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_invoice( + self, + title: str, + description: str, + payload: str, + currency: str, + prices: List[LabeledPrice], + provider_token: Optional[str] = None, + max_tip_amount: Optional[int] = None, + suggested_tip_amounts: Optional[List[int]] = None, + start_parameter: Optional[str] = None, + provider_data: Optional[str] = None, + photo_url: Optional[str] = None, + photo_size: Optional[int] = None, + photo_width: Optional[int] = None, + photo_height: Optional[int] = None, + need_name: Optional[bool] = None, + need_phone_number: Optional[bool] = None, + need_email: Optional[bool] = None, + need_shipping_address: Optional[bool] = None, + send_phone_number_to_provider: Optional[bool] = None, + send_email_to_provider: Optional[bool] = None, + is_flexible: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendInvoice: + """ + Shortcut for method :class:`aiogram.methods.send_invoice.SendInvoice` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send invoices. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendinvoice + + :param title: Product name, 1-32 characters + :param description: Product description, 1-255 characters + :param payload: Bot-defined invoice payload, 1-128 bytes. This will not be displayed to the user, use for your internal processes. + :param currency: Three-letter ISO 4217 currency code, see `more on currencies `_. Pass 'XTR' for payments in `Telegram Stars `_. + :param prices: Price breakdown, a JSON-serialized list of components (e.g. product price, tax, discount, delivery cost, delivery tax, bonus, etc.). Must contain exactly one item for payments in `Telegram Stars `_. + :param provider_token: Payment provider token, obtained via `@BotFather `_. Pass an empty string for payments in `Telegram Stars `_. + :param max_tip_amount: The maximum accepted amount for tips in the *smallest units* of the currency (integer, **not** float/double). For example, for a maximum tip of :code:`US$ 1.45` pass :code:`max_tip_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies). Defaults to 0. Not supported for payments in `Telegram Stars `_. + :param suggested_tip_amounts: A JSON-serialized array of suggested amounts of tips in the *smallest units* of the currency (integer, **not** float/double). At most 4 suggested tip amounts can be specified. The suggested tip amounts must be positive, passed in a strictly increased order and must not exceed *max_tip_amount*. + :param start_parameter: Unique deep-linking parameter. If left empty, **forwarded copies** of the sent message will have a *Pay* button, allowing multiple users to pay directly from the forwarded message, using the same invoice. If non-empty, forwarded copies of the sent message will have a *URL* button with a deep link to the bot (instead of a *Pay* button), with the value used as the start parameter + :param provider_data: JSON-serialized data about the invoice, which will be shared with the payment provider. A detailed description of required fields should be provided by the payment provider. + :param photo_url: URL of the product photo for the invoice. Can be a photo of the goods or a marketing image for a service. People like it better when they see what they are paying for. + :param photo_size: Photo size in bytes + :param photo_width: Photo width + :param photo_height: Photo height + :param need_name: Pass :code:`True` if you require the user's full name to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_phone_number: Pass :code:`True` if you require the user's phone number to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_email: Pass :code:`True` if you require the user's email address to complete the order. Ignored for payments in `Telegram Stars `_. + :param need_shipping_address: Pass :code:`True` if you require the user's shipping address to complete the order. Ignored for payments in `Telegram Stars `_. + :param send_phone_number_to_provider: Pass :code:`True` if the user's phone number should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param send_email_to_provider: Pass :code:`True` if the user's email address should be sent to the provider. Ignored for payments in `Telegram Stars `_. + :param is_flexible: Pass :code:`True` if the final price depends on the shipping method. Ignored for payments in `Telegram Stars `_. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. If empty, one 'Pay :code:`total price`' button will be shown. If not empty, the first button must be a Pay button. + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_invoice.SendInvoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendInvoice + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendInvoice( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + title=title, + description=description, + payload=payload, + currency=currency, + prices=prices, + provider_token=provider_token, + max_tip_amount=max_tip_amount, + suggested_tip_amounts=suggested_tip_amounts, + start_parameter=start_parameter, + provider_data=provider_data, + photo_url=photo_url, + photo_size=photo_size, + photo_width=photo_width, + photo_height=photo_height, + need_name=need_name, + need_phone_number=need_phone_number, + need_email=need_email, + need_shipping_address=need_shipping_address, + send_phone_number_to_provider=send_phone_number_to_provider, + send_email_to_provider=send_email_to_provider, + is_flexible=is_flexible, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_location( + self, + latitude: float, + longitude: float, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendLocation: + """ + Shortcut for method :class:`aiogram.methods.send_location.SendLocation` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send point on the map. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendlocation + + :param latitude: Latitude of the location + :param longitude: Longitude of the location + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :param live_period: Period in seconds during which the location will be updated (see `Live Locations `_, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + :param heading: For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :param proximity_alert_radius: For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_location.SendLocation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendLocation + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendLocation( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + latitude=latitude, + longitude=longitude, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_location( + self, + latitude: float, + longitude: float, + horizontal_accuracy: Optional[float] = None, + live_period: Optional[int] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendLocation: + """ + Shortcut for method :class:`aiogram.methods.send_location.SendLocation` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send point on the map. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendlocation + + :param latitude: Latitude of the location + :param longitude: Longitude of the location + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :param live_period: Period in seconds during which the location will be updated (see `Live Locations `_, should be between 60 and 86400, or 0x7FFFFFFF for live locations that can be edited indefinitely. + :param heading: For live locations, a direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :param proximity_alert_radius: For live locations, a maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_location.SendLocation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendLocation + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendLocation( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + latitude=latitude, + longitude=longitude, + horizontal_accuracy=horizontal_accuracy, + live_period=live_period, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_media_group( + self, + media: List[Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo]], + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendMediaGroup: + """ + Shortcut for method :class:`aiogram.methods.send_media_group.SendMediaGroup` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of `Messages `_ that were sent is returned. + + Source: https://core.telegram.org/bots/api#sendmediagroup + + :param media: A JSON-serialized array describing messages to be sent, must include 2-10 items + :param disable_notification: Sends messages `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent messages from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_media_group.SendMediaGroup` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMediaGroup + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendMediaGroup( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + media=media, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_media_group( + self, + media: List[Union[InputMediaAudio, InputMediaDocument, InputMediaPhoto, InputMediaVideo]], + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendMediaGroup: + """ + Shortcut for method :class:`aiogram.methods.send_media_group.SendMediaGroup` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send a group of photos, videos, documents or audios as an album. Documents and audio files can be only grouped in an album with messages of the same type. On success, an array of `Messages `_ that were sent is returned. + + Source: https://core.telegram.org/bots/api#sendmediagroup + + :param media: A JSON-serialized array describing messages to be sent, must include 2-10 items + :param disable_notification: Sends messages `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent messages from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the messages are a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_media_group.SendMediaGroup` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMediaGroup + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendMediaGroup( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + media=media, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply( + self, + text: str, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[Union[LinkPreviewOptions, Default]] = Default( + "link_preview" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + **kwargs: Any, + ) -> SendMessage: + """ + Shortcut for method :class:`aiogram.methods.send_message.SendMessage` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send text messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendmessage + + :param text: Text of the message to be sent, 1-4096 characters after entities parsing + :param parse_mode: Mode for parsing entities in the message text. See `formatting options `_ for more details. + :param entities: A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode* + :param link_preview_options: Link preview generation options for the message + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param disable_web_page_preview: Disables link previews for links in this message + :return: instance of method :class:`aiogram.methods.send_message.SendMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMessage + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendMessage( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + text=text, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + disable_web_page_preview=disable_web_page_preview, + **kwargs, + ).as_(self._bot) + + def answer( + self, + text: str, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[Union[LinkPreviewOptions, Default]] = Default( + "link_preview" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendMessage: + """ + Shortcut for method :class:`aiogram.methods.send_message.SendMessage` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send text messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendmessage + + :param text: Text of the message to be sent, 1-4096 characters after entities parsing + :param parse_mode: Mode for parsing entities in the message text. See `formatting options `_ for more details. + :param entities: A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode* + :param link_preview_options: Link preview generation options for the message + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param disable_web_page_preview: Disables link previews for links in this message + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_message.SendMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendMessage + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendMessage( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + text=text, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + disable_web_page_preview=disable_web_page_preview, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_photo( + self, + photo: Union[InputFile, str], + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendPhoto: + """ + Shortcut for method :class:`aiogram.methods.send_photo.SendPhoto` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send photos. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendphoto + + :param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. :ref:`More information on Sending Files » ` + :param caption: Photo caption (may also be used when resending photos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the photo caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the photo needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_photo.SendPhoto` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPhoto + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendPhoto( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + photo=photo, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_photo( + self, + photo: Union[InputFile, str], + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendPhoto: + """ + Shortcut for method :class:`aiogram.methods.send_photo.SendPhoto` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send photos. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendphoto + + :param photo: Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a new photo using multipart/form-data. The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20. :ref:`More information on Sending Files » ` + :param caption: Photo caption (may also be used when resending photos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the photo caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the photo needs to be covered with a spoiler animation + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_photo.SendPhoto` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPhoto + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendPhoto( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + photo=photo, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_poll( + self, + question: str, + options: List[Union[InputPollOption, str]], + question_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + question_entities: Optional[List[MessageEntity]] = None, + is_anonymous: Optional[bool] = None, + type: Optional[str] = None, + allows_multiple_answers: Optional[bool] = None, + correct_option_id: Optional[int] = None, + explanation: Optional[str] = None, + explanation_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + explanation_entities: Optional[List[MessageEntity]] = None, + open_period: Optional[int] = None, + close_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + is_closed: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendPoll: + """ + Shortcut for method :class:`aiogram.methods.send_poll.SendPoll` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send a native poll. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpoll + + :param question: Poll question, 1-300 characters + :param options: A JSON-serialized list of 2-10 answer options + :param question_parse_mode: Mode for parsing entities in the question. See `formatting options `_ for more details. Currently, only custom emoji entities are allowed + :param question_entities: A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of *question_parse_mode* + :param is_anonymous: :code:`True`, if the poll needs to be anonymous, defaults to :code:`True` + :param type: Poll type, 'quiz' or 'regular', defaults to 'regular' + :param allows_multiple_answers: :code:`True`, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to :code:`False` + :param correct_option_id: 0-based identifier of the correct answer option, required for polls in quiz mode + :param explanation: Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing + :param explanation_parse_mode: Mode for parsing entities in the explanation. See `formatting options `_ for more details. + :param explanation_entities: A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of *explanation_parse_mode* + :param open_period: Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with *close_date*. + :param close_date: Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with *open_period*. + :param is_closed: Pass :code:`True` if the poll needs to be immediately closed. This can be useful for poll preview. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_poll.SendPoll` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPoll + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendPoll( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + question=question, + options=options, + question_parse_mode=question_parse_mode, + question_entities=question_entities, + is_anonymous=is_anonymous, + type=type, + allows_multiple_answers=allows_multiple_answers, + correct_option_id=correct_option_id, + explanation=explanation, + explanation_parse_mode=explanation_parse_mode, + explanation_entities=explanation_entities, + open_period=open_period, + close_date=close_date, + is_closed=is_closed, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_poll( + self, + question: str, + options: List[Union[InputPollOption, str]], + question_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + question_entities: Optional[List[MessageEntity]] = None, + is_anonymous: Optional[bool] = None, + type: Optional[str] = None, + allows_multiple_answers: Optional[bool] = None, + correct_option_id: Optional[int] = None, + explanation: Optional[str] = None, + explanation_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + explanation_entities: Optional[List[MessageEntity]] = None, + open_period: Optional[int] = None, + close_date: Optional[Union[datetime.datetime, datetime.timedelta, int]] = None, + is_closed: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendPoll: + """ + Shortcut for method :class:`aiogram.methods.send_poll.SendPoll` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send a native poll. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpoll + + :param question: Poll question, 1-300 characters + :param options: A JSON-serialized list of 2-10 answer options + :param question_parse_mode: Mode for parsing entities in the question. See `formatting options `_ for more details. Currently, only custom emoji entities are allowed + :param question_entities: A JSON-serialized list of special entities that appear in the poll question. It can be specified instead of *question_parse_mode* + :param is_anonymous: :code:`True`, if the poll needs to be anonymous, defaults to :code:`True` + :param type: Poll type, 'quiz' or 'regular', defaults to 'regular' + :param allows_multiple_answers: :code:`True`, if the poll allows multiple answers, ignored for polls in quiz mode, defaults to :code:`False` + :param correct_option_id: 0-based identifier of the correct answer option, required for polls in quiz mode + :param explanation: Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters with at most 2 line feeds after entities parsing + :param explanation_parse_mode: Mode for parsing entities in the explanation. See `formatting options `_ for more details. + :param explanation_entities: A JSON-serialized list of special entities that appear in the poll explanation. It can be specified instead of *explanation_parse_mode* + :param open_period: Amount of time in seconds the poll will be active after creation, 5-600. Can't be used together with *close_date*. + :param close_date: Point in time (Unix timestamp) when the poll will be automatically closed. Must be at least 5 and no more than 600 seconds in the future. Can't be used together with *open_period*. + :param is_closed: Pass :code:`True` if the poll needs to be immediately closed. This can be useful for poll preview. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_poll.SendPoll` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPoll + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendPoll( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + question=question, + options=options, + question_parse_mode=question_parse_mode, + question_entities=question_entities, + is_anonymous=is_anonymous, + type=type, + allows_multiple_answers=allows_multiple_answers, + correct_option_id=correct_option_id, + explanation=explanation, + explanation_parse_mode=explanation_parse_mode, + explanation_entities=explanation_entities, + open_period=open_period, + close_date=close_date, + is_closed=is_closed, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_dice( + self, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendDice: + """ + Shortcut for method :class:`aiogram.methods.send_dice.SendDice` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send an animated emoji that will display a random value. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#senddice + + :param emoji: Emoji on which the dice throw animation is based. Currently, must be one of '🎲', '🎯', '🏀', '⚽', '🎳', or '🎰'. Dice can have values 1-6 for '🎲', '🎯' and '🎳', values 1-5 for '🏀' and '⚽', and values 1-64 for '🎰'. Defaults to '🎲' + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_dice.SendDice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDice + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendDice( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_dice( + self, + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendDice: + """ + Shortcut for method :class:`aiogram.methods.send_dice.SendDice` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send an animated emoji that will display a random value. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#senddice + + :param emoji: Emoji on which the dice throw animation is based. Currently, must be one of '🎲', '🎯', '🏀', '⚽', '🎳', or '🎰'. Dice can have values 1-6 for '🎲', '🎯' and '🎳', values 1-5 for '🏀' and '⚽', and values 1-64 for '🎰'. Defaults to '🎲' + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_dice.SendDice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendDice + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendDice( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_sticker( + self, + sticker: Union[InputFile, str], + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendSticker: + """ + Shortcut for method :class:`aiogram.methods.send_sticker.SendSticker` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send static .WEBP, `animated `_ .TGS, or `video `_ .WEBM stickers. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendsticker + + :param sticker: Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. :ref:`More information on Sending Files » `. Video and animated stickers can't be sent via an HTTP URL. + :param emoji: Emoji associated with the sticker; only for just uploaded stickers + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_sticker.SendSticker` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendSticker + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendSticker( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + sticker=sticker, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_sticker( + self, + sticker: Union[InputFile, str], + emoji: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendSticker: + """ + Shortcut for method :class:`aiogram.methods.send_sticker.SendSticker` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send static .WEBP, `animated `_ .TGS, or `video `_ .WEBM stickers. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendsticker + + :param sticker: Sticker to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a .WEBP sticker from the Internet, or upload a new .WEBP, .TGS, or .WEBM sticker using multipart/form-data. :ref:`More information on Sending Files » `. Video and animated stickers can't be sent via an HTTP URL. + :param emoji: Emoji associated with the sticker; only for just uploaded stickers + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_sticker.SendSticker` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendSticker + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendSticker( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + sticker=sticker, + emoji=emoji, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_venue( + self, + latitude: float, + longitude: float, + title: str, + address: str, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendVenue: + """ + Shortcut for method :class:`aiogram.methods.send_venue.SendVenue` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send information about a venue. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvenue + + :param latitude: Latitude of the venue + :param longitude: Longitude of the venue + :param title: Name of the venue + :param address: Address of the venue + :param foursquare_id: Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.) + :param google_place_id: Google Places identifier of the venue + :param google_place_type: Google Places type of the venue. (See `supported types `_.) + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_venue.SendVenue` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVenue + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendVenue( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + latitude=latitude, + longitude=longitude, + title=title, + address=address, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_venue( + self, + latitude: float, + longitude: float, + title: str, + address: str, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVenue: + """ + Shortcut for method :class:`aiogram.methods.send_venue.SendVenue` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send information about a venue. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvenue + + :param latitude: Latitude of the venue + :param longitude: Longitude of the venue + :param title: Name of the venue + :param address: Address of the venue + :param foursquare_id: Foursquare identifier of the venue + :param foursquare_type: Foursquare type of the venue, if known. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.) + :param google_place_id: Google Places identifier of the venue + :param google_place_type: Google Places type of the venue. (See `supported types `_.) + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_venue.SendVenue` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVenue + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendVenue( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + latitude=latitude, + longitude=longitude, + title=title, + address=address, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_video( + self, + video: Union[InputFile, str], + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + supports_streaming: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendVideo: + """ + Shortcut for method :class:`aiogram.methods.send_video.SendVideo` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvideo + + :param video: Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. :ref:`More information on Sending Files » ` + :param duration: Duration of sent video in seconds + :param width: Video width + :param height: Video height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Video caption (may also be used when resending videos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the video caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the video needs to be covered with a spoiler animation + :param supports_streaming: Pass :code:`True` if the uploaded video is suitable for streaming + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_video.SendVideo` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideo + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendVideo( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + video=video, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + supports_streaming=supports_streaming, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_video( + self, + video: Union[InputFile, str], + duration: Optional[int] = None, + width: Optional[int] = None, + height: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + has_spoiler: Optional[bool] = None, + supports_streaming: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVideo: + """ + Shortcut for method :class:`aiogram.methods.send_video.SendVideo` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send video files, Telegram clients support MPEG4 videos (other formats may be sent as :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvideo + + :param video: Video to send. Pass a file_id as String to send a video that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a video from the Internet, or upload a new video using multipart/form-data. :ref:`More information on Sending Files » ` + :param duration: Duration of sent video in seconds + :param width: Video width + :param height: Video height + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param caption: Video caption (may also be used when resending videos by *file_id*), 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the video caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param has_spoiler: Pass :code:`True` if the video needs to be covered with a spoiler animation + :param supports_streaming: Pass :code:`True` if the uploaded video is suitable for streaming + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_video.SendVideo` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideo + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendVideo( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + video=video, + duration=duration, + width=width, + height=height, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + has_spoiler=has_spoiler, + supports_streaming=supports_streaming, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_video_note( + self, + video_note: Union[InputFile, str], + duration: Optional[int] = None, + length: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendVideoNote: + """ + Shortcut for method :class:`aiogram.methods.send_video_note.SendVideoNote` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + As of `v.4.0 `_, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvideonote + + :param video_note: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. :ref:`More information on Sending Files » `. Sending video notes by a URL is currently unsupported + :param duration: Duration of sent video in seconds + :param length: Video width and height, i.e. diameter of the video message + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_video_note.SendVideoNote` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideoNote + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendVideoNote( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + video_note=video_note, + duration=duration, + length=length, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_video_note( + self, + video_note: Union[InputFile, str], + duration: Optional[int] = None, + length: Optional[int] = None, + thumbnail: Optional[InputFile] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVideoNote: + """ + Shortcut for method :class:`aiogram.methods.send_video_note.SendVideoNote` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + As of `v.4.0 `_, Telegram clients support rounded square MPEG4 videos of up to 1 minute long. Use this method to send video messages. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendvideonote + + :param video_note: Video note to send. Pass a file_id as String to send a video note that exists on the Telegram servers (recommended) or upload a new video using multipart/form-data. :ref:`More information on Sending Files » `. Sending video notes by a URL is currently unsupported + :param duration: Duration of sent video in seconds + :param length: Video width and height, i.e. diameter of the video message + :param thumbnail: Thumbnail of the file sent; can be ignored if thumbnail generation for the file is supported server-side. The thumbnail should be in JPEG format and less than 200 kB in size. A thumbnail's width and height should not exceed 320. Ignored if the file is not uploaded using multipart/form-data. Thumbnails can't be reused and can be only uploaded as a new file, so you can pass 'attach://' if the thumbnail was uploaded using multipart/form-data under . :ref:`More information on Sending Files » ` + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_video_note.SendVideoNote` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVideoNote + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendVideoNote( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + video_note=video_note, + duration=duration, + length=length, + thumbnail=thumbnail, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def reply_voice( + self, + voice: Union[InputFile, str], + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + **kwargs: Any, + ) -> SendVoice: + """ + Shortcut for method :class:`aiogram.methods.send_voice.SendVoice` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as :class:`aiogram.types.audio.Audio` or :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvoice + + :param voice: Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param caption: Voice message caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the voice message caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the voice message in seconds + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :return: instance of method :class:`aiogram.methods.send_voice.SendVoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVoice + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendVoice( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + voice=voice, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + **kwargs, + ).as_(self._bot) + + def answer_voice( + self, + voice: Union[InputFile, str], + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + message_effect_id: Optional[str] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> SendVoice: + """ + Shortcut for method :class:`aiogram.methods.send_voice.SendVoice` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message. For this to work, your audio must be in an .OGG file encoded with OPUS, or in .MP3 format, or in .M4A format (other formats may be sent as :class:`aiogram.types.audio.Audio` or :class:`aiogram.types.document.Document`). On success, the sent :class:`aiogram.types.message.Message` is returned. Bots can currently send voice messages of up to 50 MB in size, this limit may be changed in the future. + + Source: https://core.telegram.org/bots/api#sendvoice + + :param voice: Audio file to send. Pass a file_id as String to send a file that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a file from the Internet, or upload a new one using multipart/form-data. :ref:`More information on Sending Files » ` + :param caption: Voice message caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the voice message caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param duration: Duration of the voice message in seconds + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param message_effect_id: Unique identifier of the message effect to be added to the message; for private chats only + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.send_voice.SendVoice` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendVoice + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendVoice( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + voice=voice, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + disable_notification=disable_notification, + protect_content=protect_content, + message_effect_id=message_effect_id, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def send_copy( # noqa: C901 + self: Message, + chat_id: Union[str, int], + disable_notification: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, None] = None, + allow_sending_without_reply: Optional[bool] = None, + message_thread_id: Optional[int] = None, + business_connection_id: Optional[str] = None, + parse_mode: Optional[str] = None, + message_effect_id: Optional[str] = None, + ) -> Union[ + ForwardMessage, + SendAnimation, + SendAudio, + SendContact, + SendDocument, + SendLocation, + SendMessage, + SendPhoto, + SendPoll, + SendDice, + SendSticker, + SendVenue, + SendVideo, + SendVideoNote, + SendVoice, + ]: + """ + Send copy of a message. + + Is similar to :meth:`aiogram.client.bot.Bot.copy_message` + but returning the sent message instead of :class:`aiogram.types.message_id.MessageId` + + .. note:: + + This method doesn't use the API method named `copyMessage` and + historically implemented before the similar method is added to API + + :param chat_id: + :param disable_notification: + :param reply_to_message_id: + :param reply_parameters: + :param reply_markup: + :param allow_sending_without_reply: + :param message_thread_id: + :param business_connection_id: + :param parse_mode: + :param message_effect_id: + :return: + """ + from ..methods import ( + ForwardMessage, + SendAnimation, + SendAudio, + SendContact, + SendDice, + SendDocument, + SendLocation, + SendMessage, + SendPhoto, + SendPoll, + SendSticker, + SendVenue, + SendVideo, + SendVideoNote, + SendVoice, + ) + + kwargs: Dict[str, Any] = { + "chat_id": chat_id, + "reply_markup": reply_markup or self.reply_markup, + "disable_notification": disable_notification, + "reply_to_message_id": reply_to_message_id, + "reply_parameters": reply_parameters, + "message_thread_id": message_thread_id, + "business_connection_id": business_connection_id, + "allow_sending_without_reply": allow_sending_without_reply, + # when sending a copy, we don't need any parse mode + # because all entities are already prepared + "parse_mode": parse_mode, + "message_effect_id": message_effect_id or self.effect_id, + } + + if self.text: + return SendMessage( + text=self.text, + entities=self.entities, + **kwargs, + ).as_(self._bot) + if self.audio: + return SendAudio( + audio=self.audio.file_id, + caption=self.caption, + title=self.audio.title, + performer=self.audio.performer, + duration=self.audio.duration, + caption_entities=self.caption_entities, + **kwargs, + ).as_(self._bot) + if self.animation: + return SendAnimation( + animation=self.animation.file_id, + caption=self.caption, + caption_entities=self.caption_entities, + **kwargs, + ).as_(self._bot) + if self.document: + return SendDocument( + document=self.document.file_id, + caption=self.caption, + caption_entities=self.caption_entities, + **kwargs, + ).as_(self._bot) + if self.photo: + return SendPhoto( + photo=self.photo[-1].file_id, + caption=self.caption, + caption_entities=self.caption_entities, + **kwargs, + ).as_(self._bot) + if self.sticker: + return SendSticker( + sticker=self.sticker.file_id, + **kwargs, + ).as_(self._bot) + if self.video: + return SendVideo( + video=self.video.file_id, + caption=self.caption, + caption_entities=self.caption_entities, + **kwargs, + ).as_(self._bot) + if self.video_note: + return SendVideoNote( + video_note=self.video_note.file_id, + **kwargs, + ).as_(self._bot) + if self.voice: + return SendVoice( + voice=self.voice.file_id, + **kwargs, + ).as_(self._bot) + if self.contact: + return SendContact( + phone_number=self.contact.phone_number, + first_name=self.contact.first_name, + last_name=self.contact.last_name, + vcard=self.contact.vcard, + **kwargs, + ).as_(self._bot) + if self.venue: + return SendVenue( + latitude=self.venue.location.latitude, + longitude=self.venue.location.longitude, + title=self.venue.title, + address=self.venue.address, + foursquare_id=self.venue.foursquare_id, + foursquare_type=self.venue.foursquare_type, + **kwargs, + ).as_(self._bot) + if self.location: + return SendLocation( + latitude=self.location.latitude, + longitude=self.location.longitude, + **kwargs, + ).as_(self._bot) + if self.poll: + from .input_poll_option import InputPollOption + + return SendPoll( + question=self.poll.question, + options=[ + InputPollOption( + text=option.text, + voter_count=option.voter_count, + text_entities=option.text_entities, + text_parse_mode=None, + ) + for option in self.poll.options + ], + **kwargs, + ).as_(self._bot) + if self.dice: # Dice value can't be controlled + return SendDice( + **kwargs, + ).as_(self._bot) + if self.story: + return ForwardMessage( + from_chat_id=self.chat.id, + message_id=self.message_id, + **kwargs, + ).as_(self._bot) + + raise TypeError("This type of message can't be copied.") + + def copy_to( + self, + chat_id: Union[int, str], + message_thread_id: Optional[int] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + allow_sending_without_reply: Optional[bool] = None, + reply_to_message_id: Optional[int] = None, + **kwargs: Any, + ) -> CopyMessage: + """ + Shortcut for method :class:`aiogram.methods.copy_message.CopyMessage` + will automatically fill method attributes: + + - :code:`from_chat_id` + - :code:`message_id` + + Use this method to copy messages of any kind. Service messages, paid media messages, giveaway messages, giveaway winners messages, and invoice messages can't be copied. A quiz :class:`aiogram.methods.poll.Poll` can be copied only if the value of the field *correct_option_id* is known to the bot. The method is analogous to the method :class:`aiogram.methods.forward_message.ForwardMessage`, but the copied message doesn't have a link to the original message. Returns the :class:`aiogram.types.message_id.MessageId` of the sent message on success. + + Source: https://core.telegram.org/bots/api#copymessage + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param caption: New caption for media, 0-1024 characters after entities parsing. If not specified, the original caption is kept + :param parse_mode: Mode for parsing entities in the new caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the new caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media. Ignored if a new caption isn't specified. + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :param allow_sending_without_reply: Pass :code:`True` if the message should be sent even if the specified replied-to message is not found + :param reply_to_message_id: If the message is a reply, ID of the original message + :return: instance of method :class:`aiogram.methods.copy_message.CopyMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import CopyMessage + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return CopyMessage( + from_chat_id=self.chat.id, + message_id=self.message_id, + chat_id=chat_id, + message_thread_id=message_thread_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + disable_notification=disable_notification, + protect_content=protect_content, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + allow_sending_without_reply=allow_sending_without_reply, + reply_to_message_id=reply_to_message_id, + **kwargs, + ).as_(self._bot) + + def edit_text( + self, + text: str, + business_connection_id: Optional[str] = None, + inline_message_id: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + entities: Optional[List[MessageEntity]] = None, + link_preview_options: Optional[LinkPreviewOptions] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + disable_web_page_preview: Optional[Union[bool, Default]] = Default( + "link_preview_is_disabled" + ), + **kwargs: Any, + ) -> EditMessageText: + """ + Shortcut for method :class:`aiogram.methods.edit_message_text.EditMessageText` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to edit text and `game `_ messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagetext + + :param text: New text of the message, 1-4096 characters after entities parsing + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param parse_mode: Mode for parsing entities in the message text. See `formatting options `_ for more details. + :param entities: A JSON-serialized list of special entities that appear in message text, which can be specified instead of *parse_mode* + :param link_preview_options: Link preview generation options for the message + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. + :param disable_web_page_preview: Disables link previews for links in this message + :return: instance of method :class:`aiogram.methods.edit_message_text.EditMessageText` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import EditMessageText + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return EditMessageText( + chat_id=self.chat.id, + message_id=self.message_id, + text=text, + business_connection_id=business_connection_id, + inline_message_id=inline_message_id, + parse_mode=parse_mode, + entities=entities, + link_preview_options=link_preview_options, + reply_markup=reply_markup, + disable_web_page_preview=disable_web_page_preview, + **kwargs, + ).as_(self._bot) + + def forward( + self, + chat_id: Union[int, str], + message_thread_id: Optional[int] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[Union[bool, Default]] = Default("protect_content"), + **kwargs: Any, + ) -> ForwardMessage: + """ + Shortcut for method :class:`aiogram.methods.forward_message.ForwardMessage` + will automatically fill method attributes: + + - :code:`from_chat_id` + - :code:`message_id` + + Use this method to forward messages of any kind. Service messages and messages with protected content can't be forwarded. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#forwardmessage + + :param chat_id: Unique identifier for the target chat or username of the target channel (in the format :code:`@channelusername`) + :param message_thread_id: Unique identifier for the target message thread (topic) of the forum; for forum supergroups only + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the forwarded message from forwarding and saving + :return: instance of method :class:`aiogram.methods.forward_message.ForwardMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import ForwardMessage + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return ForwardMessage( + from_chat_id=self.chat.id, + message_id=self.message_id, + chat_id=chat_id, + message_thread_id=message_thread_id, + disable_notification=disable_notification, + protect_content=protect_content, + **kwargs, + ).as_(self._bot) + + def edit_media( + self, + media: Union[ + InputMediaAnimation, + InputMediaDocument, + InputMediaAudio, + InputMediaPhoto, + InputMediaVideo, + ], + business_connection_id: Optional[str] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **kwargs: Any, + ) -> EditMessageMedia: + """ + Shortcut for method :class:`aiogram.methods.edit_message_media.EditMessageMedia` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to edit animation, audio, document, photo, or video messages. If a message is part of a message album, then it can be edited only to an audio for audio albums, only to a document for document albums and to a photo or a video otherwise. When an inline message is edited, a new file can't be uploaded; use a previously uploaded file via its file_id or specify a URL. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagemedia + + :param media: A JSON-serialized object for a new media content of the message + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param reply_markup: A JSON-serialized object for a new `inline keyboard `_. + :return: instance of method :class:`aiogram.methods.edit_message_media.EditMessageMedia` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import EditMessageMedia + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return EditMessageMedia( + chat_id=self.chat.id, + message_id=self.message_id, + media=media, + business_connection_id=business_connection_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + **kwargs, + ).as_(self._bot) + + def edit_reply_markup( + self, + business_connection_id: Optional[str] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **kwargs: Any, + ) -> EditMessageReplyMarkup: + """ + Shortcut for method :class:`aiogram.methods.edit_message_reply_markup.EditMessageReplyMarkup` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagereplymarkup + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. + :return: instance of method :class:`aiogram.methods.edit_message_reply_markup.EditMessageReplyMarkup` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import EditMessageReplyMarkup + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return EditMessageReplyMarkup( + chat_id=self.chat.id, + message_id=self.message_id, + business_connection_id=business_connection_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + **kwargs, + ).as_(self._bot) + + def delete_reply_markup( + self, + business_connection_id: Optional[str] = None, + inline_message_id: Optional[str] = None, + **kwargs: Any, + ) -> EditMessageReplyMarkup: + """ + Shortcut for method :class:`aiogram.methods.edit_message_reply_markup.EditMessageReplyMarkup` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + - :code:`reply_markup` + + Use this method to edit only the reply markup of messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagereplymarkup + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :return: instance of method :class:`aiogram.methods.edit_message_reply_markup.EditMessageReplyMarkup` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import EditMessageReplyMarkup + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return EditMessageReplyMarkup( + chat_id=self.chat.id, + message_id=self.message_id, + reply_markup=None, + business_connection_id=business_connection_id, + inline_message_id=inline_message_id, + **kwargs, + ).as_(self._bot) + + def edit_live_location( + self, + latitude: float, + longitude: float, + business_connection_id: Optional[str] = None, + inline_message_id: Optional[str] = None, + live_period: Optional[int] = None, + horizontal_accuracy: Optional[float] = None, + heading: Optional[int] = None, + proximity_alert_radius: Optional[int] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **kwargs: Any, + ) -> EditMessageLiveLocation: + """ + Shortcut for method :class:`aiogram.methods.edit_message_live_location.EditMessageLiveLocation` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to edit live location messages. A location can be edited until its *live_period* expires or editing is explicitly disabled by a call to :class:`aiogram.methods.stop_message_live_location.StopMessageLiveLocation`. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#editmessagelivelocation + + :param latitude: Latitude of new location + :param longitude: Longitude of new location + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param live_period: New period in seconds during which the location can be updated, starting from the message send date. If 0x7FFFFFFF is specified, then the location can be updated forever. Otherwise, the new value must not exceed the current *live_period* by more than a day, and the live location expiration date must remain within the next 90 days. If not specified, then *live_period* remains unchanged + :param horizontal_accuracy: The radius of uncertainty for the location, measured in meters; 0-1500 + :param heading: Direction in which the user is moving, in degrees. Must be between 1 and 360 if specified. + :param proximity_alert_radius: The maximum distance for proximity alerts about approaching another chat member, in meters. Must be between 1 and 100000 if specified. + :param reply_markup: A JSON-serialized object for a new `inline keyboard `_. + :return: instance of method :class:`aiogram.methods.edit_message_live_location.EditMessageLiveLocation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import EditMessageLiveLocation + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return EditMessageLiveLocation( + chat_id=self.chat.id, + message_id=self.message_id, + latitude=latitude, + longitude=longitude, + business_connection_id=business_connection_id, + inline_message_id=inline_message_id, + live_period=live_period, + horizontal_accuracy=horizontal_accuracy, + heading=heading, + proximity_alert_radius=proximity_alert_radius, + reply_markup=reply_markup, + **kwargs, + ).as_(self._bot) + + def stop_live_location( + self, + business_connection_id: Optional[str] = None, + inline_message_id: Optional[str] = None, + reply_markup: Optional[InlineKeyboardMarkup] = None, + **kwargs: Any, + ) -> StopMessageLiveLocation: + """ + Shortcut for method :class:`aiogram.methods.stop_message_live_location.StopMessageLiveLocation` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to stop updating a live location message before *live_period* expires. On success, if the message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#stopmessagelivelocation + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param reply_markup: A JSON-serialized object for a new `inline keyboard `_. + :return: instance of method :class:`aiogram.methods.stop_message_live_location.StopMessageLiveLocation` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import StopMessageLiveLocation + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return StopMessageLiveLocation( + chat_id=self.chat.id, + message_id=self.message_id, + business_connection_id=business_connection_id, + inline_message_id=inline_message_id, + reply_markup=reply_markup, + **kwargs, + ).as_(self._bot) + + def edit_caption( + self, + business_connection_id: Optional[str] = None, + inline_message_id: Optional[str] = None, + caption: Optional[str] = None, + parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[Union[bool, Default]] = Default( + "show_caption_above_media" + ), + reply_markup: Optional[InlineKeyboardMarkup] = None, + **kwargs: Any, + ) -> EditMessageCaption: + """ + Shortcut for method :class:`aiogram.methods.edit_message_caption.EditMessageCaption` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to edit captions of messages. On success, if the edited message is not an inline message, the edited :class:`aiogram.types.message.Message` is returned, otherwise :code:`True` is returned. Note that business messages that were not sent by the bot and do not contain an inline keyboard can only be edited within **48 hours** from the time they were sent. + + Source: https://core.telegram.org/bots/api#editmessagecaption + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message to be edited was sent + :param inline_message_id: Required if *chat_id* and *message_id* are not specified. Identifier of the inline message + :param caption: New caption of the message, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the message caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media. Supported only for animation, photo and video messages. + :param reply_markup: A JSON-serialized object for an `inline keyboard `_. + :return: instance of method :class:`aiogram.methods.edit_message_caption.EditMessageCaption` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import EditMessageCaption + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return EditMessageCaption( + chat_id=self.chat.id, + message_id=self.message_id, + business_connection_id=business_connection_id, + inline_message_id=inline_message_id, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + reply_markup=reply_markup, + **kwargs, + ).as_(self._bot) + + def delete( + self, + **kwargs: Any, + ) -> DeleteMessage: + """ + Shortcut for method :class:`aiogram.methods.delete_message.DeleteMessage` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to delete a message, including service messages, with the following limitations: + + - A message can only be deleted if it was sent less than 48 hours ago. + + - Service messages about a supergroup, channel, or forum topic creation can't be deleted. + + - A dice message in a private chat can only be deleted if it was sent more than 24 hours ago. + + - Bots can delete outgoing messages in private chats, groups, and supergroups. + + - Bots can delete incoming messages in private chats. + + - Bots granted *can_post_messages* permissions can delete outgoing messages in channels. + + - If the bot is an administrator of a group, it can delete any message there. + + - If the bot has *can_delete_messages* permission in a supergroup or a channel, it can delete any message there. + + Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletemessage + + :return: instance of method :class:`aiogram.methods.delete_message.DeleteMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import DeleteMessage + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return DeleteMessage( + chat_id=self.chat.id, + message_id=self.message_id, + **kwargs, + ).as_(self._bot) + + def pin( + self, + business_connection_id: Optional[str] = None, + disable_notification: Optional[bool] = None, + **kwargs: Any, + ) -> PinChatMessage: + """ + Shortcut for method :class:`aiogram.methods.pin_chat_message.PinChatMessage` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to add a message to the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#pinchatmessage + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be pinned + :param disable_notification: Pass :code:`True` if it is not necessary to send a notification to all chat members about the new pinned message. Notifications are always disabled in channels and private chats. + :return: instance of method :class:`aiogram.methods.pin_chat_message.PinChatMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import PinChatMessage + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return PinChatMessage( + chat_id=self.chat.id, + message_id=self.message_id, + business_connection_id=business_connection_id, + disable_notification=disable_notification, + **kwargs, + ).as_(self._bot) + + def unpin( + self, + business_connection_id: Optional[str] = None, + **kwargs: Any, + ) -> UnpinChatMessage: + """ + Shortcut for method :class:`aiogram.methods.unpin_chat_message.UnpinChatMessage` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to remove a message from the list of pinned messages in a chat. If the chat is not a private chat, the bot must be an administrator in the chat for this to work and must have the 'can_pin_messages' administrator right in a supergroup or 'can_edit_messages' administrator right in a channel. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#unpinchatmessage + + :param business_connection_id: Unique identifier of the business connection on behalf of which the message will be unpinned + :return: instance of method :class:`aiogram.methods.unpin_chat_message.UnpinChatMessage` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import UnpinChatMessage + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return UnpinChatMessage( + chat_id=self.chat.id, + message_id=self.message_id, + business_connection_id=business_connection_id, + **kwargs, + ).as_(self._bot) + + def get_url( + self, force_private: bool = False, include_thread_id: bool = False + ) -> Optional[str]: + """ + Returns message URL. Cannot be used in private (one-to-one) chats. + If chat has a username, returns URL like https://t.me/username/message_id + Otherwise (or if {force_private} flag is set), returns https://t.me/c/shifted_chat_id/message_id + + :param force_private: if set, a private URL is returned even for a public chat + :param include_thread_id: if set, adds chat thread id to URL and returns like https://t.me/username/thread_id/message_id + :return: string with full message URL + """ + if self.chat.type in ("private", "group"): + return None + + chat_value = ( + f"c/{self.chat.shifted_id}" + if not self.chat.username or force_private + else self.chat.username + ) + + message_id_value = ( + f"{self.message_thread_id}/{self.message_id}" + if include_thread_id and self.message_thread_id and self.is_topic_message + else f"{self.message_id}" + ) + + return f"https://t.me/{chat_value}/{message_id_value}" + + def react( + self, + reaction: Optional[ + List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + ] = None, + is_big: Optional[bool] = None, + **kwargs: Any, + ) -> SetMessageReaction: + """ + Shortcut for method :class:`aiogram.methods.set_message_reaction.SetMessageReaction` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_id` + + Use this method to change the chosen reactions on a message. Service messages can't be reacted to. Automatically forwarded messages from a channel to its discussion group have the same available reactions as messages in the channel. Bots can't use paid reactions. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setmessagereaction + + :param reaction: A JSON-serialized list of reaction types to set on the message. Currently, as non-premium users, bots can set up to one reaction per message. A custom emoji reaction can be used if it is either already present on the message or explicitly allowed by chat administrators. Paid reactions can't be used by bots. + :param is_big: Pass :code:`True` to set the reaction with a big animation + :return: instance of method :class:`aiogram.methods.set_message_reaction.SetMessageReaction` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SetMessageReaction + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SetMessageReaction( + chat_id=self.chat.id, + message_id=self.message_id, + reaction=reaction, + is_big=is_big, + **kwargs, + ).as_(self._bot) + + def answer_paid_media( + self, + star_count: int, + media: List[Union[InputPaidMediaPhoto, InputPaidMediaVideo]], + caption: Optional[str] = None, + parse_mode: Optional[str] = None, + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[bool] = None, + reply_parameters: Optional[ReplyParameters] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + **kwargs: Any, + ) -> SendPaidMedia: + """ + Shortcut for method :class:`aiogram.methods.send_paid_media.SendPaidMedia` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + + Use this method to send paid media. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpaidmedia + + :param star_count: The number of Telegram Stars that must be paid to buy access to the media + :param media: A JSON-serialized array describing the media to be sent; up to 10 items + :param caption: Media caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the media caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param reply_parameters: Description of the message to reply to + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :return: instance of method :class:`aiogram.methods.send_paid_media.SendPaidMedia` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPaidMedia + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendPaidMedia( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + star_count=star_count, + media=media, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + disable_notification=disable_notification, + protect_content=protect_content, + reply_parameters=reply_parameters, + reply_markup=reply_markup, + **kwargs, + ).as_(self._bot) + + def reply_paid_media( + self, + star_count: int, + media: List[Union[InputPaidMediaPhoto, InputPaidMediaVideo]], + caption: Optional[str] = None, + parse_mode: Optional[str] = None, + caption_entities: Optional[List[MessageEntity]] = None, + show_caption_above_media: Optional[bool] = None, + disable_notification: Optional[bool] = None, + protect_content: Optional[bool] = None, + reply_markup: Optional[ + Union[InlineKeyboardMarkup, ReplyKeyboardMarkup, ReplyKeyboardRemove, ForceReply] + ] = None, + **kwargs: Any, + ) -> SendPaidMedia: + """ + Shortcut for method :class:`aiogram.methods.send_paid_media.SendPaidMedia` + will automatically fill method attributes: + + - :code:`chat_id` + - :code:`message_thread_id` + - :code:`business_connection_id` + - :code:`reply_parameters` + + Use this method to send paid media. On success, the sent :class:`aiogram.types.message.Message` is returned. + + Source: https://core.telegram.org/bots/api#sendpaidmedia + + :param star_count: The number of Telegram Stars that must be paid to buy access to the media + :param media: A JSON-serialized array describing the media to be sent; up to 10 items + :param caption: Media caption, 0-1024 characters after entities parsing + :param parse_mode: Mode for parsing entities in the media caption. See `formatting options `_ for more details. + :param caption_entities: A JSON-serialized list of special entities that appear in the caption, which can be specified instead of *parse_mode* + :param show_caption_above_media: Pass :code:`True`, if the caption must be shown above the message media + :param disable_notification: Sends the message `silently `_. Users will receive a notification with no sound. + :param protect_content: Protects the contents of the sent message from forwarding and saving + :param reply_markup: Additional interface options. A JSON-serialized object for an `inline keyboard `_, `custom reply keyboard `_, instructions to remove a reply keyboard or to force a reply from the user + :return: instance of method :class:`aiogram.methods.send_paid_media.SendPaidMedia` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SendPaidMedia + + assert ( + self.chat is not None + ), "This method can be used only if chat is present in the message." + + return SendPaidMedia( + chat_id=self.chat.id, + message_thread_id=self.message_thread_id if self.is_topic_message else None, + business_connection_id=self.business_connection_id, + reply_parameters=self.as_reply_parameters(), + star_count=star_count, + media=media, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + show_caption_above_media=show_caption_above_media, + disable_notification=disable_notification, + protect_content=protect_content, + reply_markup=reply_markup, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/message_auto_delete_timer_changed.py b/env/Lib/site-packages/aiogram/types/message_auto_delete_timer_changed.py new file mode 100644 index 0000000..8414a24 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_auto_delete_timer_changed.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class MessageAutoDeleteTimerChanged(TelegramObject): + """ + This object represents a service message about a change in auto-delete timer settings. + + Source: https://core.telegram.org/bots/api#messageautodeletetimerchanged + """ + + message_auto_delete_time: int + """New auto-delete time for messages in the chat; in seconds""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, message_auto_delete_time: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + message_auto_delete_time=message_auto_delete_time, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/message_entity.py b/env/Lib/site-packages/aiogram/types/message_entity.py new file mode 100644 index 0000000..ee774b0 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_entity.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..utils.text_decorations import add_surrogates, remove_surrogates +from .base import MutableTelegramObject + +if TYPE_CHECKING: + from .user import User + + +class MessageEntity(MutableTelegramObject): + """ + This object represents one special entity in a text message. For example, hashtags, usernames, URLs, etc. + + Source: https://core.telegram.org/bots/api#messageentity + """ + + type: str + """Type of the entity. Currently, can be 'mention' (:code:`@username`), 'hashtag' (:code:`#hashtag`), 'cashtag' (:code:`$USD`), 'bot_command' (:code:`/start@jobs_bot`), 'url' (:code:`https://telegram.org`), 'email' (:code:`do-not-reply@telegram.org`), 'phone_number' (:code:`+1-212-555-0123`), 'bold' (**bold text**), 'italic' (*italic text*), 'underline' (underlined text), 'strikethrough' (strikethrough text), 'spoiler' (spoiler message), 'blockquote' (block quotation), 'expandable_blockquote' (collapsed-by-default block quotation), 'code' (monowidth string), 'pre' (monowidth block), 'text_link' (for clickable text URLs), 'text_mention' (for users `without usernames `_), 'custom_emoji' (for inline custom emoji stickers)""" + offset: int + """Offset in `UTF-16 code units `_ to the start of the entity""" + length: int + """Length of the entity in `UTF-16 code units `_""" + url: Optional[str] = None + """*Optional*. For 'text_link' only, URL that will be opened after user taps on the text""" + user: Optional[User] = None + """*Optional*. For 'text_mention' only, the mentioned user""" + language: Optional[str] = None + """*Optional*. For 'pre' only, the programming language of the entity text""" + custom_emoji_id: Optional[str] = None + """*Optional*. For 'custom_emoji' only, unique identifier of the custom emoji. Use :class:`aiogram.methods.get_custom_emoji_stickers.GetCustomEmojiStickers` to get full information about the sticker""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: str, + offset: int, + length: int, + url: Optional[str] = None, + user: Optional[User] = None, + language: Optional[str] = None, + custom_emoji_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + offset=offset, + length=length, + url=url, + user=user, + language=language, + custom_emoji_id=custom_emoji_id, + **__pydantic_kwargs, + ) + + def extract_from(self, text: str) -> str: + return remove_surrogates( + add_surrogates(text)[self.offset * 2 : (self.offset + self.length) * 2] + ) diff --git a/env/Lib/site-packages/aiogram/types/message_id.py b/env/Lib/site-packages/aiogram/types/message_id.py new file mode 100644 index 0000000..d50888f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_id.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class MessageId(TelegramObject): + """ + This object represents a unique message identifier. + + Source: https://core.telegram.org/bots/api#messageid + """ + + message_id: int + """Unique message identifier""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, message_id: int, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(message_id=message_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/message_origin.py b/env/Lib/site-packages/aiogram/types/message_origin.py new file mode 100644 index 0000000..01f9977 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_origin.py @@ -0,0 +1,14 @@ +from aiogram.types import TelegramObject + + +class MessageOrigin(TelegramObject): + """ + This object describes the origin of a message. It can be one of + + - :class:`aiogram.types.message_origin_user.MessageOriginUser` + - :class:`aiogram.types.message_origin_hidden_user.MessageOriginHiddenUser` + - :class:`aiogram.types.message_origin_chat.MessageOriginChat` + - :class:`aiogram.types.message_origin_channel.MessageOriginChannel` + + Source: https://core.telegram.org/bots/api#messageorigin + """ diff --git a/env/Lib/site-packages/aiogram/types/message_origin_channel.py b/env/Lib/site-packages/aiogram/types/message_origin_channel.py new file mode 100644 index 0000000..9decfaf --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_origin_channel.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from ..enums import MessageOriginType +from .custom import DateTime +from .message_origin import MessageOrigin + +if TYPE_CHECKING: + from .chat import Chat + + +class MessageOriginChannel(MessageOrigin): + """ + The message was originally sent to a channel chat. + + Source: https://core.telegram.org/bots/api#messageoriginchannel + """ + + type: Literal[MessageOriginType.CHANNEL] = MessageOriginType.CHANNEL + """Type of the message origin, always 'channel'""" + date: DateTime + """Date the message was sent originally in Unix time""" + chat: Chat + """Channel chat to which the message was originally sent""" + message_id: int + """Unique message identifier inside the chat""" + author_signature: Optional[str] = None + """*Optional*. Signature of the original post author""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[MessageOriginType.CHANNEL] = MessageOriginType.CHANNEL, + date: DateTime, + chat: Chat, + message_id: int, + author_signature: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + date=date, + chat=chat, + message_id=message_id, + author_signature=author_signature, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/message_origin_chat.py b/env/Lib/site-packages/aiogram/types/message_origin_chat.py new file mode 100644 index 0000000..b1e5fb9 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_origin_chat.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from ..enums import MessageOriginType +from .custom import DateTime +from .message_origin import MessageOrigin + +if TYPE_CHECKING: + from .chat import Chat + + +class MessageOriginChat(MessageOrigin): + """ + The message was originally sent on behalf of a chat to a group chat. + + Source: https://core.telegram.org/bots/api#messageoriginchat + """ + + type: Literal[MessageOriginType.CHAT] = MessageOriginType.CHAT + """Type of the message origin, always 'chat'""" + date: DateTime + """Date the message was sent originally in Unix time""" + sender_chat: Chat + """Chat that sent the message originally""" + author_signature: Optional[str] = None + """*Optional*. For messages originally sent by an anonymous chat administrator, original message author signature""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[MessageOriginType.CHAT] = MessageOriginType.CHAT, + date: DateTime, + sender_chat: Chat, + author_signature: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + date=date, + sender_chat=sender_chat, + author_signature=author_signature, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/message_origin_hidden_user.py b/env/Lib/site-packages/aiogram/types/message_origin_hidden_user.py new file mode 100644 index 0000000..cd702f1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_origin_hidden_user.py @@ -0,0 +1,40 @@ +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import MessageOriginType +from .custom import DateTime +from .message_origin import MessageOrigin + + +class MessageOriginHiddenUser(MessageOrigin): + """ + The message was originally sent by an unknown user. + + Source: https://core.telegram.org/bots/api#messageoriginhiddenuser + """ + + type: Literal[MessageOriginType.HIDDEN_USER] = MessageOriginType.HIDDEN_USER + """Type of the message origin, always 'hidden_user'""" + date: DateTime + """Date the message was sent originally in Unix time""" + sender_user_name: str + """Name of the user that sent the message originally""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[MessageOriginType.HIDDEN_USER] = MessageOriginType.HIDDEN_USER, + date: DateTime, + sender_user_name: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, date=date, sender_user_name=sender_user_name, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/message_origin_user.py b/env/Lib/site-packages/aiogram/types/message_origin_user.py new file mode 100644 index 0000000..d77ac7a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_origin_user.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import MessageOriginType +from .custom import DateTime +from .message_origin import MessageOrigin + +if TYPE_CHECKING: + from .user import User + + +class MessageOriginUser(MessageOrigin): + """ + The message was originally sent by a known user. + + Source: https://core.telegram.org/bots/api#messageoriginuser + """ + + type: Literal[MessageOriginType.USER] = MessageOriginType.USER + """Type of the message origin, always 'user'""" + date: DateTime + """Date the message was sent originally in Unix time""" + sender_user: User + """User that sent the message originally""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[MessageOriginType.USER] = MessageOriginType.USER, + date: DateTime, + sender_user: User, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, date=date, sender_user=sender_user, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/message_reaction_count_updated.py b/env/Lib/site-packages/aiogram/types/message_reaction_count_updated.py new file mode 100644 index 0000000..e9d0f8b --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_reaction_count_updated.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat import Chat + from .custom import DateTime + from .reaction_count import ReactionCount + + +class MessageReactionCountUpdated(TelegramObject): + """ + This object represents reaction changes on a message with anonymous reactions. + + Source: https://core.telegram.org/bots/api#messagereactioncountupdated + """ + + chat: Chat + """The chat containing the message""" + message_id: int + """Unique message identifier inside the chat""" + date: DateTime + """Date of the change in Unix time""" + reactions: List[ReactionCount] + """List of reactions that are present on the message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat: Chat, + message_id: int, + date: DateTime, + reactions: List[ReactionCount], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat=chat, + message_id=message_id, + date=date, + reactions=reactions, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/message_reaction_updated.py b/env/Lib/site-packages/aiogram/types/message_reaction_updated.py new file mode 100644 index 0000000..7831c77 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/message_reaction_updated.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat import Chat + from .custom import DateTime + from .reaction_type_custom_emoji import ReactionTypeCustomEmoji + from .reaction_type_emoji import ReactionTypeEmoji + from .reaction_type_paid import ReactionTypePaid + from .user import User + + +class MessageReactionUpdated(TelegramObject): + """ + This object represents a change of a reaction on a message performed by a user. + + Source: https://core.telegram.org/bots/api#messagereactionupdated + """ + + chat: Chat + """The chat containing the message the user reacted to""" + message_id: int + """Unique identifier of the message inside the chat""" + date: DateTime + """Date of the change in Unix time""" + old_reaction: List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + """Previous list of reaction types that were set by the user""" + new_reaction: List[Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid]] + """New list of reaction types that have been set by the user""" + user: Optional[User] = None + """*Optional*. The user that changed the reaction, if the user isn't anonymous""" + actor_chat: Optional[Chat] = None + """*Optional*. The chat on behalf of which the reaction was changed, if the user is anonymous""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + chat: Chat, + message_id: int, + date: DateTime, + old_reaction: List[ + Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid] + ], + new_reaction: List[ + Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid] + ], + user: Optional[User] = None, + actor_chat: Optional[Chat] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + chat=chat, + message_id=message_id, + date=date, + old_reaction=old_reaction, + new_reaction=new_reaction, + user=user, + actor_chat=actor_chat, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/order_info.py b/env/Lib/site-packages/aiogram/types/order_info.py new file mode 100644 index 0000000..5d71f65 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/order_info.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .shipping_address import ShippingAddress + + +class OrderInfo(TelegramObject): + """ + This object represents information about an order. + + Source: https://core.telegram.org/bots/api#orderinfo + """ + + name: Optional[str] = None + """*Optional*. User name""" + phone_number: Optional[str] = None + """*Optional*. User's phone number""" + email: Optional[str] = None + """*Optional*. User email""" + shipping_address: Optional[ShippingAddress] = None + """*Optional*. User shipping address""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + name: Optional[str] = None, + phone_number: Optional[str] = None, + email: Optional[str] = None, + shipping_address: Optional[ShippingAddress] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + name=name, + phone_number=phone_number, + email=email, + shipping_address=shipping_address, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/paid_media.py b/env/Lib/site-packages/aiogram/types/paid_media.py new file mode 100644 index 0000000..d17c44d --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/paid_media.py @@ -0,0 +1,13 @@ +from .base import TelegramObject + + +class PaidMedia(TelegramObject): + """ + This object describes paid media. Currently, it can be one of + + - :class:`aiogram.types.paid_media_preview.PaidMediaPreview` + - :class:`aiogram.types.paid_media_photo.PaidMediaPhoto` + - :class:`aiogram.types.paid_media_video.PaidMediaVideo` + + Source: https://core.telegram.org/bots/api#paidmedia + """ diff --git a/env/Lib/site-packages/aiogram/types/paid_media_info.py b/env/Lib/site-packages/aiogram/types/paid_media_info.py new file mode 100644 index 0000000..db5bbf0 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/paid_media_info.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Union + +from .base import TelegramObject + +if TYPE_CHECKING: + from .paid_media_photo import PaidMediaPhoto + from .paid_media_preview import PaidMediaPreview + from .paid_media_video import PaidMediaVideo + + +class PaidMediaInfo(TelegramObject): + """ + Describes the paid media added to a message. + + Source: https://core.telegram.org/bots/api#paidmediainfo + """ + + star_count: int + """The number of Telegram Stars that must be paid to buy access to the media""" + paid_media: List[Union[PaidMediaPreview, PaidMediaPhoto, PaidMediaVideo]] + """Information about the paid media""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + star_count: int, + paid_media: List[Union[PaidMediaPreview, PaidMediaPhoto, PaidMediaVideo]], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(star_count=star_count, paid_media=paid_media, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/paid_media_photo.py b/env/Lib/site-packages/aiogram/types/paid_media_photo.py new file mode 100644 index 0000000..71c2e10 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/paid_media_photo.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal + +from ..enums import PaidMediaType +from .paid_media import PaidMedia + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class PaidMediaPhoto(PaidMedia): + """ + The paid media is a photo. + + Source: https://core.telegram.org/bots/api#paidmediaphoto + """ + + type: Literal[PaidMediaType.PHOTO] = PaidMediaType.PHOTO + """Type of the paid media, always 'photo'""" + photo: List[PhotoSize] + """The photo""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[PaidMediaType.PHOTO] = PaidMediaType.PHOTO, + photo: List[PhotoSize], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, photo=photo, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/paid_media_preview.py b/env/Lib/site-packages/aiogram/types/paid_media_preview.py new file mode 100644 index 0000000..5054de2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/paid_media_preview.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from ..enums import PaidMediaType +from .paid_media import PaidMedia + + +class PaidMediaPreview(PaidMedia): + """ + The paid media isn't available before the payment. + + Source: https://core.telegram.org/bots/api#paidmediapreview + """ + + type: Literal[PaidMediaType.PREVIEW] = PaidMediaType.PREVIEW + """Type of the paid media, always 'preview'""" + width: Optional[int] = None + """*Optional*. Media width as defined by the sender""" + height: Optional[int] = None + """*Optional*. Media height as defined by the sender""" + duration: Optional[int] = None + """*Optional*. Duration of the media in seconds as defined by the sender""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[PaidMediaType.PREVIEW] = PaidMediaType.PREVIEW, + width: Optional[int] = None, + height: Optional[int] = None, + duration: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, width=width, height=height, duration=duration, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/paid_media_video.py b/env/Lib/site-packages/aiogram/types/paid_media_video.py new file mode 100644 index 0000000..28affbb --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/paid_media_video.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import PaidMediaType +from .paid_media import PaidMedia + +if TYPE_CHECKING: + from .video import Video + + +class PaidMediaVideo(PaidMedia): + """ + The paid media is a video. + + Source: https://core.telegram.org/bots/api#paidmediavideo + """ + + type: Literal[PaidMediaType.VIDEO] = PaidMediaType.VIDEO + """Type of the paid media, always 'video'""" + video: Video + """The video""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[PaidMediaType.VIDEO] = PaidMediaType.VIDEO, + video: Video, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, video=video, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/passport_data.py b/env/Lib/site-packages/aiogram/types/passport_data.py new file mode 100644 index 0000000..d93af1f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_data.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .encrypted_credentials import EncryptedCredentials + from .encrypted_passport_element import EncryptedPassportElement + + +class PassportData(TelegramObject): + """ + Describes Telegram Passport data shared with the bot by the user. + + Source: https://core.telegram.org/bots/api#passportdata + """ + + data: List[EncryptedPassportElement] + """Array with information about documents and other Telegram Passport elements that was shared with the bot""" + credentials: EncryptedCredentials + """Encrypted credentials required to decrypt the data""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + data: List[EncryptedPassportElement], + credentials: EncryptedCredentials, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(data=data, credentials=credentials, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error.py b/env/Lib/site-packages/aiogram/types/passport_element_error.py new file mode 100644 index 0000000..36a1db8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +from .base import MutableTelegramObject + + +class PassportElementError(MutableTelegramObject): + """ + This object represents an error in the Telegram Passport element which was submitted that should be resolved by the user. It should be one of: + + - :class:`aiogram.types.passport_element_error_data_field.PassportElementErrorDataField` + - :class:`aiogram.types.passport_element_error_front_side.PassportElementErrorFrontSide` + - :class:`aiogram.types.passport_element_error_reverse_side.PassportElementErrorReverseSide` + - :class:`aiogram.types.passport_element_error_selfie.PassportElementErrorSelfie` + - :class:`aiogram.types.passport_element_error_file.PassportElementErrorFile` + - :class:`aiogram.types.passport_element_error_files.PassportElementErrorFiles` + - :class:`aiogram.types.passport_element_error_translation_file.PassportElementErrorTranslationFile` + - :class:`aiogram.types.passport_element_error_translation_files.PassportElementErrorTranslationFiles` + - :class:`aiogram.types.passport_element_error_unspecified.PassportElementErrorUnspecified` + + Source: https://core.telegram.org/bots/api#passportelementerror + """ diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_data_field.py b/env/Lib/site-packages/aiogram/types/passport_element_error_data_field.py new file mode 100644 index 0000000..3bf2bb2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_data_field.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorDataField(PassportElementError): + """ + Represents an issue in one of the data fields that was provided by the user. The error is considered resolved when the field's value changes. + + Source: https://core.telegram.org/bots/api#passportelementerrordatafield + """ + + source: Literal[PassportElementErrorType.DATA] = PassportElementErrorType.DATA + """Error source, must be *data*""" + type: str + """The section of the user's Telegram Passport which has the error, one of 'personal_details', 'passport', 'driver_license', 'identity_card', 'internal_passport', 'address'""" + field_name: str + """Name of the data field which has the error""" + data_hash: str + """Base64-encoded data hash""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[PassportElementErrorType.DATA] = PassportElementErrorType.DATA, + type: str, + field_name: str, + data_hash: str, + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, + type=type, + field_name=field_name, + data_hash=data_hash, + message=message, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_file.py b/env/Lib/site-packages/aiogram/types/passport_element_error_file.py new file mode 100644 index 0000000..8bc40b3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_file.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorFile(PassportElementError): + """ + Represents an issue with a document scan. The error is considered resolved when the file with the document scan changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorfile + """ + + source: Literal[PassportElementErrorType.FILE] = PassportElementErrorType.FILE + """Error source, must be *file*""" + type: str + """The section of the user's Telegram Passport which has the issue, one of 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration'""" + file_hash: str + """Base64-encoded file hash""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[PassportElementErrorType.FILE] = PassportElementErrorType.FILE, + type: str, + file_hash: str, + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, type=type, file_hash=file_hash, message=message, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_files.py b/env/Lib/site-packages/aiogram/types/passport_element_error_files.py new file mode 100644 index 0000000..3639da2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_files.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorFiles(PassportElementError): + """ + Represents an issue with a list of scans. The error is considered resolved when the list of files containing the scans changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorfiles + """ + + source: Literal[PassportElementErrorType.FILES] = PassportElementErrorType.FILES + """Error source, must be *files*""" + type: str + """The section of the user's Telegram Passport which has the issue, one of 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration'""" + file_hashes: List[str] + """List of base64-encoded file hashes""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[PassportElementErrorType.FILES] = PassportElementErrorType.FILES, + type: str, + file_hashes: List[str], + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, + type=type, + file_hashes=file_hashes, + message=message, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_front_side.py b/env/Lib/site-packages/aiogram/types/passport_element_error_front_side.py new file mode 100644 index 0000000..86315f2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_front_side.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorFrontSide(PassportElementError): + """ + Represents an issue with the front side of a document. The error is considered resolved when the file with the front side of the document changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorfrontside + """ + + source: Literal[PassportElementErrorType.FRONT_SIDE] = PassportElementErrorType.FRONT_SIDE + """Error source, must be *front_side*""" + type: str + """The section of the user's Telegram Passport which has the issue, one of 'passport', 'driver_license', 'identity_card', 'internal_passport'""" + file_hash: str + """Base64-encoded hash of the file with the front side of the document""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[ + PassportElementErrorType.FRONT_SIDE + ] = PassportElementErrorType.FRONT_SIDE, + type: str, + file_hash: str, + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, type=type, file_hash=file_hash, message=message, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_reverse_side.py b/env/Lib/site-packages/aiogram/types/passport_element_error_reverse_side.py new file mode 100644 index 0000000..ecb400f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_reverse_side.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorReverseSide(PassportElementError): + """ + Represents an issue with the reverse side of a document. The error is considered resolved when the file with reverse side of the document changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorreverseside + """ + + source: Literal[PassportElementErrorType.REVERSE_SIDE] = PassportElementErrorType.REVERSE_SIDE + """Error source, must be *reverse_side*""" + type: str + """The section of the user's Telegram Passport which has the issue, one of 'driver_license', 'identity_card'""" + file_hash: str + """Base64-encoded hash of the file with the reverse side of the document""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[ + PassportElementErrorType.REVERSE_SIDE + ] = PassportElementErrorType.REVERSE_SIDE, + type: str, + file_hash: str, + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, type=type, file_hash=file_hash, message=message, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_selfie.py b/env/Lib/site-packages/aiogram/types/passport_element_error_selfie.py new file mode 100644 index 0000000..bff6dd6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_selfie.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorSelfie(PassportElementError): + """ + Represents an issue with the selfie with a document. The error is considered resolved when the file with the selfie changes. + + Source: https://core.telegram.org/bots/api#passportelementerrorselfie + """ + + source: Literal[PassportElementErrorType.SELFIE] = PassportElementErrorType.SELFIE + """Error source, must be *selfie*""" + type: str + """The section of the user's Telegram Passport which has the issue, one of 'passport', 'driver_license', 'identity_card', 'internal_passport'""" + file_hash: str + """Base64-encoded hash of the file with the selfie""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[PassportElementErrorType.SELFIE] = PassportElementErrorType.SELFIE, + type: str, + file_hash: str, + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, type=type, file_hash=file_hash, message=message, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_translation_file.py b/env/Lib/site-packages/aiogram/types/passport_element_error_translation_file.py new file mode 100644 index 0000000..29689ca --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_translation_file.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorTranslationFile(PassportElementError): + """ + Represents an issue with one of the files that constitute the translation of a document. The error is considered resolved when the file changes. + + Source: https://core.telegram.org/bots/api#passportelementerrortranslationfile + """ + + source: Literal[PassportElementErrorType.TRANSLATION_FILE] = ( + PassportElementErrorType.TRANSLATION_FILE + ) + """Error source, must be *translation_file*""" + type: str + """Type of element of the user's Telegram Passport which has the issue, one of 'passport', 'driver_license', 'identity_card', 'internal_passport', 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration'""" + file_hash: str + """Base64-encoded file hash""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[ + PassportElementErrorType.TRANSLATION_FILE + ] = PassportElementErrorType.TRANSLATION_FILE, + type: str, + file_hash: str, + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, type=type, file_hash=file_hash, message=message, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_translation_files.py b/env/Lib/site-packages/aiogram/types/passport_element_error_translation_files.py new file mode 100644 index 0000000..65e9940 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_translation_files.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorTranslationFiles(PassportElementError): + """ + Represents an issue with the translated version of a document. The error is considered resolved when a file with the document translation change. + + Source: https://core.telegram.org/bots/api#passportelementerrortranslationfiles + """ + + source: Literal[PassportElementErrorType.TRANSLATION_FILES] = ( + PassportElementErrorType.TRANSLATION_FILES + ) + """Error source, must be *translation_files*""" + type: str + """Type of element of the user's Telegram Passport which has the issue, one of 'passport', 'driver_license', 'identity_card', 'internal_passport', 'utility_bill', 'bank_statement', 'rental_agreement', 'passport_registration', 'temporary_registration'""" + file_hashes: List[str] + """List of base64-encoded file hashes""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[ + PassportElementErrorType.TRANSLATION_FILES + ] = PassportElementErrorType.TRANSLATION_FILES, + type: str, + file_hashes: List[str], + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, + type=type, + file_hashes=file_hashes, + message=message, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_element_error_unspecified.py b/env/Lib/site-packages/aiogram/types/passport_element_error_unspecified.py new file mode 100644 index 0000000..3575d35 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_element_error_unspecified.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import PassportElementErrorType +from .passport_element_error import PassportElementError + + +class PassportElementErrorUnspecified(PassportElementError): + """ + Represents an issue in an unspecified place. The error is considered resolved when new data is added. + + Source: https://core.telegram.org/bots/api#passportelementerrorunspecified + """ + + source: Literal[PassportElementErrorType.UNSPECIFIED] = PassportElementErrorType.UNSPECIFIED + """Error source, must be *unspecified*""" + type: str + """Type of element of the user's Telegram Passport which has the issue""" + element_hash: str + """Base64-encoded element hash""" + message: str + """Error message""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + source: Literal[ + PassportElementErrorType.UNSPECIFIED + ] = PassportElementErrorType.UNSPECIFIED, + type: str, + element_hash: str, + message: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + source=source, + type=type, + element_hash=element_hash, + message=message, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/passport_file.py b/env/Lib/site-packages/aiogram/types/passport_file.py new file mode 100644 index 0000000..d95da61 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/passport_file.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject +from .custom import DateTime + + +class PassportFile(TelegramObject): + """ + This object represents a file uploaded to Telegram Passport. Currently all Telegram Passport files are in JPEG format when decrypted and don't exceed 10MB. + + Source: https://core.telegram.org/bots/api#passportfile + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + file_size: int + """File size in bytes""" + file_date: DateTime + """Unix time when the file was uploaded""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + file_size: int, + file_date: DateTime, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + file_size=file_size, + file_date=file_date, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/photo_size.py b/env/Lib/site-packages/aiogram/types/photo_size.py new file mode 100644 index 0000000..9a2ccbe --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/photo_size.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class PhotoSize(TelegramObject): + """ + This object represents one size of a photo or a `file `_ / :class:`aiogram.methods.sticker.Sticker` thumbnail. + + Source: https://core.telegram.org/bots/api#photosize + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + width: int + """Photo width""" + height: int + """Photo height""" + file_size: Optional[int] = None + """*Optional*. File size in bytes""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + width: int, + height: int, + file_size: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + width=width, + height=height, + file_size=file_size, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/poll.py b/env/Lib/site-packages/aiogram/types/poll.py new file mode 100644 index 0000000..5805224 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/poll.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from .message_entity import MessageEntity + from .poll_option import PollOption + + +class Poll(TelegramObject): + """ + This object contains information about a poll. + + Source: https://core.telegram.org/bots/api#poll + """ + + id: str + """Unique poll identifier""" + question: str + """Poll question, 1-300 characters""" + options: List[PollOption] + """List of poll options""" + total_voter_count: int + """Total number of users that voted in the poll""" + is_closed: bool + """:code:`True`, if the poll is closed""" + is_anonymous: bool + """:code:`True`, if the poll is anonymous""" + type: str + """Poll type, currently can be 'regular' or 'quiz'""" + allows_multiple_answers: bool + """:code:`True`, if the poll allows multiple answers""" + question_entities: Optional[List[MessageEntity]] = None + """*Optional*. Special entities that appear in the *question*. Currently, only custom emoji entities are allowed in poll questions""" + correct_option_id: Optional[int] = None + """*Optional*. 0-based identifier of the correct answer option. Available only for polls in the quiz mode, which are closed, or was sent (not forwarded) by the bot or to the private chat with the bot.""" + explanation: Optional[str] = None + """*Optional*. Text that is shown when a user chooses an incorrect answer or taps on the lamp icon in a quiz-style poll, 0-200 characters""" + explanation_entities: Optional[List[MessageEntity]] = None + """*Optional*. Special entities like usernames, URLs, bot commands, etc. that appear in the *explanation*""" + open_period: Optional[int] = None + """*Optional*. Amount of time in seconds the poll will be active after creation""" + close_date: Optional[DateTime] = None + """*Optional*. Point in time (Unix timestamp) when the poll will be automatically closed""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: str, + question: str, + options: List[PollOption], + total_voter_count: int, + is_closed: bool, + is_anonymous: bool, + type: str, + allows_multiple_answers: bool, + question_entities: Optional[List[MessageEntity]] = None, + correct_option_id: Optional[int] = None, + explanation: Optional[str] = None, + explanation_entities: Optional[List[MessageEntity]] = None, + open_period: Optional[int] = None, + close_date: Optional[DateTime] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + question=question, + options=options, + total_voter_count=total_voter_count, + is_closed=is_closed, + is_anonymous=is_anonymous, + type=type, + allows_multiple_answers=allows_multiple_answers, + question_entities=question_entities, + correct_option_id=correct_option_id, + explanation=explanation, + explanation_entities=explanation_entities, + open_period=open_period, + close_date=close_date, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/poll_answer.py b/env/Lib/site-packages/aiogram/types/poll_answer.py new file mode 100644 index 0000000..c12be34 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/poll_answer.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat import Chat + from .user import User + + +class PollAnswer(TelegramObject): + """ + This object represents an answer of a user in a non-anonymous poll. + + Source: https://core.telegram.org/bots/api#pollanswer + """ + + poll_id: str + """Unique poll identifier""" + option_ids: List[int] + """0-based identifiers of chosen answer options. May be empty if the vote was retracted.""" + voter_chat: Optional[Chat] = None + """*Optional*. The chat that changed the answer to the poll, if the voter is anonymous""" + user: Optional[User] = None + """*Optional*. The user that changed the answer to the poll, if the voter isn't anonymous""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + poll_id: str, + option_ids: List[int], + voter_chat: Optional[Chat] = None, + user: Optional[User] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + poll_id=poll_id, + option_ids=option_ids, + voter_chat=voter_chat, + user=user, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/poll_option.py b/env/Lib/site-packages/aiogram/types/poll_option.py new file mode 100644 index 0000000..f380934 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/poll_option.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .message_entity import MessageEntity + + +class PollOption(TelegramObject): + """ + This object contains information about one answer option in a poll. + + Source: https://core.telegram.org/bots/api#polloption + """ + + text: str + """Option text, 1-100 characters""" + voter_count: int + """Number of users that voted for this option""" + text_entities: Optional[List[MessageEntity]] = None + """*Optional*. Special entities that appear in the option *text*. Currently, only custom emoji entities are allowed in poll option texts""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + text: str, + voter_count: int, + text_entities: Optional[List[MessageEntity]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + text=text, + voter_count=voter_count, + text_entities=text_entities, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/pre_checkout_query.py b/env/Lib/site-packages/aiogram/types/pre_checkout_query.py new file mode 100644 index 0000000..41bda8c --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/pre_checkout_query.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from pydantic import Field + +from .base import TelegramObject + +if TYPE_CHECKING: + from ..methods import AnswerPreCheckoutQuery + from .order_info import OrderInfo + from .user import User + + +class PreCheckoutQuery(TelegramObject): + """ + This object contains information about an incoming pre-checkout query. + + Source: https://core.telegram.org/bots/api#precheckoutquery + """ + + id: str + """Unique query identifier""" + from_user: User = Field(..., alias="from") + """User who sent the query""" + currency: str + """Three-letter ISO 4217 `currency `_ code, or 'XTR' for payments in `Telegram Stars `_""" + total_amount: int + """Total price in the *smallest units* of the currency (integer, **not** float/double). For example, for a price of :code:`US$ 1.45` pass :code:`amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + invoice_payload: str + """Bot-specified invoice payload""" + shipping_option_id: Optional[str] = None + """*Optional*. Identifier of the shipping option chosen by the user""" + order_info: Optional[OrderInfo] = None + """*Optional*. Order information provided by the user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: str, + from_user: User, + currency: str, + total_amount: int, + invoice_payload: str, + shipping_option_id: Optional[str] = None, + order_info: Optional[OrderInfo] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + from_user=from_user, + currency=currency, + total_amount=total_amount, + invoice_payload=invoice_payload, + shipping_option_id=shipping_option_id, + order_info=order_info, + **__pydantic_kwargs, + ) + + def answer( + self, + ok: bool, + error_message: Optional[str] = None, + **kwargs: Any, + ) -> AnswerPreCheckoutQuery: + """ + Shortcut for method :class:`aiogram.methods.answer_pre_checkout_query.AnswerPreCheckoutQuery` + will automatically fill method attributes: + + - :code:`pre_checkout_query_id` + + Once the user has confirmed their payment and shipping details, the Bot API sends the final confirmation in the form of an :class:`aiogram.types.update.Update` with the field *pre_checkout_query*. Use this method to respond to such pre-checkout queries. On success, :code:`True` is returned. **Note:** The Bot API must receive an answer within 10 seconds after the pre-checkout query was sent. + + Source: https://core.telegram.org/bots/api#answerprecheckoutquery + + :param ok: Specify :code:`True` if everything is alright (goods are available, etc.) and the bot is ready to proceed with the order. Use :code:`False` if there are any problems. + :param error_message: Required if *ok* is :code:`False`. Error message in human readable form that explains the reason for failure to proceed with the checkout (e.g. "Sorry, somebody just bought the last of our amazing black T-shirts while you were busy filling out your payment details. Please choose a different color or garment!"). Telegram will display this message to the user. + :return: instance of method :class:`aiogram.methods.answer_pre_checkout_query.AnswerPreCheckoutQuery` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import AnswerPreCheckoutQuery + + return AnswerPreCheckoutQuery( + pre_checkout_query_id=self.id, + ok=ok, + error_message=error_message, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/proximity_alert_triggered.py b/env/Lib/site-packages/aiogram/types/proximity_alert_triggered.py new file mode 100644 index 0000000..f5a30c6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/proximity_alert_triggered.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + +if TYPE_CHECKING: + from .user import User + + +class ProximityAlertTriggered(TelegramObject): + """ + This object represents the content of a service message, sent whenever a user in the chat triggers a proximity alert set by another user. + + Source: https://core.telegram.org/bots/api#proximityalerttriggered + """ + + traveler: User + """User that triggered the alert""" + watcher: User + """User that set the alert""" + distance: int + """The distance between the users""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + traveler: User, + watcher: User, + distance: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + traveler=traveler, watcher=watcher, distance=distance, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/reaction_count.py b/env/Lib/site-packages/aiogram/types/reaction_count.py new file mode 100644 index 0000000..e4ee167 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/reaction_count.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Union + +from .base import TelegramObject + +if TYPE_CHECKING: + from .reaction_type_custom_emoji import ReactionTypeCustomEmoji + from .reaction_type_emoji import ReactionTypeEmoji + from .reaction_type_paid import ReactionTypePaid + + +class ReactionCount(TelegramObject): + """ + Represents a reaction added to a message along with the number of times it was added. + + Source: https://core.telegram.org/bots/api#reactioncount + """ + + type: Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid] + """Type of the reaction""" + total_count: int + """Number of times the reaction was added""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Union[ReactionTypeEmoji, ReactionTypeCustomEmoji, ReactionTypePaid], + total_count: int, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, total_count=total_count, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/reaction_type.py b/env/Lib/site-packages/aiogram/types/reaction_type.py new file mode 100644 index 0000000..335d35d --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/reaction_type.py @@ -0,0 +1,13 @@ +from .base import TelegramObject + + +class ReactionType(TelegramObject): + """ + This object describes the type of a reaction. Currently, it can be one of + + - :class:`aiogram.types.reaction_type_emoji.ReactionTypeEmoji` + - :class:`aiogram.types.reaction_type_custom_emoji.ReactionTypeCustomEmoji` + - :class:`aiogram.types.reaction_type_paid.ReactionTypePaid` + + Source: https://core.telegram.org/bots/api#reactiontype + """ diff --git a/env/Lib/site-packages/aiogram/types/reaction_type_custom_emoji.py b/env/Lib/site-packages/aiogram/types/reaction_type_custom_emoji.py new file mode 100644 index 0000000..c86ec5e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/reaction_type_custom_emoji.py @@ -0,0 +1,34 @@ +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import ReactionTypeType +from .reaction_type import ReactionType + + +class ReactionTypeCustomEmoji(ReactionType): + """ + The reaction is based on a custom emoji. + + Source: https://core.telegram.org/bots/api#reactiontypecustomemoji + """ + + type: Literal[ReactionTypeType.CUSTOM_EMOJI] = ReactionTypeType.CUSTOM_EMOJI + """Type of the reaction, always 'custom_emoji'""" + custom_emoji_id: str + """Custom emoji identifier""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[ReactionTypeType.CUSTOM_EMOJI] = ReactionTypeType.CUSTOM_EMOJI, + custom_emoji_id: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, custom_emoji_id=custom_emoji_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/reaction_type_emoji.py b/env/Lib/site-packages/aiogram/types/reaction_type_emoji.py new file mode 100644 index 0000000..a209fe2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/reaction_type_emoji.py @@ -0,0 +1,34 @@ +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import ReactionTypeType +from .reaction_type import ReactionType + + +class ReactionTypeEmoji(ReactionType): + """ + The reaction is based on an emoji. + + Source: https://core.telegram.org/bots/api#reactiontypeemoji + """ + + type: Literal[ReactionTypeType.EMOJI] = ReactionTypeType.EMOJI + """Type of the reaction, always 'emoji'""" + emoji: str + """Reaction emoji. Currently, it can be one of "👍", "👎", "❤", "🔥", "🥰", "👏", "😁", "🤔", "🤯", "😱", "🤬", "😢", "🎉", "🤩", "🤮", "💩", "🙏", "👌", "🕊", "🤡", "🥱", "🥴", "😍", "🐳", "❤‍🔥", "🌚", "🌭", "💯", "🤣", "⚡", "🍌", "🏆", "💔", "🤨", "😐", "🍓", "🍾", "💋", "🖕", "😈", "😴", "😭", "🤓", "👻", "👨‍💻", "👀", "🎃", "🙈", "😇", "😨", "🤝", "✍", "🤗", "🫡", "🎅", "🎄", "☃", "💅", "🤪", "🗿", "🆒", "💘", "🙉", "🦄", "😘", "💊", "🙊", "😎", "👾", "🤷‍♂", "🤷", "🤷‍♀", "😡" """ + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[ReactionTypeType.EMOJI] = ReactionTypeType.EMOJI, + emoji: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, emoji=emoji, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/reaction_type_paid.py b/env/Lib/site-packages/aiogram/types/reaction_type_paid.py new file mode 100644 index 0000000..8e95a83 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/reaction_type_paid.py @@ -0,0 +1,28 @@ +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import ReactionTypeType +from .reaction_type import ReactionType + + +class ReactionTypePaid(ReactionType): + """ + The reaction is paid. + + Source: https://core.telegram.org/bots/api#reactiontypepaid + """ + + type: Literal["paid"] = "paid" + """Type of the reaction, always 'paid'""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, type: Literal["paid"] = "paid", **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/refunded_payment.py b/env/Lib/site-packages/aiogram/types/refunded_payment.py new file mode 100644 index 0000000..8b889dc --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/refunded_payment.py @@ -0,0 +1,49 @@ +from typing import TYPE_CHECKING, Any, Literal, Optional + +from .base import TelegramObject + + +class RefundedPayment(TelegramObject): + """ + This object contains basic information about a refunded payment. + + Source: https://core.telegram.org/bots/api#refundedpayment + """ + + currency: Literal["XTR"] = "XTR" + """Three-letter ISO 4217 `currency `_ code, or 'XTR' for payments in `Telegram Stars `_. Currently, always 'XTR'""" + total_amount: int + """Total refunded price in the *smallest units* of the currency (integer, **not** float/double). For example, for a price of :code:`US$ 1.45`, :code:`total_amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + invoice_payload: str + """Bot-specified invoice payload""" + telegram_payment_charge_id: str + """Telegram payment identifier""" + provider_payment_charge_id: Optional[str] = None + """*Optional*. Provider payment identifier""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + currency: Literal["XTR"] = "XTR", + total_amount: int, + invoice_payload: str, + telegram_payment_charge_id: str, + provider_payment_charge_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + currency=currency, + total_amount=total_amount, + invoice_payload=invoice_payload, + telegram_payment_charge_id=telegram_payment_charge_id, + provider_payment_charge_id=provider_payment_charge_id, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/reply_keyboard_markup.py b/env/Lib/site-packages/aiogram/types/reply_keyboard_markup.py new file mode 100644 index 0000000..f3d6dab --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/reply_keyboard_markup.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import MutableTelegramObject + +if TYPE_CHECKING: + from .keyboard_button import KeyboardButton + + +class ReplyKeyboardMarkup(MutableTelegramObject): + """ + This object represents a `custom keyboard `_ with reply options (see `Introduction to bots `_ for details and examples). Not supported in channels and for messages sent on behalf of a Telegram Business account. + + Source: https://core.telegram.org/bots/api#replykeyboardmarkup + """ + + keyboard: List[List[KeyboardButton]] + """Array of button rows, each represented by an Array of :class:`aiogram.types.keyboard_button.KeyboardButton` objects""" + is_persistent: Optional[bool] = None + """*Optional*. Requests clients to always show the keyboard when the regular keyboard is hidden. Defaults to *false*, in which case the custom keyboard can be hidden and opened with a keyboard icon.""" + resize_keyboard: Optional[bool] = None + """*Optional*. Requests clients to resize the keyboard vertically for optimal fit (e.g., make the keyboard smaller if there are just two rows of buttons). Defaults to *false*, in which case the custom keyboard is always of the same height as the app's standard keyboard.""" + one_time_keyboard: Optional[bool] = None + """*Optional*. Requests clients to hide the keyboard as soon as it's been used. The keyboard will still be available, but clients will automatically display the usual letter-keyboard in the chat - the user can press a special button in the input field to see the custom keyboard again. Defaults to *false*.""" + input_field_placeholder: Optional[str] = None + """*Optional*. The placeholder to be shown in the input field when the keyboard is active; 1-64 characters""" + selective: Optional[bool] = None + """*Optional*. Use this parameter if you want to show the keyboard to specific users only. Targets: 1) users that are @mentioned in the *text* of the :class:`aiogram.types.message.Message` object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + keyboard: List[List[KeyboardButton]], + is_persistent: Optional[bool] = None, + resize_keyboard: Optional[bool] = None, + one_time_keyboard: Optional[bool] = None, + input_field_placeholder: Optional[str] = None, + selective: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + keyboard=keyboard, + is_persistent=is_persistent, + resize_keyboard=resize_keyboard, + one_time_keyboard=one_time_keyboard, + input_field_placeholder=input_field_placeholder, + selective=selective, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/reply_keyboard_remove.py b/env/Lib/site-packages/aiogram/types/reply_keyboard_remove.py new file mode 100644 index 0000000..9c135a1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/reply_keyboard_remove.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional + +from .base import MutableTelegramObject + + +class ReplyKeyboardRemove(MutableTelegramObject): + """ + Upon receiving a message with this object, Telegram clients will remove the current custom keyboard and display the default letter-keyboard. By default, custom keyboards are displayed until a new keyboard is sent by a bot. An exception is made for one-time keyboards that are hidden immediately after the user presses a button (see :class:`aiogram.types.reply_keyboard_markup.ReplyKeyboardMarkup`). Not supported in channels and for messages sent on behalf of a Telegram Business account. + + Source: https://core.telegram.org/bots/api#replykeyboardremove + """ + + remove_keyboard: Literal[True] = True + """Requests clients to remove the custom keyboard (user will not be able to summon this keyboard; if you want to hide the keyboard from sight but keep it accessible, use *one_time_keyboard* in :class:`aiogram.types.reply_keyboard_markup.ReplyKeyboardMarkup`)""" + selective: Optional[bool] = None + """*Optional*. Use this parameter if you want to remove the keyboard for specific users only. Targets: 1) users that are @mentioned in the *text* of the :class:`aiogram.types.message.Message` object; 2) if the bot's message is a reply to a message in the same chat and forum topic, sender of the original message.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + remove_keyboard: Literal[True] = True, + selective: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + remove_keyboard=remove_keyboard, selective=selective, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/reply_parameters.py b/env/Lib/site-packages/aiogram/types/reply_parameters.py new file mode 100644 index 0000000..5b03fda --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/reply_parameters.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional, Union + +from ..client.default import Default +from .base import TelegramObject + +if TYPE_CHECKING: + from .message_entity import MessageEntity + + +class ReplyParameters(TelegramObject): + """ + Describes reply parameters for the message that is being sent. + + Source: https://core.telegram.org/bots/api#replyparameters + """ + + message_id: int + """Identifier of the message that will be replied to in the current chat, or in the chat *chat_id* if it is specified""" + chat_id: Optional[Union[int, str]] = None + """*Optional*. If the message to be replied to is from a different chat, unique identifier for the chat or username of the channel (in the format :code:`@channelusername`). Not supported for messages sent on behalf of a business account.""" + allow_sending_without_reply: Optional[Union[bool, Default]] = Default( + "allow_sending_without_reply" + ) + """*Optional*. Pass :code:`True` if the message should be sent even if the specified message to be replied to is not found. Always :code:`False` for replies in another chat or forum topic. Always :code:`True` for messages sent on behalf of a business account.""" + quote: Optional[str] = None + """*Optional*. Quoted part of the message to be replied to; 0-1024 characters after entities parsing. The quote must be an exact substring of the message to be replied to, including *bold*, *italic*, *underline*, *strikethrough*, *spoiler*, and *custom_emoji* entities. The message will fail to send if the quote isn't found in the original message.""" + quote_parse_mode: Optional[Union[str, Default]] = Default("parse_mode") + """*Optional*. Mode for parsing entities in the quote. See `formatting options `_ for more details.""" + quote_entities: Optional[List[MessageEntity]] = None + """*Optional*. A JSON-serialized list of special entities that appear in the quote. It can be specified instead of *quote_parse_mode*.""" + quote_position: Optional[int] = None + """*Optional*. Position of the quote in the original message in UTF-16 code units""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + message_id: int, + chat_id: Optional[Union[int, str]] = None, + allow_sending_without_reply: Optional[Union[bool, Default]] = Default( + "allow_sending_without_reply" + ), + quote: Optional[str] = None, + quote_parse_mode: Optional[Union[str, Default]] = Default("parse_mode"), + quote_entities: Optional[List[MessageEntity]] = None, + quote_position: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + message_id=message_id, + chat_id=chat_id, + allow_sending_without_reply=allow_sending_without_reply, + quote=quote, + quote_parse_mode=quote_parse_mode, + quote_entities=quote_entities, + quote_position=quote_position, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/response_parameters.py b/env/Lib/site-packages/aiogram/types/response_parameters.py new file mode 100644 index 0000000..19fc54f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/response_parameters.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class ResponseParameters(TelegramObject): + """ + Describes why a request was unsuccessful. + + Source: https://core.telegram.org/bots/api#responseparameters + """ + + migrate_to_chat_id: Optional[int] = None + """*Optional*. The group has been migrated to a supergroup with the specified identifier. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this identifier.""" + retry_after: Optional[int] = None + """*Optional*. In case of exceeding flood control, the number of seconds left to wait before the request can be repeated""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + migrate_to_chat_id: Optional[int] = None, + retry_after: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + migrate_to_chat_id=migrate_to_chat_id, retry_after=retry_after, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state.py b/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state.py new file mode 100644 index 0000000..740323e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state.py @@ -0,0 +1,15 @@ +from __future__ import annotations + +from .base import TelegramObject + + +class RevenueWithdrawalState(TelegramObject): + """ + This object describes the state of a revenue withdrawal operation. Currently, it can be one of + + - :class:`aiogram.types.revenue_withdrawal_state_pending.RevenueWithdrawalStatePending` + - :class:`aiogram.types.revenue_withdrawal_state_succeeded.RevenueWithdrawalStateSucceeded` + - :class:`aiogram.types.revenue_withdrawal_state_failed.RevenueWithdrawalStateFailed` + + Source: https://core.telegram.org/bots/api#revenuewithdrawalstate + """ diff --git a/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_failed.py b/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_failed.py new file mode 100644 index 0000000..501a9ff --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_failed.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import RevenueWithdrawalStateType +from .revenue_withdrawal_state import RevenueWithdrawalState + + +class RevenueWithdrawalStateFailed(RevenueWithdrawalState): + """ + The withdrawal failed and the transaction was refunded. + + Source: https://core.telegram.org/bots/api#revenuewithdrawalstatefailed + """ + + type: Literal[RevenueWithdrawalStateType.FAILED] = RevenueWithdrawalStateType.FAILED + """Type of the state, always 'failed'""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[RevenueWithdrawalStateType.FAILED] = RevenueWithdrawalStateType.FAILED, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_pending.py b/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_pending.py new file mode 100644 index 0000000..c4e481f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_pending.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import RevenueWithdrawalStateType +from .revenue_withdrawal_state import RevenueWithdrawalState + + +class RevenueWithdrawalStatePending(RevenueWithdrawalState): + """ + The withdrawal is in progress. + + Source: https://core.telegram.org/bots/api#revenuewithdrawalstatepending + """ + + type: Literal[RevenueWithdrawalStateType.PENDING] = RevenueWithdrawalStateType.PENDING + """Type of the state, always 'pending'""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[RevenueWithdrawalStateType.PENDING] = RevenueWithdrawalStateType.PENDING, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_succeeded.py b/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_succeeded.py new file mode 100644 index 0000000..48d45f1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/revenue_withdrawal_state_succeeded.py @@ -0,0 +1,42 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import RevenueWithdrawalStateType +from .custom import DateTime +from .revenue_withdrawal_state import RevenueWithdrawalState + + +class RevenueWithdrawalStateSucceeded(RevenueWithdrawalState): + """ + The withdrawal succeeded. + + Source: https://core.telegram.org/bots/api#revenuewithdrawalstatesucceeded + """ + + type: Literal[RevenueWithdrawalStateType.SUCCEEDED] = RevenueWithdrawalStateType.SUCCEEDED + """Type of the state, always 'succeeded'""" + date: DateTime + """Date the withdrawal was completed in Unix time""" + url: str + """An HTTPS URL that can be used to see transaction details""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[ + RevenueWithdrawalStateType.SUCCEEDED + ] = RevenueWithdrawalStateType.SUCCEEDED, + date: DateTime, + url: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, date=date, url=url, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/sent_web_app_message.py b/env/Lib/site-packages/aiogram/types/sent_web_app_message.py new file mode 100644 index 0000000..e8241a5 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/sent_web_app_message.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class SentWebAppMessage(TelegramObject): + """ + Describes an inline message sent by a `Web App `_ on behalf of a user. + + Source: https://core.telegram.org/bots/api#sentwebappmessage + """ + + inline_message_id: Optional[str] = None + """*Optional*. Identifier of the sent inline message. Available only if there is an `inline keyboard `_ attached to the message.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + inline_message_id: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(inline_message_id=inline_message_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/shared_user.py b/env/Lib/site-packages/aiogram/types/shared_user.py new file mode 100644 index 0000000..e160b89 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/shared_user.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class SharedUser(TelegramObject): + """ + This object contains information about a user that was shared with the bot using a :class:`aiogram.types.keyboard_button_request_users.KeyboardButtonRequestUsers` button. + + Source: https://core.telegram.org/bots/api#shareduser + """ + + user_id: int + """Identifier of the shared user. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so 64-bit integers or double-precision float types are safe for storing these identifiers. The bot may not have access to the user and could be unable to use this identifier, unless the user is already known to the bot by some other means.""" + first_name: Optional[str] = None + """*Optional*. First name of the user, if the name was requested by the bot""" + last_name: Optional[str] = None + """*Optional*. Last name of the user, if the name was requested by the bot""" + username: Optional[str] = None + """*Optional*. Username of the user, if the username was requested by the bot""" + photo: Optional[List[PhotoSize]] = None + """*Optional*. Available sizes of the chat photo, if the photo was requested by the bot""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + user_id: int, + first_name: Optional[str] = None, + last_name: Optional[str] = None, + username: Optional[str] = None, + photo: Optional[List[PhotoSize]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + user_id=user_id, + first_name=first_name, + last_name=last_name, + username=username, + photo=photo, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/shipping_address.py b/env/Lib/site-packages/aiogram/types/shipping_address.py new file mode 100644 index 0000000..a8293cd --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/shipping_address.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class ShippingAddress(TelegramObject): + """ + This object represents a shipping address. + + Source: https://core.telegram.org/bots/api#shippingaddress + """ + + country_code: str + """Two-letter `ISO 3166-1 alpha-2 `_ country code""" + state: str + """State, if applicable""" + city: str + """City""" + street_line1: str + """First line for the address""" + street_line2: str + """Second line for the address""" + post_code: str + """Address post code""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + country_code: str, + state: str, + city: str, + street_line1: str, + street_line2: str, + post_code: str, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + country_code=country_code, + state=state, + city=city, + street_line1=street_line1, + street_line2=street_line2, + post_code=post_code, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/shipping_option.py b/env/Lib/site-packages/aiogram/types/shipping_option.py new file mode 100644 index 0000000..b027451 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/shipping_option.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .labeled_price import LabeledPrice + + +class ShippingOption(TelegramObject): + """ + This object represents one shipping option. + + Source: https://core.telegram.org/bots/api#shippingoption + """ + + id: str + """Shipping option identifier""" + title: str + """Option title""" + prices: List[LabeledPrice] + """List of price portions""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: str, + title: str, + prices: List[LabeledPrice], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(id=id, title=title, prices=prices, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/shipping_query.py b/env/Lib/site-packages/aiogram/types/shipping_query.py new file mode 100644 index 0000000..61b4ae4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/shipping_query.py @@ -0,0 +1,90 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from pydantic import Field + +from .base import TelegramObject + +if TYPE_CHECKING: + from ..methods import AnswerShippingQuery + from ..types import ShippingOption + from .shipping_address import ShippingAddress + from .user import User + + +class ShippingQuery(TelegramObject): + """ + This object contains information about an incoming shipping query. + + Source: https://core.telegram.org/bots/api#shippingquery + """ + + id: str + """Unique query identifier""" + from_user: User = Field(..., alias="from") + """User who sent the query""" + invoice_payload: str + """Bot-specified invoice payload""" + shipping_address: ShippingAddress + """User specified shipping address""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: str, + from_user: User, + invoice_payload: str, + shipping_address: ShippingAddress, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + from_user=from_user, + invoice_payload=invoice_payload, + shipping_address=shipping_address, + **__pydantic_kwargs, + ) + + def answer( + self, + ok: bool, + shipping_options: Optional[List[ShippingOption]] = None, + error_message: Optional[str] = None, + **kwargs: Any, + ) -> AnswerShippingQuery: + """ + Shortcut for method :class:`aiogram.methods.answer_shipping_query.AnswerShippingQuery` + will automatically fill method attributes: + + - :code:`shipping_query_id` + + If you sent an invoice requesting a shipping address and the parameter *is_flexible* was specified, the Bot API will send an :class:`aiogram.types.update.Update` with a *shipping_query* field to the bot. Use this method to reply to shipping queries. On success, :code:`True` is returned. + + Source: https://core.telegram.org/bots/api#answershippingquery + + :param ok: Pass :code:`True` if delivery to the specified address is possible and :code:`False` if there are any problems (for example, if delivery to the specified address is not possible) + :param shipping_options: Required if *ok* is :code:`True`. A JSON-serialized array of available shipping options. + :param error_message: Required if *ok* is :code:`False`. Error message in human readable form that explains why it is impossible to complete the order (e.g. "Sorry, delivery to your desired address is unavailable'). Telegram will display this message to the user. + :return: instance of method :class:`aiogram.methods.answer_shipping_query.AnswerShippingQuery` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import AnswerShippingQuery + + return AnswerShippingQuery( + shipping_query_id=self.id, + ok=ok, + shipping_options=shipping_options, + error_message=error_message, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/star_transaction.py b/env/Lib/site-packages/aiogram/types/star_transaction.py new file mode 100644 index 0000000..5d680af --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/star_transaction.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, Union + +from .base import TelegramObject +from .custom import DateTime + +if TYPE_CHECKING: + from .transaction_partner_fragment import TransactionPartnerFragment + from .transaction_partner_other import TransactionPartnerOther + from .transaction_partner_telegram_ads import TransactionPartnerTelegramAds + from .transaction_partner_user import TransactionPartnerUser + + +class StarTransaction(TelegramObject): + """ + Describes a Telegram Star transaction. + + Source: https://core.telegram.org/bots/api#startransaction + """ + + id: str + """Unique identifier of the transaction. Coincides with the identifer of the original transaction for refund transactions. Coincides with *SuccessfulPayment.telegram_payment_charge_id* for successful incoming payments from users.""" + amount: int + """Number of Telegram Stars transferred by the transaction""" + date: DateTime + """Date the transaction was created in Unix time""" + source: Optional[ + Union[ + TransactionPartnerUser, + TransactionPartnerFragment, + TransactionPartnerTelegramAds, + TransactionPartnerOther, + ] + ] = None + """*Optional*. Source of an incoming transaction (e.g., a user purchasing goods or services, Fragment refunding a failed withdrawal). Only for incoming transactions""" + receiver: Optional[ + Union[ + TransactionPartnerUser, + TransactionPartnerFragment, + TransactionPartnerTelegramAds, + TransactionPartnerOther, + ] + ] = None + """*Optional*. Receiver of an outgoing transaction (e.g., a user for a purchase refund, Fragment for a withdrawal). Only for outgoing transactions""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: str, + amount: int, + date: DateTime, + source: Optional[ + Union[ + TransactionPartnerUser, + TransactionPartnerFragment, + TransactionPartnerTelegramAds, + TransactionPartnerOther, + ] + ] = None, + receiver: Optional[ + Union[ + TransactionPartnerUser, + TransactionPartnerFragment, + TransactionPartnerTelegramAds, + TransactionPartnerOther, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + amount=amount, + date=date, + source=source, + receiver=receiver, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/star_transactions.py b/env/Lib/site-packages/aiogram/types/star_transactions.py new file mode 100644 index 0000000..d2ee5b0 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/star_transactions.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .star_transaction import StarTransaction + + +class StarTransactions(TelegramObject): + """ + Contains a list of Telegram Star transactions. + + Source: https://core.telegram.org/bots/api#startransactions + """ + + transactions: List[StarTransaction] + """The list of transactions""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, transactions: List[StarTransaction], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(transactions=transactions, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/sticker.py b/env/Lib/site-packages/aiogram/types/sticker.py new file mode 100644 index 0000000..4c1b864 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/sticker.py @@ -0,0 +1,152 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from ..methods import DeleteStickerFromSet, SetStickerPositionInSet + from .file import File + from .mask_position import MaskPosition + from .photo_size import PhotoSize + + +class Sticker(TelegramObject): + """ + This object represents a sticker. + + Source: https://core.telegram.org/bots/api#sticker + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + type: str + """Type of the sticker, currently one of 'regular', 'mask', 'custom_emoji'. The type of the sticker is independent from its format, which is determined by the fields *is_animated* and *is_video*.""" + width: int + """Sticker width""" + height: int + """Sticker height""" + is_animated: bool + """:code:`True`, if the sticker is `animated `_""" + is_video: bool + """:code:`True`, if the sticker is a `video sticker `_""" + thumbnail: Optional[PhotoSize] = None + """*Optional*. Sticker thumbnail in the .WEBP or .JPG format""" + emoji: Optional[str] = None + """*Optional*. Emoji associated with the sticker""" + set_name: Optional[str] = None + """*Optional*. Name of the sticker set to which the sticker belongs""" + premium_animation: Optional[File] = None + """*Optional*. For premium regular stickers, premium animation for the sticker""" + mask_position: Optional[MaskPosition] = None + """*Optional*. For mask stickers, the position where the mask should be placed""" + custom_emoji_id: Optional[str] = None + """*Optional*. For custom emoji stickers, unique identifier of the custom emoji""" + needs_repainting: Optional[bool] = None + """*Optional*. :code:`True`, if the sticker must be repainted to a text color in messages, the color of the Telegram Premium badge in emoji status, white color on chat photos, or another appropriate color in other places""" + file_size: Optional[int] = None + """*Optional*. File size in bytes""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + type: str, + width: int, + height: int, + is_animated: bool, + is_video: bool, + thumbnail: Optional[PhotoSize] = None, + emoji: Optional[str] = None, + set_name: Optional[str] = None, + premium_animation: Optional[File] = None, + mask_position: Optional[MaskPosition] = None, + custom_emoji_id: Optional[str] = None, + needs_repainting: Optional[bool] = None, + file_size: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + type=type, + width=width, + height=height, + is_animated=is_animated, + is_video=is_video, + thumbnail=thumbnail, + emoji=emoji, + set_name=set_name, + premium_animation=premium_animation, + mask_position=mask_position, + custom_emoji_id=custom_emoji_id, + needs_repainting=needs_repainting, + file_size=file_size, + **__pydantic_kwargs, + ) + + def set_position_in_set( + self, + position: int, + **kwargs: Any, + ) -> SetStickerPositionInSet: + """ + Shortcut for method :class:`aiogram.methods.set_sticker_position_in_set.SetStickerPositionInSet` + will automatically fill method attributes: + + - :code:`sticker` + + Use this method to move a sticker in a set created by the bot to a specific position. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#setstickerpositioninset + + :param position: New sticker position in the set, zero-based + :return: instance of method :class:`aiogram.methods.set_sticker_position_in_set.SetStickerPositionInSet` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import SetStickerPositionInSet + + return SetStickerPositionInSet( + sticker=self.file_id, + position=position, + **kwargs, + ).as_(self._bot) + + def delete_from_set( + self, + **kwargs: Any, + ) -> DeleteStickerFromSet: + """ + Shortcut for method :class:`aiogram.methods.delete_sticker_from_set.DeleteStickerFromSet` + will automatically fill method attributes: + + - :code:`sticker` + + Use this method to delete a sticker from a set created by the bot. Returns :code:`True` on success. + + Source: https://core.telegram.org/bots/api#deletestickerfromset + + :return: instance of method :class:`aiogram.methods.delete_sticker_from_set.DeleteStickerFromSet` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import DeleteStickerFromSet + + return DeleteStickerFromSet( + sticker=self.file_id, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/sticker_set.py b/env/Lib/site-packages/aiogram/types/sticker_set.py new file mode 100644 index 0000000..29f9962 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/sticker_set.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from pydantic import Field + +from .base import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + from .sticker import Sticker + + +class StickerSet(TelegramObject): + """ + This object represents a sticker set. + + Source: https://core.telegram.org/bots/api#stickerset + """ + + name: str + """Sticker set name""" + title: str + """Sticker set title""" + sticker_type: str + """Type of stickers in the set, currently one of 'regular', 'mask', 'custom_emoji'""" + stickers: List[Sticker] + """List of all set stickers""" + thumbnail: Optional[PhotoSize] = None + """*Optional*. Sticker set thumbnail in the .WEBP, .TGS, or .WEBM format""" + is_animated: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """:code:`True`, if the sticker set contains `animated stickers `_ + +.. deprecated:: API:7.2 + https://core.telegram.org/bots/api-changelog#march-31-2024""" + is_video: Optional[bool] = Field(None, json_schema_extra={"deprecated": True}) + """:code:`True`, if the sticker set contains `video stickers `_ + +.. deprecated:: API:7.2 + https://core.telegram.org/bots/api-changelog#march-31-2024""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + name: str, + title: str, + sticker_type: str, + stickers: List[Sticker], + thumbnail: Optional[PhotoSize] = None, + is_animated: Optional[bool] = None, + is_video: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + name=name, + title=title, + sticker_type=sticker_type, + stickers=stickers, + thumbnail=thumbnail, + is_animated=is_animated, + is_video=is_video, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/story.py b/env/Lib/site-packages/aiogram/types/story.py new file mode 100644 index 0000000..69aaaec --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/story.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat import Chat + + +class Story(TelegramObject): + """ + This object represents a story. + + Source: https://core.telegram.org/bots/api#story + """ + + chat: Chat + """Chat that posted the story""" + id: int + """Unique identifier for the story in the chat""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, chat: Chat, id: int, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(chat=chat, id=id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/successful_payment.py b/env/Lib/site-packages/aiogram/types/successful_payment.py new file mode 100644 index 0000000..30d4356 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/successful_payment.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .order_info import OrderInfo + + +class SuccessfulPayment(TelegramObject): + """ + This object contains basic information about a successful payment. + + Source: https://core.telegram.org/bots/api#successfulpayment + """ + + currency: str + """Three-letter ISO 4217 `currency `_ code, or 'XTR' for payments in `Telegram Stars `_""" + total_amount: int + """Total price in the *smallest units* of the currency (integer, **not** float/double). For example, for a price of :code:`US$ 1.45` pass :code:`amount = 145`. See the *exp* parameter in `currencies.json `_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" + invoice_payload: str + """Bot-specified invoice payload""" + telegram_payment_charge_id: str + """Telegram payment identifier""" + provider_payment_charge_id: str + """Provider payment identifier""" + shipping_option_id: Optional[str] = None + """*Optional*. Identifier of the shipping option chosen by the user""" + order_info: Optional[OrderInfo] = None + """*Optional*. Order information provided by the user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + currency: str, + total_amount: int, + invoice_payload: str, + telegram_payment_charge_id: str, + provider_payment_charge_id: str, + shipping_option_id: Optional[str] = None, + order_info: Optional[OrderInfo] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + currency=currency, + total_amount=total_amount, + invoice_payload=invoice_payload, + telegram_payment_charge_id=telegram_payment_charge_id, + provider_payment_charge_id=provider_payment_charge_id, + shipping_option_id=shipping_option_id, + order_info=order_info, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/switch_inline_query_chosen_chat.py b/env/Lib/site-packages/aiogram/types/switch_inline_query_chosen_chat.py new file mode 100644 index 0000000..9a25dca --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/switch_inline_query_chosen_chat.py @@ -0,0 +1,49 @@ +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class SwitchInlineQueryChosenChat(TelegramObject): + """ + This object represents an inline button that switches the current user to inline mode in a chosen chat, with an optional default inline query. + + Source: https://core.telegram.org/bots/api#switchinlinequerychosenchat + """ + + query: Optional[str] = None + """*Optional*. The default inline query to be inserted in the input field. If left empty, only the bot's username will be inserted""" + allow_user_chats: Optional[bool] = None + """*Optional*. True, if private chats with users can be chosen""" + allow_bot_chats: Optional[bool] = None + """*Optional*. True, if private chats with bots can be chosen""" + allow_group_chats: Optional[bool] = None + """*Optional*. True, if group and supergroup chats can be chosen""" + allow_channel_chats: Optional[bool] = None + """*Optional*. True, if channel chats can be chosen""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + query: Optional[str] = None, + allow_user_chats: Optional[bool] = None, + allow_bot_chats: Optional[bool] = None, + allow_group_chats: Optional[bool] = None, + allow_channel_chats: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + query=query, + allow_user_chats=allow_user_chats, + allow_bot_chats=allow_bot_chats, + allow_group_chats=allow_group_chats, + allow_channel_chats=allow_channel_chats, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/text_quote.py b/env/Lib/site-packages/aiogram/types/text_quote.py new file mode 100644 index 0000000..a882ccf --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/text_quote.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .message_entity import MessageEntity + + +class TextQuote(TelegramObject): + """ + This object contains information about the quoted part of a message that is replied to by the given message. + + Source: https://core.telegram.org/bots/api#textquote + """ + + text: str + """Text of the quoted part of a message that is replied to by the given message""" + position: int + """Approximate quote position in the original message in UTF-16 code units as specified by the sender""" + entities: Optional[List[MessageEntity]] = None + """*Optional*. Special entities that appear in the quote. Currently, only *bold*, *italic*, *underline*, *strikethrough*, *spoiler*, and *custom_emoji* entities are kept in quotes.""" + is_manual: Optional[bool] = None + """*Optional*. True, if the quote was chosen manually by the message sender. Otherwise, the quote was added automatically by the server.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + text: str, + position: int, + entities: Optional[List[MessageEntity]] = None, + is_manual: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + text=text, + position=position, + entities=entities, + is_manual=is_manual, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/transaction_partner.py b/env/Lib/site-packages/aiogram/types/transaction_partner.py new file mode 100644 index 0000000..a26b0fc --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/transaction_partner.py @@ -0,0 +1,14 @@ +from .base import TelegramObject + + +class TransactionPartner(TelegramObject): + """ + This object describes the source of a transaction, or its recipient for outgoing transactions. Currently, it can be one of + + - :class:`aiogram.types.transaction_partner_user.TransactionPartnerUser` + - :class:`aiogram.types.transaction_partner_fragment.TransactionPartnerFragment` + - :class:`aiogram.types.transaction_partner_telegram_ads.TransactionPartnerTelegramAds` + - :class:`aiogram.types.transaction_partner_other.TransactionPartnerOther` + + Source: https://core.telegram.org/bots/api#transactionpartner + """ diff --git a/env/Lib/site-packages/aiogram/types/transaction_partner_fragment.py b/env/Lib/site-packages/aiogram/types/transaction_partner_fragment.py new file mode 100644 index 0000000..350109e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/transaction_partner_fragment.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, Union + +from ..enums import TransactionPartnerType +from .transaction_partner import TransactionPartner + +if TYPE_CHECKING: + from .revenue_withdrawal_state_failed import RevenueWithdrawalStateFailed + from .revenue_withdrawal_state_pending import RevenueWithdrawalStatePending + from .revenue_withdrawal_state_succeeded import RevenueWithdrawalStateSucceeded + + +class TransactionPartnerFragment(TransactionPartner): + """ + Describes a withdrawal transaction with Fragment. + + Source: https://core.telegram.org/bots/api#transactionpartnerfragment + """ + + type: Literal[TransactionPartnerType.FRAGMENT] = TransactionPartnerType.FRAGMENT + """Type of the transaction partner, always 'fragment'""" + withdrawal_state: Optional[ + Union[ + RevenueWithdrawalStatePending, + RevenueWithdrawalStateSucceeded, + RevenueWithdrawalStateFailed, + ] + ] = None + """*Optional*. State of the transaction if the transaction is outgoing""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[TransactionPartnerType.FRAGMENT] = TransactionPartnerType.FRAGMENT, + withdrawal_state: Optional[ + Union[ + RevenueWithdrawalStatePending, + RevenueWithdrawalStateSucceeded, + RevenueWithdrawalStateFailed, + ] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, withdrawal_state=withdrawal_state, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/transaction_partner_other.py b/env/Lib/site-packages/aiogram/types/transaction_partner_other.py new file mode 100644 index 0000000..699297e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/transaction_partner_other.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import TransactionPartnerType +from .transaction_partner import TransactionPartner + + +class TransactionPartnerOther(TransactionPartner): + """ + Describes a transaction with an unknown source or recipient. + + Source: https://core.telegram.org/bots/api#transactionpartnerother + """ + + type: Literal[TransactionPartnerType.OTHER] = TransactionPartnerType.OTHER + """Type of the transaction partner, always 'other'""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[TransactionPartnerType.OTHER] = TransactionPartnerType.OTHER, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/transaction_partner_telegram_ads.py b/env/Lib/site-packages/aiogram/types/transaction_partner_telegram_ads.py new file mode 100644 index 0000000..5df8eb6 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/transaction_partner_telegram_ads.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal + +from ..enums import TransactionPartnerType +from .transaction_partner import TransactionPartner + + +class TransactionPartnerTelegramAds(TransactionPartner): + """ + Describes a withdrawal transaction to the Telegram Ads platform. + + Source: https://core.telegram.org/bots/api#transactionpartnertelegramads + """ + + type: Literal[TransactionPartnerType.TELEGRAM_ADS] = TransactionPartnerType.TELEGRAM_ADS + """Type of the transaction partner, always 'telegram_ads'""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[ + TransactionPartnerType.TELEGRAM_ADS + ] = TransactionPartnerType.TELEGRAM_ADS, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(type=type, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/transaction_partner_user.py b/env/Lib/site-packages/aiogram/types/transaction_partner_user.py new file mode 100644 index 0000000..260c9a1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/transaction_partner_user.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Literal, Optional, Union + +from ..enums import TransactionPartnerType +from .transaction_partner import TransactionPartner + +if TYPE_CHECKING: + from .paid_media_photo import PaidMediaPhoto + from .paid_media_preview import PaidMediaPreview + from .paid_media_video import PaidMediaVideo + from .user import User + + +class TransactionPartnerUser(TransactionPartner): + """ + Describes a transaction with a user. + + Source: https://core.telegram.org/bots/api#transactionpartneruser + """ + + type: Literal[TransactionPartnerType.USER] = TransactionPartnerType.USER + """Type of the transaction partner, always 'user'""" + user: User + """Information about the user""" + invoice_payload: Optional[str] = None + """*Optional*. Bot-specified invoice payload""" + paid_media: Optional[List[Union[PaidMediaPreview, PaidMediaPhoto, PaidMediaVideo]]] = None + """*Optional*. Information about the paid media bought by the user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + type: Literal[TransactionPartnerType.USER] = TransactionPartnerType.USER, + user: User, + invoice_payload: Optional[str] = None, + paid_media: Optional[ + List[Union[PaidMediaPreview, PaidMediaPhoto, PaidMediaVideo]] + ] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + type=type, + user=user, + invoice_payload=invoice_payload, + paid_media=paid_media, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/update.py b/env/Lib/site-packages/aiogram/types/update.py new file mode 100644 index 0000000..0533996 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/update.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional, cast + +from ..utils.mypy_hacks import lru_cache +from .base import TelegramObject + +if TYPE_CHECKING: + from .business_connection import BusinessConnection + from .business_messages_deleted import BusinessMessagesDeleted + from .callback_query import CallbackQuery + from .chat_boost_removed import ChatBoostRemoved + from .chat_boost_updated import ChatBoostUpdated + from .chat_join_request import ChatJoinRequest + from .chat_member_updated import ChatMemberUpdated + from .chosen_inline_result import ChosenInlineResult + from .inline_query import InlineQuery + from .message import Message + from .message_reaction_count_updated import MessageReactionCountUpdated + from .message_reaction_updated import MessageReactionUpdated + from .poll import Poll + from .poll_answer import PollAnswer + from .pre_checkout_query import PreCheckoutQuery + from .shipping_query import ShippingQuery + + +class Update(TelegramObject): + """ + This `object `_ represents an incoming update. + + At most **one** of the optional parameters can be present in any given update. + + Source: https://core.telegram.org/bots/api#update + """ + + update_id: int + """The update's unique identifier. Update identifiers start from a certain positive number and increase sequentially. This identifier becomes especially handy if you're using `webhooks `_, since it allows you to ignore repeated updates or to restore the correct update sequence, should they get out of order. If there are no new updates for at least a week, then identifier of the next update will be chosen randomly instead of sequentially.""" + message: Optional[Message] = None + """*Optional*. New incoming message of any kind - text, photo, sticker, etc.""" + edited_message: Optional[Message] = None + """*Optional*. New version of a message that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.""" + channel_post: Optional[Message] = None + """*Optional*. New incoming channel post of any kind - text, photo, sticker, etc.""" + edited_channel_post: Optional[Message] = None + """*Optional*. New version of a channel post that is known to the bot and was edited. This update may at times be triggered by changes to message fields that are either unavailable or not actively used by your bot.""" + business_connection: Optional[BusinessConnection] = None + """*Optional*. The bot was connected to or disconnected from a business account, or a user edited an existing connection with the bot""" + business_message: Optional[Message] = None + """*Optional*. New message from a connected business account""" + edited_business_message: Optional[Message] = None + """*Optional*. New version of a message from a connected business account""" + deleted_business_messages: Optional[BusinessMessagesDeleted] = None + """*Optional*. Messages were deleted from a connected business account""" + message_reaction: Optional[MessageReactionUpdated] = None + """*Optional*. A reaction to a message was changed by a user. The bot must be an administrator in the chat and must explicitly specify :code:`"message_reaction"` in the list of *allowed_updates* to receive these updates. The update isn't received for reactions set by bots.""" + message_reaction_count: Optional[MessageReactionCountUpdated] = None + """*Optional*. Reactions to a message with anonymous reactions were changed. The bot must be an administrator in the chat and must explicitly specify :code:`"message_reaction_count"` in the list of *allowed_updates* to receive these updates. The updates are grouped and can be sent with delay up to a few minutes.""" + inline_query: Optional[InlineQuery] = None + """*Optional*. New incoming `inline `_ query""" + chosen_inline_result: Optional[ChosenInlineResult] = None + """*Optional*. The result of an `inline `_ query that was chosen by a user and sent to their chat partner. Please see our documentation on the `feedback collecting `_ for details on how to enable these updates for your bot.""" + callback_query: Optional[CallbackQuery] = None + """*Optional*. New incoming callback query""" + shipping_query: Optional[ShippingQuery] = None + """*Optional*. New incoming shipping query. Only for invoices with flexible price""" + pre_checkout_query: Optional[PreCheckoutQuery] = None + """*Optional*. New incoming pre-checkout query. Contains full information about checkout""" + poll: Optional[Poll] = None + """*Optional*. New poll state. Bots receive only updates about manually stopped polls and polls, which are sent by the bot""" + poll_answer: Optional[PollAnswer] = None + """*Optional*. A user changed their answer in a non-anonymous poll. Bots receive new votes only in polls that were sent by the bot itself.""" + my_chat_member: Optional[ChatMemberUpdated] = None + """*Optional*. The bot's chat member status was updated in a chat. For private chats, this update is received only when the bot is blocked or unblocked by the user.""" + chat_member: Optional[ChatMemberUpdated] = None + """*Optional*. A chat member's status was updated in a chat. The bot must be an administrator in the chat and must explicitly specify :code:`"chat_member"` in the list of *allowed_updates* to receive these updates.""" + chat_join_request: Optional[ChatJoinRequest] = None + """*Optional*. A request to join the chat has been sent. The bot must have the *can_invite_users* administrator right in the chat to receive these updates.""" + chat_boost: Optional[ChatBoostUpdated] = None + """*Optional*. A chat boost was added or changed. The bot must be an administrator in the chat to receive these updates.""" + removed_chat_boost: Optional[ChatBoostRemoved] = None + """*Optional*. A boost was removed from a chat. The bot must be an administrator in the chat to receive these updates.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + update_id: int, + message: Optional[Message] = None, + edited_message: Optional[Message] = None, + channel_post: Optional[Message] = None, + edited_channel_post: Optional[Message] = None, + business_connection: Optional[BusinessConnection] = None, + business_message: Optional[Message] = None, + edited_business_message: Optional[Message] = None, + deleted_business_messages: Optional[BusinessMessagesDeleted] = None, + message_reaction: Optional[MessageReactionUpdated] = None, + message_reaction_count: Optional[MessageReactionCountUpdated] = None, + inline_query: Optional[InlineQuery] = None, + chosen_inline_result: Optional[ChosenInlineResult] = None, + callback_query: Optional[CallbackQuery] = None, + shipping_query: Optional[ShippingQuery] = None, + pre_checkout_query: Optional[PreCheckoutQuery] = None, + poll: Optional[Poll] = None, + poll_answer: Optional[PollAnswer] = None, + my_chat_member: Optional[ChatMemberUpdated] = None, + chat_member: Optional[ChatMemberUpdated] = None, + chat_join_request: Optional[ChatJoinRequest] = None, + chat_boost: Optional[ChatBoostUpdated] = None, + removed_chat_boost: Optional[ChatBoostRemoved] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + update_id=update_id, + message=message, + edited_message=edited_message, + channel_post=channel_post, + edited_channel_post=edited_channel_post, + business_connection=business_connection, + business_message=business_message, + edited_business_message=edited_business_message, + deleted_business_messages=deleted_business_messages, + message_reaction=message_reaction, + message_reaction_count=message_reaction_count, + inline_query=inline_query, + chosen_inline_result=chosen_inline_result, + callback_query=callback_query, + shipping_query=shipping_query, + pre_checkout_query=pre_checkout_query, + poll=poll, + poll_answer=poll_answer, + my_chat_member=my_chat_member, + chat_member=chat_member, + chat_join_request=chat_join_request, + chat_boost=chat_boost, + removed_chat_boost=removed_chat_boost, + **__pydantic_kwargs, + ) + + def __hash__(self) -> int: + return hash((type(self), self.update_id)) + + @property + @lru_cache() + def event_type(self) -> str: + """ + Detect update type + If update type is unknown, raise UpdateTypeLookupError + + :return: + """ + if self.message: + return "message" + if self.edited_message: + return "edited_message" + if self.channel_post: + return "channel_post" + if self.edited_channel_post: + return "edited_channel_post" + if self.inline_query: + return "inline_query" + if self.chosen_inline_result: + return "chosen_inline_result" + if self.callback_query: + return "callback_query" + if self.shipping_query: + return "shipping_query" + if self.pre_checkout_query: + return "pre_checkout_query" + if self.poll: + return "poll" + if self.poll_answer: + return "poll_answer" + if self.my_chat_member: + return "my_chat_member" + if self.chat_member: + return "chat_member" + if self.chat_join_request: + return "chat_join_request" + if self.message_reaction: + return "message_reaction" + if self.message_reaction_count: + return "message_reaction_count" + if self.chat_boost: + return "chat_boost" + if self.removed_chat_boost: + return "removed_chat_boost" + if self.deleted_business_messages: + return "deleted_business_messages" + if self.business_connection: + return "business_connection" + if self.edited_business_message: + return "edited_business_message" + if self.business_message: + return "business_message" + + raise UpdateTypeLookupError("Update does not contain any known event type.") + + @property + def event(self) -> TelegramObject: + return cast(TelegramObject, getattr(self, self.event_type)) + + +class UpdateTypeLookupError(LookupError): + """Update does not contain any known event type.""" diff --git a/env/Lib/site-packages/aiogram/types/user.py b/env/Lib/site-packages/aiogram/types/user.py new file mode 100644 index 0000000..56782f2 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/user.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from ..utils import markdown +from ..utils.link import create_tg_link +from .base import TelegramObject + +if TYPE_CHECKING: + from ..methods import GetUserProfilePhotos + + +class User(TelegramObject): + """ + This object represents a Telegram user or bot. + + Source: https://core.telegram.org/bots/api#user + """ + + id: int + """Unique identifier for this user or bot. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier.""" + is_bot: bool + """:code:`True`, if this user is a bot""" + first_name: str + """User's or bot's first name""" + last_name: Optional[str] = None + """*Optional*. User's or bot's last name""" + username: Optional[str] = None + """*Optional*. User's or bot's username""" + language_code: Optional[str] = None + """*Optional*. `IETF language tag `_ of the user's language""" + is_premium: Optional[bool] = None + """*Optional*. :code:`True`, if this user is a Telegram Premium user""" + added_to_attachment_menu: Optional[bool] = None + """*Optional*. :code:`True`, if this user added the bot to the attachment menu""" + can_join_groups: Optional[bool] = None + """*Optional*. :code:`True`, if the bot can be invited to groups. Returned only in :class:`aiogram.methods.get_me.GetMe`.""" + can_read_all_group_messages: Optional[bool] = None + """*Optional*. :code:`True`, if `privacy mode `_ is disabled for the bot. Returned only in :class:`aiogram.methods.get_me.GetMe`.""" + supports_inline_queries: Optional[bool] = None + """*Optional*. :code:`True`, if the bot supports inline queries. Returned only in :class:`aiogram.methods.get_me.GetMe`.""" + can_connect_to_business: Optional[bool] = None + """*Optional*. :code:`True`, if the bot can be connected to a Telegram Business account to receive its messages. Returned only in :class:`aiogram.methods.get_me.GetMe`.""" + has_main_web_app: Optional[bool] = None + """*Optional*. :code:`True`, if the bot has a main Web App. Returned only in :class:`aiogram.methods.get_me.GetMe`.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + id: int, + is_bot: bool, + first_name: str, + last_name: Optional[str] = None, + username: Optional[str] = None, + language_code: Optional[str] = None, + is_premium: Optional[bool] = None, + added_to_attachment_menu: Optional[bool] = None, + can_join_groups: Optional[bool] = None, + can_read_all_group_messages: Optional[bool] = None, + supports_inline_queries: Optional[bool] = None, + can_connect_to_business: Optional[bool] = None, + has_main_web_app: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + id=id, + is_bot=is_bot, + first_name=first_name, + last_name=last_name, + username=username, + language_code=language_code, + is_premium=is_premium, + added_to_attachment_menu=added_to_attachment_menu, + can_join_groups=can_join_groups, + can_read_all_group_messages=can_read_all_group_messages, + supports_inline_queries=supports_inline_queries, + can_connect_to_business=can_connect_to_business, + has_main_web_app=has_main_web_app, + **__pydantic_kwargs, + ) + + @property + def full_name(self) -> str: + if self.last_name: + return f"{self.first_name} {self.last_name}" + return self.first_name + + @property + def url(self) -> str: + return create_tg_link("user", id=self.id) + + def mention_markdown(self, name: Optional[str] = None) -> str: + if name is None: + name = self.full_name + return markdown.link(name, self.url) + + def mention_html(self, name: Optional[str] = None) -> str: + if name is None: + name = self.full_name + return markdown.hlink(name, self.url) + + def get_profile_photos( + self, + offset: Optional[int] = None, + limit: Optional[int] = None, + **kwargs: Any, + ) -> GetUserProfilePhotos: + """ + Shortcut for method :class:`aiogram.methods.get_user_profile_photos.GetUserProfilePhotos` + will automatically fill method attributes: + + - :code:`user_id` + + Use this method to get a list of profile pictures for a user. Returns a :class:`aiogram.types.user_profile_photos.UserProfilePhotos` object. + + Source: https://core.telegram.org/bots/api#getuserprofilephotos + + :param offset: Sequential number of the first photo to be returned. By default, all photos are returned. + :param limit: Limits the number of photos to be retrieved. Values between 1-100 are accepted. Defaults to 100. + :return: instance of method :class:`aiogram.methods.get_user_profile_photos.GetUserProfilePhotos` + """ + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + + from aiogram.methods import GetUserProfilePhotos + + return GetUserProfilePhotos( + user_id=self.id, + offset=offset, + limit=limit, + **kwargs, + ).as_(self._bot) diff --git a/env/Lib/site-packages/aiogram/types/user_chat_boosts.py b/env/Lib/site-packages/aiogram/types/user_chat_boosts.py new file mode 100644 index 0000000..3da8d37 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/user_chat_boosts.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .chat_boost import ChatBoost + + +class UserChatBoosts(TelegramObject): + """ + This object represents a list of boosts added to a chat by a user. + + Source: https://core.telegram.org/bots/api#userchatboosts + """ + + boosts: List[ChatBoost] + """The list of boosts added to the chat by the user""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, boosts: List[ChatBoost], **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(boosts=boosts, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/user_profile_photos.py b/env/Lib/site-packages/aiogram/types/user_profile_photos.py new file mode 100644 index 0000000..c1c5d28 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/user_profile_photos.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class UserProfilePhotos(TelegramObject): + """ + This object represent a user's profile pictures. + + Source: https://core.telegram.org/bots/api#userprofilephotos + """ + + total_count: int + """Total number of profile pictures the target user has""" + photos: List[List[PhotoSize]] + """Requested profile pictures (in up to 4 sizes each)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + total_count: int, + photos: List[List[PhotoSize]], + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(total_count=total_count, photos=photos, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/user_shared.py b/env/Lib/site-packages/aiogram/types/user_shared.py new file mode 100644 index 0000000..59d1ede --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/user_shared.py @@ -0,0 +1,32 @@ +from typing import TYPE_CHECKING, Any + +from aiogram.types import TelegramObject + + +class UserShared(TelegramObject): + """ + This object contains information about the user whose identifier was shared with the bot using a :class:`aiogram.types.keyboard_button_request_user.KeyboardButtonRequestUser` button. + + .. deprecated:: API:7.0 + https://core.telegram.org/bots/api-changelog#december-29-2023 + + Source: https://core.telegram.org/bots/api#usershared + """ + + request_id: int + """Identifier of the request""" + user_id: int + """Identifier of the shared user. This number may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a 64-bit integer or double-precision float type are safe for storing this identifier. The bot may not have access to the user and could be unable to use this identifier, unless the user is already known to the bot by some other means.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, request_id: int, user_id: int, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(request_id=request_id, user_id=user_id, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/users_shared.py b/env/Lib/site-packages/aiogram/types/users_shared.py new file mode 100644 index 0000000..351fc0e --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/users_shared.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from pydantic import Field + +from .base import TelegramObject + +if TYPE_CHECKING: + from .shared_user import SharedUser + + +class UsersShared(TelegramObject): + """ + This object contains information about the users whose identifiers were shared with the bot using a :class:`aiogram.types.keyboard_button_request_users.KeyboardButtonRequestUsers` button. + + Source: https://core.telegram.org/bots/api#usersshared + """ + + request_id: int + """Identifier of the request""" + users: List[SharedUser] + """Information about users shared with the bot.""" + user_ids: Optional[List[int]] = Field(None, json_schema_extra={"deprecated": True}) + """Identifiers of the shared users. These numbers may have more than 32 significant bits and some programming languages may have difficulty/silent defects in interpreting them. But they have at most 52 significant bits, so 64-bit integers or double-precision float types are safe for storing these identifiers. The bot may not have access to the users and could be unable to use these identifiers, unless the users are already known to the bot by some other means. + +.. deprecated:: API:7.2 + https://core.telegram.org/bots/api-changelog#march-31-2024""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + request_id: int, + users: List[SharedUser], + user_ids: Optional[List[int]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + request_id=request_id, users=users, user_ids=user_ids, **__pydantic_kwargs + ) diff --git a/env/Lib/site-packages/aiogram/types/venue.py b/env/Lib/site-packages/aiogram/types/venue.py new file mode 100644 index 0000000..e0a3f84 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/venue.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .location import Location + + +class Venue(TelegramObject): + """ + This object represents a venue. + + Source: https://core.telegram.org/bots/api#venue + """ + + location: Location + """Venue location. Can't be a live location""" + title: str + """Name of the venue""" + address: str + """Address of the venue""" + foursquare_id: Optional[str] = None + """*Optional*. Foursquare identifier of the venue""" + foursquare_type: Optional[str] = None + """*Optional*. Foursquare type of the venue. (For example, 'arts_entertainment/default', 'arts_entertainment/aquarium' or 'food/icecream'.)""" + google_place_id: Optional[str] = None + """*Optional*. Google Places identifier of the venue""" + google_place_type: Optional[str] = None + """*Optional*. Google Places type of the venue. (See `supported types `_.)""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + location: Location, + title: str, + address: str, + foursquare_id: Optional[str] = None, + foursquare_type: Optional[str] = None, + google_place_id: Optional[str] = None, + google_place_type: Optional[str] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + location=location, + title=title, + address=address, + foursquare_id=foursquare_id, + foursquare_type=foursquare_type, + google_place_id=google_place_id, + google_place_type=google_place_type, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/video.py b/env/Lib/site-packages/aiogram/types/video.py new file mode 100644 index 0000000..e8ecf1f --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/video.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class Video(TelegramObject): + """ + This object represents a video file. + + Source: https://core.telegram.org/bots/api#video + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + width: int + """Video width as defined by the sender""" + height: int + """Video height as defined by the sender""" + duration: int + """Duration of the video in seconds as defined by the sender""" + thumbnail: Optional[PhotoSize] = None + """*Optional*. Video thumbnail""" + file_name: Optional[str] = None + """*Optional*. Original filename as defined by the sender""" + mime_type: Optional[str] = None + """*Optional*. MIME type of the file as defined by the sender""" + file_size: Optional[int] = None + """*Optional*. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + width: int, + height: int, + duration: int, + thumbnail: Optional[PhotoSize] = None, + file_name: Optional[str] = None, + mime_type: Optional[str] = None, + file_size: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + width=width, + height=height, + duration=duration, + thumbnail=thumbnail, + file_name=file_name, + mime_type=mime_type, + file_size=file_size, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/video_chat_ended.py b/env/Lib/site-packages/aiogram/types/video_chat_ended.py new file mode 100644 index 0000000..289eb72 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/video_chat_ended.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class VideoChatEnded(TelegramObject): + """ + This object represents a service message about a video chat ended in the chat. + + Source: https://core.telegram.org/bots/api#videochatended + """ + + duration: int + """Video chat duration in seconds""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, duration: int, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(duration=duration, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/video_chat_participants_invited.py b/env/Lib/site-packages/aiogram/types/video_chat_participants_invited.py new file mode 100644 index 0000000..74e1a35 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/video_chat_participants_invited.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List + +from .base import TelegramObject + +if TYPE_CHECKING: + from .user import User + + +class VideoChatParticipantsInvited(TelegramObject): + """ + This object represents a service message about new members invited to a video chat. + + Source: https://core.telegram.org/bots/api#videochatparticipantsinvited + """ + + users: List[User] + """New members that were invited to the video chat""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, users: List[User], **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(users=users, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/video_chat_scheduled.py b/env/Lib/site-packages/aiogram/types/video_chat_scheduled.py new file mode 100644 index 0000000..c82e495 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/video_chat_scheduled.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject +from .custom import DateTime + + +class VideoChatScheduled(TelegramObject): + """ + This object represents a service message about a video chat scheduled in the chat. + + Source: https://core.telegram.org/bots/api#videochatscheduled + """ + + start_date: DateTime + """Point in time (Unix timestamp) when the video chat is supposed to be started by a chat administrator""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, start_date: DateTime, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(start_date=start_date, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/video_chat_started.py b/env/Lib/site-packages/aiogram/types/video_chat_started.py new file mode 100644 index 0000000..a6f9aed --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/video_chat_started.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +from .base import TelegramObject + + +class VideoChatStarted(TelegramObject): + """ + This object represents a service message about a video chat started in the chat. Currently holds no information. + + Source: https://core.telegram.org/bots/api#videochatstarted + """ diff --git a/env/Lib/site-packages/aiogram/types/video_note.py b/env/Lib/site-packages/aiogram/types/video_note.py new file mode 100644 index 0000000..5be8502 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/video_note.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + +if TYPE_CHECKING: + from .photo_size import PhotoSize + + +class VideoNote(TelegramObject): + """ + This object represents a `video message `_ (available in Telegram apps as of `v.4.0 `_). + + Source: https://core.telegram.org/bots/api#videonote + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + length: int + """Video width and height (diameter of the video message) as defined by the sender""" + duration: int + """Duration of the video in seconds as defined by the sender""" + thumbnail: Optional[PhotoSize] = None + """*Optional*. Video thumbnail""" + file_size: Optional[int] = None + """*Optional*. File size in bytes""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + length: int, + duration: int, + thumbnail: Optional[PhotoSize] = None, + file_size: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + length=length, + duration=duration, + thumbnail=thumbnail, + file_size=file_size, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/voice.py b/env/Lib/site-packages/aiogram/types/voice.py new file mode 100644 index 0000000..d5e0abc --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/voice.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +from .base import TelegramObject + + +class Voice(TelegramObject): + """ + This object represents a voice note. + + Source: https://core.telegram.org/bots/api#voice + """ + + file_id: str + """Identifier for this file, which can be used to download or reuse the file""" + file_unique_id: str + """Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.""" + duration: int + """Duration of the audio in seconds as defined by the sender""" + mime_type: Optional[str] = None + """*Optional*. MIME type of the file as defined by the sender""" + file_size: Optional[int] = None + """*Optional*. File size in bytes. It can be bigger than 2^31 and some programming languages may have difficulty/silent defects in interpreting it. But it has at most 52 significant bits, so a signed 64-bit integer or double-precision float type are safe for storing this value.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + file_id: str, + file_unique_id: str, + duration: int, + mime_type: Optional[str] = None, + file_size: Optional[int] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + file_id=file_id, + file_unique_id=file_unique_id, + duration=duration, + mime_type=mime_type, + file_size=file_size, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/web_app_data.py b/env/Lib/site-packages/aiogram/types/web_app_data.py new file mode 100644 index 0000000..8fac379 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/web_app_data.py @@ -0,0 +1,31 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class WebAppData(TelegramObject): + """ + Describes data sent from a `Web App `_ to the bot. + + Source: https://core.telegram.org/bots/api#webappdata + """ + + data: str + """The data. Be aware that a bad client can send arbitrary data in this field.""" + button_text: str + """Text of the *web_app* keyboard button from which the Web App was opened. Be aware that a bad client can send arbitrary data in this field.""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, *, data: str, button_text: str, **__pydantic_kwargs: Any + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(data=data, button_text=button_text, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/web_app_info.py b/env/Lib/site-packages/aiogram/types/web_app_info.py new file mode 100644 index 0000000..fbf9846 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/web_app_info.py @@ -0,0 +1,27 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +from .base import TelegramObject + + +class WebAppInfo(TelegramObject): + """ + Describes a `Web App `_. + + Source: https://core.telegram.org/bots/api#webappinfo + """ + + url: str + """An HTTPS URL of a Web App to be opened with additional data as specified in `Initializing Web Apps `_""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__(__pydantic__self__, *, url: str, **__pydantic_kwargs: Any) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__(url=url, **__pydantic_kwargs) diff --git a/env/Lib/site-packages/aiogram/types/webhook_info.py b/env/Lib/site-packages/aiogram/types/webhook_info.py new file mode 100644 index 0000000..1753df4 --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/webhook_info.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Optional + +from .base import TelegramObject +from .custom import DateTime + + +class WebhookInfo(TelegramObject): + """ + Describes the current status of a webhook. + + Source: https://core.telegram.org/bots/api#webhookinfo + """ + + url: str + """Webhook URL, may be empty if webhook is not set up""" + has_custom_certificate: bool + """:code:`True`, if a custom certificate was provided for webhook certificate checks""" + pending_update_count: int + """Number of updates awaiting delivery""" + ip_address: Optional[str] = None + """*Optional*. Currently used webhook IP address""" + last_error_date: Optional[DateTime] = None + """*Optional*. Unix time for the most recent error that happened when trying to deliver an update via webhook""" + last_error_message: Optional[str] = None + """*Optional*. Error message in human-readable format for the most recent error that happened when trying to deliver an update via webhook""" + last_synchronization_error_date: Optional[DateTime] = None + """*Optional*. Unix time of the most recent error that happened when trying to synchronize available updates with Telegram datacenters""" + max_connections: Optional[int] = None + """*Optional*. The maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery""" + allowed_updates: Optional[List[str]] = None + """*Optional*. A list of update types the bot is subscribed to. Defaults to all update types except *chat_member*""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + url: str, + has_custom_certificate: bool, + pending_update_count: int, + ip_address: Optional[str] = None, + last_error_date: Optional[DateTime] = None, + last_error_message: Optional[str] = None, + last_synchronization_error_date: Optional[DateTime] = None, + max_connections: Optional[int] = None, + allowed_updates: Optional[List[str]] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + url=url, + has_custom_certificate=has_custom_certificate, + pending_update_count=pending_update_count, + ip_address=ip_address, + last_error_date=last_error_date, + last_error_message=last_error_message, + last_synchronization_error_date=last_synchronization_error_date, + max_connections=max_connections, + allowed_updates=allowed_updates, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/types/write_access_allowed.py b/env/Lib/site-packages/aiogram/types/write_access_allowed.py new file mode 100644 index 0000000..6b8e50a --- /dev/null +++ b/env/Lib/site-packages/aiogram/types/write_access_allowed.py @@ -0,0 +1,41 @@ +from typing import TYPE_CHECKING, Any, Optional + +from aiogram.types import TelegramObject + + +class WriteAccessAllowed(TelegramObject): + """ + This object represents a service message about a user allowing a bot to write messages after adding it to the attachment menu, launching a Web App from a link, or accepting an explicit request from a Web App sent by the method `requestWriteAccess `_. + + Source: https://core.telegram.org/bots/api#writeaccessallowed + """ + + from_request: Optional[bool] = None + """*Optional*. True, if the access was granted after the user accepted an explicit request from a Web App sent by the method `requestWriteAccess `_""" + web_app_name: Optional[str] = None + """*Optional*. Name of the Web App, if the access was granted when the Web App was launched from a link""" + from_attachment_menu: Optional[bool] = None + """*Optional*. True, if the access was granted when the bot was added to the attachment or side menu""" + + if TYPE_CHECKING: + # DO NOT EDIT MANUALLY!!! + # This section was auto-generated via `butcher` + + def __init__( + __pydantic__self__, + *, + from_request: Optional[bool] = None, + web_app_name: Optional[str] = None, + from_attachment_menu: Optional[bool] = None, + **__pydantic_kwargs: Any, + ) -> None: + # DO NOT EDIT MANUALLY!!! + # This method was auto-generated via `butcher` + # Is needed only for type checking and IDE support without any additional plugins + + super().__init__( + from_request=from_request, + web_app_name=web_app_name, + from_attachment_menu=from_attachment_menu, + **__pydantic_kwargs, + ) diff --git a/env/Lib/site-packages/aiogram/utils/__init__.py b/env/Lib/site-packages/aiogram/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..e5a6621 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/auth_widget.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/auth_widget.cpython-311.pyc new file mode 100644 index 0000000..0c5645b Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/auth_widget.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/backoff.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/backoff.cpython-311.pyc new file mode 100644 index 0000000..3810b09 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/backoff.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/callback_answer.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/callback_answer.cpython-311.pyc new file mode 100644 index 0000000..91aa564 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/callback_answer.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/chat_action.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/chat_action.cpython-311.pyc new file mode 100644 index 0000000..3cf48fd Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/chat_action.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/chat_member.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/chat_member.cpython-311.pyc new file mode 100644 index 0000000..5af477a Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/chat_member.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/deep_linking.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/deep_linking.cpython-311.pyc new file mode 100644 index 0000000..83aecdb Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/deep_linking.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/formatting.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/formatting.cpython-311.pyc new file mode 100644 index 0000000..7809393 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/formatting.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/keyboard.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/keyboard.cpython-311.pyc new file mode 100644 index 0000000..4c85129 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/keyboard.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/link.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/link.cpython-311.pyc new file mode 100644 index 0000000..5f949af Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/link.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/magic_filter.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/magic_filter.cpython-311.pyc new file mode 100644 index 0000000..d98f05b Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/magic_filter.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/markdown.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/markdown.cpython-311.pyc new file mode 100644 index 0000000..e1e0c0a Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/markdown.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/media_group.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/media_group.cpython-311.pyc new file mode 100644 index 0000000..dae3bf1 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/media_group.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/mixins.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/mixins.cpython-311.pyc new file mode 100644 index 0000000..d60c826 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/mixins.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/mypy_hacks.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/mypy_hacks.cpython-311.pyc new file mode 100644 index 0000000..fc544c0 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/mypy_hacks.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/payload.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/payload.cpython-311.pyc new file mode 100644 index 0000000..ef6de3c Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/payload.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/serialization.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/serialization.cpython-311.pyc new file mode 100644 index 0000000..7c35e9a Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/serialization.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/text_decorations.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/text_decorations.cpython-311.pyc new file mode 100644 index 0000000..a59933e Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/text_decorations.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/token.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/token.cpython-311.pyc new file mode 100644 index 0000000..3de6fdd Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/token.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/warnings.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/warnings.cpython-311.pyc new file mode 100644 index 0000000..db95559 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/warnings.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/__pycache__/web_app.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/__pycache__/web_app.cpython-311.pyc new file mode 100644 index 0000000..5595a6d Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/__pycache__/web_app.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/auth_widget.py b/env/Lib/site-packages/aiogram/utils/auth_widget.py new file mode 100644 index 0000000..080183e --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/auth_widget.py @@ -0,0 +1,34 @@ +import hashlib +import hmac +from typing import Any, Dict + + +def check_signature(token: str, hash: str, **kwargs: Any) -> bool: + """ + Generate hexadecimal representation + of the HMAC-SHA-256 signature of the data-check-string + with the SHA256 hash of the bot's token used as a secret key + + :param token: + :param hash: + :param kwargs: all params received on auth + :return: + """ + secret = hashlib.sha256(token.encode("utf-8")) + check_string = "\n".join(f"{k}={kwargs[k]}" for k in sorted(kwargs)) + hmac_string = hmac.new( + secret.digest(), check_string.encode("utf-8"), digestmod=hashlib.sha256 + ).hexdigest() + return hmac_string == hash + + +def check_integrity(token: str, data: Dict[str, Any]) -> bool: + """ + Verify the authentication and the integrity + of the data received on user's auth + + :param token: Bot's token + :param data: all data that came on auth + :return: + """ + return check_signature(token, **data) diff --git a/env/Lib/site-packages/aiogram/utils/backoff.py b/env/Lib/site-packages/aiogram/utils/backoff.py new file mode 100644 index 0000000..ebe08e9 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/backoff.py @@ -0,0 +1,83 @@ +import asyncio +import time +from dataclasses import dataclass +from random import normalvariate + + +@dataclass(frozen=True) +class BackoffConfig: + min_delay: float + max_delay: float + factor: float + jitter: float + + def __post_init__(self) -> None: + if self.max_delay <= self.min_delay: + raise ValueError("`max_delay` should be greater than `min_delay`") + if self.factor <= 1: + raise ValueError("`factor` should be greater than 1") + + +class Backoff: + def __init__(self, config: BackoffConfig) -> None: + self.config = config + self._next_delay = config.min_delay + self._current_delay = 0.0 + self._counter = 0 + + def __iter__(self) -> "Backoff": + return self + + @property + def min_delay(self) -> float: + return self.config.min_delay + + @property + def max_delay(self) -> float: + return self.config.max_delay + + @property + def factor(self) -> float: + return self.config.factor + + @property + def jitter(self) -> float: + return self.config.jitter + + @property + def next_delay(self) -> float: + return self._next_delay + + @property + def current_delay(self) -> float: + return self._current_delay + + @property + def counter(self) -> int: + return self._counter + + def sleep(self) -> None: + time.sleep(next(self)) + + async def asleep(self) -> None: + await asyncio.sleep(next(self)) + + def _calculate_next(self, value: float) -> float: + return normalvariate(min(value * self.factor, self.max_delay), self.jitter) + + def __next__(self) -> float: + self._current_delay = self._next_delay + self._next_delay = self._calculate_next(self._next_delay) + self._counter += 1 + return self._current_delay + + def reset(self) -> None: + self._current_delay = 0.0 + self._counter = 0 + self._next_delay = self.min_delay + + def __str__(self) -> str: + return ( + f"Backoff(tryings={self._counter}, current_delay={self._current_delay}, " + f"next_delay={self._next_delay})" + ) diff --git a/env/Lib/site-packages/aiogram/utils/callback_answer.py b/env/Lib/site-packages/aiogram/utils/callback_answer.py new file mode 100644 index 0000000..1515a7e --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/callback_answer.py @@ -0,0 +1,211 @@ +from typing import Any, Awaitable, Callable, Dict, Optional, Union + +from aiogram import BaseMiddleware, loggers +from aiogram.dispatcher.flags import get_flag +from aiogram.exceptions import CallbackAnswerException +from aiogram.methods import AnswerCallbackQuery +from aiogram.types import CallbackQuery, TelegramObject + + +class CallbackAnswer: + def __init__( + self, + answered: bool, + disabled: bool = False, + text: Optional[str] = None, + show_alert: Optional[bool] = None, + url: Optional[str] = None, + cache_time: Optional[int] = None, + ) -> None: + """ + Callback answer configuration + + :param answered: this request is already answered by middleware + :param disabled: answer will not be performed + :param text: answer with text + :param show_alert: show alert + :param url: game url + :param cache_time: cache answer for some time + """ + self._answered = answered + self._disabled = disabled + self._text = text + self._show_alert = show_alert + self._url = url + self._cache_time = cache_time + + def disable(self) -> None: + """ + Deactivate answering for this handler + """ + self.disabled = True + + @property + def disabled(self) -> bool: + """Indicates that automatic answer is disabled in this handler""" + return self._disabled + + @disabled.setter + def disabled(self, value: bool) -> None: + if self._answered: + raise CallbackAnswerException("Can't change disabled state after answer") + self._disabled = value + + @property + def answered(self) -> bool: + """ + Indicates that request is already answered by middleware + """ + return self._answered + + @property + def text(self) -> Optional[str]: + """ + Response text + :return: + """ + return self._text + + @text.setter + def text(self, value: Optional[str]) -> None: + if self._answered: + raise CallbackAnswerException("Can't change text after answer") + self._text = value + + @property + def show_alert(self) -> Optional[bool]: + """ + Whether to display an alert + """ + return self._show_alert + + @show_alert.setter + def show_alert(self, value: Optional[bool]) -> None: + if self._answered: + raise CallbackAnswerException("Can't change show_alert after answer") + self._show_alert = value + + @property + def url(self) -> Optional[str]: + """ + Game url + """ + return self._url + + @url.setter + def url(self, value: Optional[str]) -> None: + if self._answered: + raise CallbackAnswerException("Can't change url after answer") + self._url = value + + @property + def cache_time(self) -> Optional[int]: + """ + Response cache time + """ + return self._cache_time + + @cache_time.setter + def cache_time(self, value: Optional[int]) -> None: + if self._answered: + raise CallbackAnswerException("Can't change cache_time after answer") + self._cache_time = value + + def __str__(self) -> str: + args = ", ".join( + f"{k}={v!r}" + for k, v in { + "answered": self.answered, + "disabled": self.disabled, + "text": self.text, + "show_alert": self.show_alert, + "url": self.url, + "cache_time": self.cache_time, + }.items() + if v is not None + ) + return f"{type(self).__name__}({args})" + + +class CallbackAnswerMiddleware(BaseMiddleware): + def __init__( + self, + pre: bool = False, + text: Optional[str] = None, + show_alert: Optional[bool] = None, + url: Optional[str] = None, + cache_time: Optional[int] = None, + ) -> None: + """ + Inner middleware for callback query handlers, can be useful in bots with a lot of callback + handlers to automatically take answer to all requests + + :param pre: send answer before execute handler + :param text: answer with text + :param show_alert: show alert + :param url: game url + :param cache_time: cache answer for some time + """ + self.pre = pre + self.text = text + self.show_alert = show_alert + self.url = url + self.cache_time = cache_time + + async def __call__( + self, + handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + if not isinstance(event, CallbackQuery): + return await handler(event, data) + + callback_answer = data["callback_answer"] = self.construct_callback_answer( + properties=get_flag(data, "callback_answer") + ) + + if not callback_answer.disabled and callback_answer.answered: + await self.answer(event, callback_answer) + try: + return await handler(event, data) + finally: + if not callback_answer.disabled and not callback_answer.answered: + await self.answer(event, callback_answer) + + def construct_callback_answer( + self, properties: Optional[Union[Dict[str, Any], bool]] + ) -> CallbackAnswer: + pre, disabled, text, show_alert, url, cache_time = ( + self.pre, + False, + self.text, + self.show_alert, + self.url, + self.cache_time, + ) + if isinstance(properties, dict): + pre = properties.get("pre", pre) + disabled = properties.get("disabled", disabled) + text = properties.get("text", text) + show_alert = properties.get("show_alert", show_alert) + url = properties.get("url", url) + cache_time = properties.get("cache_time", cache_time) + + return CallbackAnswer( + answered=pre, + disabled=disabled, + text=text, + show_alert=show_alert, + url=url, + cache_time=cache_time, + ) + + def answer(self, event: CallbackQuery, callback_answer: CallbackAnswer) -> AnswerCallbackQuery: + loggers.middlewares.info("Answer to callback query id=%s", event.id) + return event.answer( + text=callback_answer.text, + show_alert=callback_answer.show_alert, + url=callback_answer.url, + cache_time=callback_answer.cache_time, + ) diff --git a/env/Lib/site-packages/aiogram/utils/chat_action.py b/env/Lib/site-packages/aiogram/utils/chat_action.py new file mode 100644 index 0000000..a2f3b46 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/chat_action.py @@ -0,0 +1,379 @@ +import asyncio +import logging +import time +from asyncio import Event, Lock +from contextlib import suppress +from types import TracebackType +from typing import Any, Awaitable, Callable, Dict, Optional, Type, Union + +from aiogram import BaseMiddleware, Bot +from aiogram.dispatcher.flags import get_flag +from aiogram.types import Message, TelegramObject + +logger = logging.getLogger(__name__) +DEFAULT_INTERVAL = 5.0 +DEFAULT_INITIAL_SLEEP = 0.0 + + +class ChatActionSender: + """ + This utility helps to automatically send chat action until long actions is done + to take acknowledge bot users the bot is doing something and not crashed. + + Provides simply to use context manager. + + Technically sender start background task with infinity loop which works + until action will be finished and sends the + `chat action `_ + every 5 seconds. + """ + + def __init__( + self, + *, + bot: Bot, + chat_id: Union[str, int], + message_thread_id: Optional[int] = None, + action: str = "typing", + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> None: + """ + :param bot: instance of the bot + :param chat_id: target chat id + :param message_thread_id: unique identifier for the target message thread; supergroups only + :param action: chat action type + :param interval: interval between iterations + :param initial_sleep: sleep before first sending of the action + """ + self.chat_id = chat_id + self.message_thread_id = message_thread_id + self.action = action + self.interval = interval + self.initial_sleep = initial_sleep + self.bot = bot + + self._lock = Lock() + self._close_event = Event() + self._closed_event = Event() + self._task: Optional[asyncio.Task[Any]] = None + + @property + def running(self) -> bool: + return bool(self._task) + + async def _wait(self, interval: float) -> None: + with suppress(asyncio.TimeoutError): + await asyncio.wait_for(self._close_event.wait(), interval) + + async def _worker(self) -> None: + logger.debug( + "Started chat action %r sender in chat_id=%s via bot id=%d", + self.action, + self.chat_id, + self.bot.id, + ) + try: + counter = 0 + await self._wait(self.initial_sleep) + while not self._close_event.is_set(): + start = time.monotonic() + logger.debug( + "Sent chat action %r to chat_id=%s via bot %d (already sent actions %d)", + self.action, + self.chat_id, + self.bot.id, + counter, + ) + await self.bot.send_chat_action( + chat_id=self.chat_id, + action=self.action, + message_thread_id=self.message_thread_id, + ) + counter += 1 + + interval = self.interval - (time.monotonic() - start) + await self._wait(interval) + finally: + logger.debug( + "Finished chat action %r sender in chat_id=%s via bot id=%d", + self.action, + self.chat_id, + self.bot.id, + ) + self._closed_event.set() + + async def _run(self) -> None: + async with self._lock: + self._close_event.clear() + self._closed_event.clear() + if self.running: + raise RuntimeError("Already running") + self._task = asyncio.create_task(self._worker()) + + async def _stop(self) -> None: + async with self._lock: + if not self.running: + return + if not self._close_event.is_set(): # pragma: no branches + self._close_event.set() + await self._closed_event.wait() + self._task = None + + async def __aenter__(self) -> "ChatActionSender": + await self._run() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> Any: + await self._stop() + + @classmethod + def typing( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `typing` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="typing", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def upload_photo( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `upload_photo` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="upload_photo", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def record_video( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `record_video` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="record_video", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def upload_video( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `upload_video` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="upload_video", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def record_voice( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `record_voice` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="record_voice", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def upload_voice( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `upload_voice` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="upload_voice", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def upload_document( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `upload_document` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="upload_document", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def choose_sticker( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `choose_sticker` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="choose_sticker", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def find_location( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `find_location` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="find_location", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def record_video_note( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `record_video_note` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="record_video_note", + interval=interval, + initial_sleep=initial_sleep, + ) + + @classmethod + def upload_video_note( + cls, + chat_id: Union[int, str], + bot: Bot, + message_thread_id: Optional[int] = None, + interval: float = DEFAULT_INTERVAL, + initial_sleep: float = DEFAULT_INITIAL_SLEEP, + ) -> "ChatActionSender": + """Create instance of the sender with `upload_video_note` action""" + return cls( + bot=bot, + chat_id=chat_id, + message_thread_id=message_thread_id, + action="upload_video_note", + interval=interval, + initial_sleep=initial_sleep, + ) + + +class ChatActionMiddleware(BaseMiddleware): + """ + Helps to automatically use chat action sender for all message handlers + """ + + async def __call__( + self, + handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + if not isinstance(event, Message): + return await handler(event, data) + bot = data["bot"] + + chat_action = get_flag(data, "chat_action") or "typing" + kwargs = {} + if isinstance(chat_action, dict): + if initial_sleep := chat_action.get("initial_sleep"): + kwargs["initial_sleep"] = initial_sleep + if interval := chat_action.get("interval"): + kwargs["interval"] = interval + if action := chat_action.get("action"): + kwargs["action"] = action + elif isinstance(chat_action, bool): + kwargs["action"] = "typing" + else: + kwargs["action"] = chat_action + kwargs["message_thread_id"] = ( + event.message_thread_id + if isinstance(event, Message) and event.is_topic_message + else None + ) + async with ChatActionSender(bot=bot, chat_id=event.chat.id, **kwargs): + return await handler(event, data) diff --git a/env/Lib/site-packages/aiogram/utils/chat_member.py b/env/Lib/site-packages/aiogram/utils/chat_member.py new file mode 100644 index 0000000..7ac666c --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/chat_member.py @@ -0,0 +1,37 @@ +from typing import Tuple, Type, Union + +from pydantic import Field, TypeAdapter +from typing_extensions import Annotated + +from aiogram.types import ( + ChatMember, + ChatMemberAdministrator, + ChatMemberBanned, + ChatMemberLeft, + ChatMemberMember, + ChatMemberOwner, + ChatMemberRestricted, +) + +ChatMemberUnion = Union[ + ChatMemberOwner, + ChatMemberAdministrator, + ChatMemberMember, + ChatMemberRestricted, + ChatMemberLeft, + ChatMemberBanned, +] + +ChatMemberCollection = Tuple[Type[ChatMember], ...] + +ChatMemberAdapter: TypeAdapter[ChatMemberUnion] = TypeAdapter( + Annotated[ + ChatMemberUnion, + Field(discriminator="status"), + ] +) + +ADMINS: ChatMemberCollection = (ChatMemberOwner, ChatMemberAdministrator) +USERS: ChatMemberCollection = (ChatMemberMember, ChatMemberRestricted) +MEMBERS: ChatMemberCollection = ADMINS + USERS +NOT_MEMBERS: ChatMemberCollection = (ChatMemberLeft, ChatMemberBanned) diff --git a/env/Lib/site-packages/aiogram/utils/deep_linking.py b/env/Lib/site-packages/aiogram/utils/deep_linking.py new file mode 100644 index 0000000..19cc64c --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/deep_linking.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +__all__ = [ + "create_start_link", + "create_startgroup_link", + "create_deep_link", + "create_telegram_link", + "encode_payload", + "decode_payload", +] + +import re +from typing import TYPE_CHECKING, Callable, Literal, Optional, cast + +from aiogram.utils.link import create_telegram_link +from aiogram.utils.payload import decode_payload, encode_payload + +if TYPE_CHECKING: + from aiogram import Bot + +BAD_PATTERN = re.compile(r"[^A-z0-9-]") + + +async def create_start_link( + bot: Bot, + payload: str, + encode: bool = False, + encoder: Optional[Callable[[bytes], bytes]] = None, +) -> str: + """ + Create 'start' deep link with your payload. + + If you need to encode payload or pass special characters - + set encode as True + + :param bot: bot instance + :param payload: args passed with /start + :param encode: encode payload with base64url or custom encoder + :param encoder: custom encoder callable + :return: link + """ + username = (await bot.me()).username + return create_deep_link( + username=cast(str, username), + link_type="start", + payload=payload, + encode=encode, + encoder=encoder, + ) + + +async def create_startgroup_link( + bot: Bot, + payload: str, + encode: bool = False, + encoder: Optional[Callable[[bytes], bytes]] = None, +) -> str: + """ + Create 'startgroup' deep link with your payload. + + If you need to encode payload or pass special characters - + set encode as True + + :param bot: bot instance + :param payload: args passed with /start + :param encode: encode payload with base64url or custom encoder + :param encoder: custom encoder callable + :return: link + """ + username = (await bot.me()).username + return create_deep_link( + username=cast(str, username), + link_type="startgroup", + payload=payload, + encode=encode, + encoder=encoder, + ) + + +def create_deep_link( + username: str, + link_type: Literal["start", "startgroup"], + payload: str, + encode: bool = False, + encoder: Optional[Callable[[bytes], bytes]] = None, +) -> str: + """ + Create deep link. + + :param username: + :param link_type: `start` or `startgroup` + :param payload: any string-convertible data + :param encode: encode payload with base64url or custom encoder + :param encoder: custom encoder callable + :return: deeplink + """ + if not isinstance(payload, str): + payload = str(payload) + + if encode or encoder: + payload = encode_payload(payload, encoder=encoder) + + if re.search(BAD_PATTERN, payload): + raise ValueError( + "Wrong payload! Only A-Z, a-z, 0-9, _ and - are allowed. " + "Pass `encode=True` or encode payload manually." + ) + + if len(payload) > 64: + raise ValueError("Payload must be up to 64 characters long.") + + return create_telegram_link(username, **{cast(str, link_type): payload}) diff --git a/env/Lib/site-packages/aiogram/utils/formatting.py b/env/Lib/site-packages/aiogram/utils/formatting.py new file mode 100644 index 0000000..929afc0 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/formatting.py @@ -0,0 +1,632 @@ +import textwrap +from typing import ( + Any, + ClassVar, + Dict, + Generator, + Iterable, + Iterator, + List, + Optional, + Tuple, + Type, +) + +from typing_extensions import Self + +from aiogram.enums import MessageEntityType +from aiogram.types import MessageEntity, User +from aiogram.utils.text_decorations import ( + add_surrogates, + html_decoration, + markdown_decoration, + remove_surrogates, +) + +NodeType = Any + + +def sizeof(value: str) -> int: + return len(value.encode("utf-16-le")) // 2 + + +class Text(Iterable[NodeType]): + """ + Simple text element + """ + + type: ClassVar[Optional[str]] = None + + __slots__ = ("_body", "_params") + + def __init__( + self, + *body: NodeType, + **params: Any, + ) -> None: + self._body: Tuple[NodeType, ...] = body + self._params: Dict[str, Any] = params + + @classmethod + def from_entities(cls, text: str, entities: List[MessageEntity]) -> "Text": + return cls( + *_unparse_entities( + text=add_surrogates(text), + entities=sorted(entities, key=lambda item: item.offset) if entities else [], + ) + ) + + def render( + self, + *, + _offset: int = 0, + _sort: bool = True, + _collect_entities: bool = True, + ) -> Tuple[str, List[MessageEntity]]: + """ + Render elements tree as text with entities list + + :return: + """ + + text = "" + entities = [] + offset = _offset + + for node in self._body: + if not isinstance(node, Text): + node = str(node) + text += node + offset += sizeof(node) + else: + node_text, node_entities = node.render( + _offset=offset, + _sort=False, + _collect_entities=_collect_entities, + ) + text += node_text + offset += sizeof(node_text) + if _collect_entities: + entities.extend(node_entities) + + if _collect_entities and self.type: + entities.append(self._render_entity(offset=_offset, length=offset - _offset)) + + if _collect_entities and _sort: + entities.sort(key=lambda entity: entity.offset) + + return text, entities + + def _render_entity(self, *, offset: int, length: int) -> MessageEntity: + assert self.type is not None, "Node without type can't be rendered as entity" + return MessageEntity(type=self.type, offset=offset, length=length, **self._params) + + def as_kwargs( + self, + *, + text_key: str = "text", + entities_key: str = "entities", + replace_parse_mode: bool = True, + parse_mode_key: str = "parse_mode", + ) -> Dict[str, Any]: + """ + Render elements tree as keyword arguments for usage in the API call, for example: + + .. code-block:: python + + entities = Text(...) + await message.answer(**entities.as_kwargs()) + + :param text_key: + :param entities_key: + :param replace_parse_mode: + :param parse_mode_key: + :return: + """ + text_value, entities_value = self.render() + result: Dict[str, Any] = { + text_key: text_value, + entities_key: entities_value, + } + if replace_parse_mode: + result[parse_mode_key] = None + return result + + def as_html(self) -> str: + """ + Render elements tree as HTML markup + """ + text, entities = self.render() + return html_decoration.unparse(text, entities) + + def as_markdown(self) -> str: + """ + Render elements tree as MarkdownV2 markup + """ + text, entities = self.render() + return markdown_decoration.unparse(text, entities) + + def replace(self: Self, *args: Any, **kwargs: Any) -> Self: + return type(self)(*args, **{**self._params, **kwargs}) + + def as_pretty_string(self, indent: bool = False) -> str: + sep = ",\n" if indent else ", " + body = sep.join( + item.as_pretty_string(indent=indent) if isinstance(item, Text) else repr(item) + for item in self._body + ) + params = sep.join(f"{k}={v!r}" for k, v in self._params.items() if v is not None) + + args = [] + if body: + args.append(body) + if params: + args.append(params) + + args_str = sep.join(args) + if indent: + args_str = textwrap.indent("\n" + args_str + "\n", " ") + return f"{type(self).__name__}({args_str})" + + def __add__(self, other: NodeType) -> "Text": + if isinstance(other, Text) and other.type == self.type and self._params == other._params: + return type(self)(*self, *other, **self._params) + if type(self) is Text and isinstance(other, str): + return type(self)(*self, other, **self._params) + return Text(self, other) + + def __iter__(self) -> Iterator[NodeType]: + yield from self._body + + def __len__(self) -> int: + text, _ = self.render(_collect_entities=False) + return sizeof(text) + + def __getitem__(self, item: slice) -> "Text": + if not isinstance(item, slice): + raise TypeError("Can only be sliced") + if (item.start is None or item.start == 0) and item.stop is None: + return self.replace(*self._body) + start = 0 if item.start is None else item.start + stop = len(self) if item.stop is None else item.stop + if start == stop: + return self.replace() + + nodes = [] + position = 0 + + for node in self._body: + node_size = len(node) + current_position = position + position += node_size + if position < start: + continue + if current_position > stop: + break + a = max((0, start - current_position)) + b = min((node_size, stop - current_position)) + new_node = node[a:b] + if not new_node: + continue + nodes.append(new_node) + + return self.replace(*nodes) + + +class HashTag(Text): + """ + Hashtag element. + + .. warning:: + + The value should always start with '#' symbol + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.HASHTAG` + """ + + type = MessageEntityType.HASHTAG + + def __init__(self, *body: NodeType, **params: Any) -> None: + if len(body) != 1: + raise ValueError("Hashtag can contain only one element") + if not isinstance(body[0], str): + raise ValueError("Hashtag can contain only string") + if not body[0].startswith("#"): + body = ("#" + body[0],) + super().__init__(*body, **params) + + +class CashTag(Text): + """ + Cashtag element. + + .. warning:: + + The value should always start with '$' symbol + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.CASHTAG` + """ + + type = MessageEntityType.CASHTAG + + def __init__(self, *body: NodeType, **params: Any) -> None: + if len(body) != 1: + raise ValueError("Cashtag can contain only one element") + if not isinstance(body[0], str): + raise ValueError("Cashtag can contain only string") + if not body[0].startswith("$"): + body = ("$" + body[0],) + super().__init__(*body, **params) + + +class BotCommand(Text): + """ + Bot command element. + + .. warning:: + + The value should always start with '/' symbol + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.BOT_COMMAND` + """ + + type = MessageEntityType.BOT_COMMAND + + +class Url(Text): + """ + Url element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.URL` + """ + + type = MessageEntityType.URL + + +class Email(Text): + """ + Email element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.EMAIL` + """ + + type = MessageEntityType.EMAIL + + +class PhoneNumber(Text): + """ + Phone number element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.PHONE_NUMBER` + """ + + type = MessageEntityType.PHONE_NUMBER + + +class Bold(Text): + """ + Bold element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.BOLD` + """ + + type = MessageEntityType.BOLD + + +class Italic(Text): + """ + Italic element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.ITALIC` + """ + + type = MessageEntityType.ITALIC + + +class Underline(Text): + """ + Underline element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.UNDERLINE` + """ + + type = MessageEntityType.UNDERLINE + + +class Strikethrough(Text): + """ + Strikethrough element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.STRIKETHROUGH` + """ + + type = MessageEntityType.STRIKETHROUGH + + +class Spoiler(Text): + """ + Spoiler element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.SPOILER` + """ + + type = MessageEntityType.SPOILER + + +class Code(Text): + """ + Code element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.CODE` + """ + + type = MessageEntityType.CODE + + +class Pre(Text): + """ + Pre element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.PRE` + """ + + type = MessageEntityType.PRE + + def __init__(self, *body: NodeType, language: Optional[str] = None, **params: Any) -> None: + super().__init__(*body, language=language, **params) + + +class TextLink(Text): + """ + Text link element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.TEXT_LINK` + """ + + type = MessageEntityType.TEXT_LINK + + def __init__(self, *body: NodeType, url: str, **params: Any) -> None: + super().__init__(*body, url=url, **params) + + +class TextMention(Text): + """ + Text mention element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.TEXT_MENTION` + """ + + type = MessageEntityType.TEXT_MENTION + + def __init__(self, *body: NodeType, user: User, **params: Any) -> None: + super().__init__(*body, user=user, **params) + + +class CustomEmoji(Text): + """ + Custom emoji element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.CUSTOM_EMOJI` + """ + + type = MessageEntityType.CUSTOM_EMOJI + + def __init__(self, *body: NodeType, custom_emoji_id: str, **params: Any) -> None: + super().__init__(*body, custom_emoji_id=custom_emoji_id, **params) + + +class BlockQuote(Text): + """ + Block quote element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.BLOCKQUOTE` + """ + + type = MessageEntityType.BLOCKQUOTE + + +class ExpandableBlockQuote(Text): + """ + Expandable block quote element. + + Will be wrapped into :obj:`aiogram.types.message_entity.MessageEntity` + with type :obj:`aiogram.enums.message_entity_type.MessageEntityType.EXPANDABLE_BLOCKQUOTE` + """ + + type = MessageEntityType.EXPANDABLE_BLOCKQUOTE + + +NODE_TYPES: Dict[Optional[str], Type[Text]] = { + Text.type: Text, + HashTag.type: HashTag, + CashTag.type: CashTag, + BotCommand.type: BotCommand, + Url.type: Url, + Email.type: Email, + PhoneNumber.type: PhoneNumber, + Bold.type: Bold, + Italic.type: Italic, + Underline.type: Underline, + Strikethrough.type: Strikethrough, + Spoiler.type: Spoiler, + Code.type: Code, + Pre.type: Pre, + TextLink.type: TextLink, + TextMention.type: TextMention, + CustomEmoji.type: CustomEmoji, + BlockQuote.type: BlockQuote, + ExpandableBlockQuote.type: ExpandableBlockQuote, +} + + +def _apply_entity(entity: MessageEntity, *nodes: NodeType) -> NodeType: + """ + Apply single entity to text + + :param entity: + :param text: + :return: + """ + node_type = NODE_TYPES.get(entity.type, Text) + return node_type( + *nodes, **entity.model_dump(exclude={"type", "offset", "length"}, warnings=False) + ) + + +def _unparse_entities( + text: bytes, + entities: List[MessageEntity], + offset: Optional[int] = None, + length: Optional[int] = None, +) -> Generator[NodeType, None, None]: + if offset is None: + offset = 0 + length = length or len(text) + + for index, entity in enumerate(entities): + if entity.offset * 2 < offset: + continue + if entity.offset * 2 > offset: + yield remove_surrogates(text[offset : entity.offset * 2]) + start = entity.offset * 2 + offset = entity.offset * 2 + entity.length * 2 + + sub_entities = list(filter(lambda e: e.offset * 2 < (offset or 0), entities[index + 1 :])) + yield _apply_entity( + entity, + *_unparse_entities(text, sub_entities, offset=start, length=offset), + ) + + if offset < length: + yield remove_surrogates(text[offset:length]) + + +def as_line(*items: NodeType, end: str = "\n", sep: str = "") -> Text: + """ + Wrap multiple nodes into line with :code:`\\\\n` at the end of line. + + :param items: Text or Any + :param end: ending of the line, by default is :code:`\\\\n` + :param sep: separator between items, by default is empty string + :return: Text + """ + if sep: + nodes = [] + for item in items[:-1]: + nodes.extend([item, sep]) + nodes.append(items[-1]) + nodes.append(end) + else: + nodes = [*items, end] + return Text(*nodes) + + +def as_list(*items: NodeType, sep: str = "\n") -> Text: + """ + Wrap each element to separated lines + + :param items: + :param sep: + :return: + """ + nodes = [] + for item in items[:-1]: + nodes.extend([item, sep]) + nodes.append(items[-1]) + return Text(*nodes) + + +def as_marked_list(*items: NodeType, marker: str = "- ") -> Text: + """ + Wrap elements as marked list + + :param items: + :param marker: line marker, by default is '- ' + :return: Text + """ + return as_list(*(Text(marker, item) for item in items)) + + +def as_numbered_list(*items: NodeType, start: int = 1, fmt: str = "{}. ") -> Text: + """ + Wrap elements as numbered list + + :param items: + :param start: initial number, by default 1 + :param fmt: number format, by default '{}. ' + :return: Text + """ + return as_list(*(Text(fmt.format(index), item) for index, item in enumerate(items, start))) + + +def as_section(title: NodeType, *body: NodeType) -> Text: + """ + Wrap elements as simple section, section has title and body + + :param title: + :param body: + :return: Text + """ + return Text(title, "\n", *body) + + +def as_marked_section( + title: NodeType, + *body: NodeType, + marker: str = "- ", +) -> Text: + """ + Wrap elements as section with marked list + + :param title: + :param body: + :param marker: + :return: + """ + return as_section(title, as_marked_list(*body, marker=marker)) + + +def as_numbered_section( + title: NodeType, + *body: NodeType, + start: int = 1, + fmt: str = "{}. ", +) -> Text: + """ + Wrap elements as section with numbered list + + :param title: + :param body: + :param start: + :param fmt: + :return: + """ + return as_section(title, as_numbered_list(*body, start=start, fmt=fmt)) + + +def as_key_value(key: NodeType, value: NodeType) -> Text: + """ + Wrap elements pair as key-value line. (:code:`{key}: {value}`) + + :param key: + :param value: + :return: Text + """ + return Text(Bold(key, ":"), " ", value) diff --git a/env/Lib/site-packages/aiogram/utils/i18n/__init__.py b/env/Lib/site-packages/aiogram/utils/i18n/__init__.py new file mode 100644 index 0000000..e48a4c7 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/i18n/__init__.py @@ -0,0 +1,21 @@ +from .context import get_i18n, gettext, lazy_gettext, lazy_ngettext, ngettext +from .core import I18n +from .middleware import ( + ConstI18nMiddleware, + FSMI18nMiddleware, + I18nMiddleware, + SimpleI18nMiddleware, +) + +__all__ = ( + "I18n", + "I18nMiddleware", + "SimpleI18nMiddleware", + "ConstI18nMiddleware", + "FSMI18nMiddleware", + "gettext", + "lazy_gettext", + "ngettext", + "lazy_ngettext", + "get_i18n", +) diff --git a/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..2c2b941 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/context.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/context.cpython-311.pyc new file mode 100644 index 0000000..a5d7d57 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/context.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/core.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/core.cpython-311.pyc new file mode 100644 index 0000000..63f7bad Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/core.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/lazy_proxy.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/lazy_proxy.cpython-311.pyc new file mode 100644 index 0000000..249c914 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/lazy_proxy.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/middleware.cpython-311.pyc b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/middleware.cpython-311.pyc new file mode 100644 index 0000000..d502885 Binary files /dev/null and b/env/Lib/site-packages/aiogram/utils/i18n/__pycache__/middleware.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/utils/i18n/context.py b/env/Lib/site-packages/aiogram/utils/i18n/context.py new file mode 100644 index 0000000..245fee3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/i18n/context.py @@ -0,0 +1,23 @@ +from typing import Any + +from aiogram.utils.i18n.core import I18n +from aiogram.utils.i18n.lazy_proxy import LazyProxy + + +def get_i18n() -> I18n: + i18n = I18n.get_current(no_error=True) + if i18n is None: + raise LookupError("I18n context is not set") + return i18n + + +def gettext(*args: Any, **kwargs: Any) -> str: + return get_i18n().gettext(*args, **kwargs) + + +def lazy_gettext(*args: Any, **kwargs: Any) -> LazyProxy: + return LazyProxy(gettext, *args, **kwargs, enable_cache=False) + + +ngettext = gettext +lazy_ngettext = lazy_gettext diff --git a/env/Lib/site-packages/aiogram/utils/i18n/core.py b/env/Lib/site-packages/aiogram/utils/i18n/core.py new file mode 100644 index 0000000..db7c797 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/i18n/core.py @@ -0,0 +1,123 @@ +import gettext +import os +from contextlib import contextmanager +from contextvars import ContextVar +from pathlib import Path +from typing import Dict, Generator, Optional, Tuple, Union + +from aiogram.utils.i18n.lazy_proxy import LazyProxy +from aiogram.utils.mixins import ContextInstanceMixin + + +class I18n(ContextInstanceMixin["I18n"]): + def __init__( + self, + *, + path: Union[str, Path], + default_locale: str = "en", + domain: str = "messages", + ) -> None: + self.path = path + self.default_locale = default_locale + self.domain = domain + self.ctx_locale = ContextVar("aiogram_ctx_locale", default=default_locale) + self.locales = self.find_locales() + + @property + def current_locale(self) -> str: + return self.ctx_locale.get() + + @current_locale.setter + def current_locale(self, value: str) -> None: + self.ctx_locale.set(value) + + @contextmanager + def use_locale(self, locale: str) -> Generator[None, None, None]: + """ + Create context with specified locale + """ + ctx_token = self.ctx_locale.set(locale) + try: + yield + finally: + self.ctx_locale.reset(ctx_token) + + @contextmanager + def context(self) -> Generator["I18n", None, None]: + """ + Use I18n context + """ + token = self.set_current(self) + try: + yield self + finally: + self.reset_current(token) + + def find_locales(self) -> Dict[str, gettext.GNUTranslations]: + """ + Load all compiled locales from path + + :return: dict with locales + """ + translations: Dict[str, gettext.GNUTranslations] = {} + + for name in os.listdir(self.path): + if not os.path.isdir(os.path.join(self.path, name)): + continue + mo_path = os.path.join(self.path, name, "LC_MESSAGES", self.domain + ".mo") + + if os.path.exists(mo_path): + with open(mo_path, "rb") as fp: + translations[name] = gettext.GNUTranslations(fp) + elif os.path.exists(mo_path[:-2] + "po"): # pragma: no cover + raise RuntimeError(f"Found locale '{name}' but this language is not compiled!") + + return translations + + def reload(self) -> None: + """ + Hot reload locales + """ + self.locales = self.find_locales() + + @property + def available_locales(self) -> Tuple[str, ...]: + """ + list of loaded locales + + :return: + """ + return tuple(self.locales.keys()) + + def gettext( + self, singular: str, plural: Optional[str] = None, n: int = 1, locale: Optional[str] = None + ) -> str: + """ + Get text + + :param singular: + :param plural: + :param n: + :param locale: + :return: + """ + if locale is None: + locale = self.current_locale + + if locale not in self.locales: + if n == 1: + return singular + return plural if plural else singular + + translator = self.locales[locale] + + if plural is None: + return translator.gettext(singular) + return translator.ngettext(singular, plural, n) + + def lazy_gettext( + self, singular: str, plural: Optional[str] = None, n: int = 1, locale: Optional[str] = None + ) -> LazyProxy: + return LazyProxy( + self.gettext, singular=singular, plural=plural, n=n, locale=locale, enable_cache=False + ) diff --git a/env/Lib/site-packages/aiogram/utils/i18n/lazy_proxy.py b/env/Lib/site-packages/aiogram/utils/i18n/lazy_proxy.py new file mode 100644 index 0000000..6852540 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/i18n/lazy_proxy.py @@ -0,0 +1,13 @@ +from typing import Any + +try: + from babel.support import LazyProxy +except ImportError: # pragma: no cover + + class LazyProxy: # type: ignore + def __init__(self, func: Any, *args: Any, **kwargs: Any) -> None: + raise RuntimeError( + "LazyProxy can be used only when Babel installed\n" + "Just install Babel (`pip install Babel`) " + "or aiogram with i18n support (`pip install aiogram[i18n]`)" + ) diff --git a/env/Lib/site-packages/aiogram/utils/i18n/middleware.py b/env/Lib/site-packages/aiogram/utils/i18n/middleware.py new file mode 100644 index 0000000..68be22b --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/i18n/middleware.py @@ -0,0 +1,187 @@ +from abc import ABC, abstractmethod +from typing import Any, Awaitable, Callable, Dict, Optional, Set + +try: + from babel import Locale, UnknownLocaleError +except ImportError: # pragma: no cover + Locale = None # type: ignore + + class UnknownLocaleError(Exception): # type: ignore + pass + + +from aiogram import BaseMiddleware, Router +from aiogram.fsm.context import FSMContext +from aiogram.types import TelegramObject, User +from aiogram.utils.i18n.core import I18n + + +class I18nMiddleware(BaseMiddleware, ABC): + """ + Abstract I18n middleware. + """ + + def __init__( + self, + i18n: I18n, + i18n_key: Optional[str] = "i18n", + middleware_key: str = "i18n_middleware", + ) -> None: + """ + Create an instance of middleware + + :param i18n: instance of I18n + :param i18n_key: context key for I18n instance + :param middleware_key: context key for this middleware + """ + self.i18n = i18n + self.i18n_key = i18n_key + self.middleware_key = middleware_key + + def setup( + self: BaseMiddleware, router: Router, exclude: Optional[Set[str]] = None + ) -> BaseMiddleware: + """ + Register middleware for all events in the Router + + :param router: + :param exclude: + :return: + """ + if exclude is None: + exclude = set() + exclude_events = {"update", *exclude} + for event_name, observer in router.observers.items(): + if event_name in exclude_events: + continue + observer.outer_middleware(self) + return self + + async def __call__( + self, + handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]], + event: TelegramObject, + data: Dict[str, Any], + ) -> Any: + current_locale = await self.get_locale(event=event, data=data) or self.i18n.default_locale + + if self.i18n_key: + data[self.i18n_key] = self.i18n + if self.middleware_key: + data[self.middleware_key] = self + + with self.i18n.context(), self.i18n.use_locale(current_locale): + return await handler(event, data) + + @abstractmethod + async def get_locale(self, event: TelegramObject, data: Dict[str, Any]) -> str: + """ + Detect current user locale based on event and context. + + **This method must be defined in child classes** + + :param event: + :param data: + :return: + """ + pass + + +class SimpleI18nMiddleware(I18nMiddleware): + """ + Simple I18n middleware. + + Chooses language code from the User object received in event + """ + + def __init__( + self, + i18n: I18n, + i18n_key: Optional[str] = "i18n", + middleware_key: str = "i18n_middleware", + ) -> None: + super().__init__(i18n=i18n, i18n_key=i18n_key, middleware_key=middleware_key) + + if Locale is None: # pragma: no cover + raise RuntimeError( + f"{type(self).__name__} can be used only when Babel installed\n" + "Just install Babel (`pip install Babel`) " + "or aiogram with i18n support (`pip install aiogram[i18n]`)" + ) + + async def get_locale(self, event: TelegramObject, data: Dict[str, Any]) -> str: + if Locale is None: # pragma: no cover + raise RuntimeError( + f"{type(self).__name__} can be used only when Babel installed\n" + "Just install Babel (`pip install Babel`) " + "or aiogram with i18n support (`pip install aiogram[i18n]`)" + ) + + event_from_user: Optional[User] = data.get("event_from_user", None) + if event_from_user is None or event_from_user.language_code is None: + return self.i18n.default_locale + try: + locale = Locale.parse(event_from_user.language_code, sep="-") + except UnknownLocaleError: + return self.i18n.default_locale + + if locale.language not in self.i18n.available_locales: + return self.i18n.default_locale + return locale.language + + +class ConstI18nMiddleware(I18nMiddleware): + """ + Const middleware chooses statically defined locale + """ + + def __init__( + self, + locale: str, + i18n: I18n, + i18n_key: Optional[str] = "i18n", + middleware_key: str = "i18n_middleware", + ) -> None: + super().__init__(i18n=i18n, i18n_key=i18n_key, middleware_key=middleware_key) + self.locale = locale + + async def get_locale(self, event: TelegramObject, data: Dict[str, Any]) -> str: + return self.locale + + +class FSMI18nMiddleware(SimpleI18nMiddleware): + """ + This middleware stores locale in the FSM storage + """ + + def __init__( + self, + i18n: I18n, + key: str = "locale", + i18n_key: Optional[str] = "i18n", + middleware_key: str = "i18n_middleware", + ) -> None: + super().__init__(i18n=i18n, i18n_key=i18n_key, middleware_key=middleware_key) + self.key = key + + async def get_locale(self, event: TelegramObject, data: Dict[str, Any]) -> str: + fsm_context: Optional[FSMContext] = data.get("state") + locale = None + if fsm_context: + fsm_data = await fsm_context.get_data() + locale = fsm_data.get(self.key, None) + if not locale: + locale = await super().get_locale(event=event, data=data) + if fsm_context: + await fsm_context.update_data(data={self.key: locale}) + return locale + + async def set_locale(self, state: FSMContext, locale: str) -> None: + """ + Write new locale to the storage + + :param state: instance of FSMContext + :param locale: new locale + """ + await state.update_data(data={self.key: locale}) + self.i18n.current_locale = locale diff --git a/env/Lib/site-packages/aiogram/utils/keyboard.py b/env/Lib/site-packages/aiogram/utils/keyboard.py new file mode 100644 index 0000000..921c28c --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/keyboard.py @@ -0,0 +1,421 @@ +from __future__ import annotations + +from abc import ABC +from copy import deepcopy +from itertools import chain +from itertools import cycle as repeat_all +from typing import ( + TYPE_CHECKING, + Any, + Generator, + Generic, + Iterable, + List, + Optional, + Type, + TypeVar, + Union, + cast, +) + +from aiogram.filters.callback_data import CallbackData +from aiogram.types import ( + CallbackGame, + InlineKeyboardButton, + InlineKeyboardMarkup, + KeyboardButton, + KeyboardButtonPollType, + KeyboardButtonRequestChat, + KeyboardButtonRequestUsers, + LoginUrl, + ReplyKeyboardMarkup, + SwitchInlineQueryChosenChat, + WebAppInfo, +) + +ButtonType = TypeVar("ButtonType", InlineKeyboardButton, KeyboardButton) +T = TypeVar("T") + + +class KeyboardBuilder(Generic[ButtonType], ABC): + """ + Generic keyboard builder that helps to adjust your markup with defined shape of lines. + + Works both of InlineKeyboardMarkup and ReplyKeyboardMarkup. + """ + + max_width: int = 0 + min_width: int = 0 + max_buttons: int = 0 + + def __init__( + self, button_type: Type[ButtonType], markup: Optional[List[List[ButtonType]]] = None + ) -> None: + if not issubclass(button_type, (InlineKeyboardButton, KeyboardButton)): + raise ValueError(f"Button type {button_type} are not allowed here") + self._button_type: Type[ButtonType] = button_type + if markup: + self._validate_markup(markup) + else: + markup = [] + self._markup: List[List[ButtonType]] = markup + + @property + def buttons(self) -> Generator[ButtonType, None, None]: + """ + Get flatten set of all buttons + + :return: + """ + yield from chain.from_iterable(self.export()) + + def _validate_button(self, button: ButtonType) -> bool: + """ + Check that button item has correct type + + :param button: + :return: + """ + allowed = self._button_type + if not isinstance(button, allowed): + raise ValueError( + f"{button!r} should be type {allowed.__name__!r} not {type(button).__name__!r}" + ) + return True + + def _validate_buttons(self, *buttons: ButtonType) -> bool: + """ + Check that all passed button has correct type + + :param buttons: + :return: + """ + return all(map(self._validate_button, buttons)) + + def _validate_row(self, row: List[ButtonType]) -> bool: + """ + Check that row of buttons are correct + Row can be only list of allowed button types and has length 0 <= n <= 8 + + :param row: + :return: + """ + if not isinstance(row, list): + raise ValueError( + f"Row {row!r} should be type 'List[{self._button_type.__name__}]' " + f"not type {type(row).__name__}" + ) + if len(row) > self.max_width: + raise ValueError(f"Row {row!r} is too long (max width: {self.max_width})") + self._validate_buttons(*row) + return True + + def _validate_markup(self, markup: List[List[ButtonType]]) -> bool: + """ + Check that passed markup has correct data structure + Markup is list of lists of buttons + + :param markup: + :return: + """ + count = 0 + if not isinstance(markup, list): + raise ValueError( + f"Markup should be type 'List[List[{self._button_type.__name__}]]' " + f"not type {type(markup).__name__!r}" + ) + for row in markup: + self._validate_row(row) + count += len(row) + if count > self.max_buttons: + raise ValueError(f"Too much buttons detected Max allowed count - {self.max_buttons}") + return True + + def _validate_size(self, size: Any) -> int: + """ + Validate that passed size is legit + + :param size: + :return: + """ + if not isinstance(size, int): + raise ValueError("Only int sizes are allowed") + if size not in range(self.min_width, self.max_width + 1): + raise ValueError( + f"Row size {size} is not allowed, range: [{self.min_width}, {self.max_width}]" + ) + return size + + def export(self) -> List[List[ButtonType]]: + """ + Export configured markup as list of lists of buttons + + .. code-block:: python + + >>> builder = KeyboardBuilder(button_type=InlineKeyboardButton) + >>> ... # Add buttons to builder + >>> markup = InlineKeyboardMarkup(inline_keyboard=builder.export()) + + :return: + """ + return deepcopy(self._markup) + + def add(self, *buttons: ButtonType) -> "KeyboardBuilder[ButtonType]": + """ + Add one or many buttons to markup. + + :param buttons: + :return: + """ + self._validate_buttons(*buttons) + markup = self.export() + + # Try to add new buttons to the end of last row if it possible + if markup and len(markup[-1]) < self.max_width: + last_row = markup[-1] + pos = self.max_width - len(last_row) + head, buttons = buttons[:pos], buttons[pos:] + last_row.extend(head) + + # Separate buttons to exclusive rows with max possible row width + while buttons: + row, buttons = buttons[: self.max_width], buttons[self.max_width :] + markup.append(list(row)) + + self._markup = markup + return self + + def row( + self, *buttons: ButtonType, width: Optional[int] = None + ) -> "KeyboardBuilder[ButtonType]": + """ + Add row to markup + + When too much buttons is passed it will be separated to many rows + + :param buttons: + :param width: + :return: + """ + if width is None: + width = self.max_width + + self._validate_size(width) + self._validate_buttons(*buttons) + self._markup.extend( + list(buttons[pos : pos + width]) for pos in range(0, len(buttons), width) + ) + return self + + def adjust(self, *sizes: int, repeat: bool = False) -> "KeyboardBuilder[ButtonType]": + """ + Adjust previously added buttons to specific row sizes. + + By default, when the sum of passed sizes is lower than buttons count the last + one size will be used for tail of the markup. + If repeat=True is passed - all sizes will be cycled when available more buttons + count than all sizes + + :param sizes: + :param repeat: + :return: + """ + if not sizes: + sizes = (self.max_width,) + + validated_sizes = map(self._validate_size, sizes) + sizes_iter = repeat_all(validated_sizes) if repeat else repeat_last(validated_sizes) + size = next(sizes_iter) + + markup = [] + row: List[ButtonType] = [] + for button in self.buttons: + if len(row) >= size: + markup.append(row) + size = next(sizes_iter) + row = [] + row.append(button) + if row: + markup.append(row) + self._markup = markup + return self + + def _button(self, **kwargs: Any) -> "KeyboardBuilder[ButtonType]": + """ + Add button to markup + + :param kwargs: + :return: + """ + if isinstance(callback_data := kwargs.get("callback_data", None), CallbackData): + kwargs["callback_data"] = callback_data.pack() + button = self._button_type(**kwargs) + return self.add(button) + + def as_markup(self, **kwargs: Any) -> Union[InlineKeyboardMarkup, ReplyKeyboardMarkup]: + if self._button_type is KeyboardButton: + keyboard = cast(List[List[KeyboardButton]], self.export()) # type: ignore + return ReplyKeyboardMarkup(keyboard=keyboard, **kwargs) + inline_keyboard = cast(List[List[InlineKeyboardButton]], self.export()) # type: ignore + return InlineKeyboardMarkup(inline_keyboard=inline_keyboard) + + def attach(self, builder: "KeyboardBuilder[ButtonType]") -> "KeyboardBuilder[ButtonType]": + if not isinstance(builder, KeyboardBuilder): + raise ValueError(f"Only KeyboardBuilder can be attached, not {type(builder).__name__}") + if builder._button_type is not self._button_type: + raise ValueError( + f"Only builders with same button type can be attached, " + f"not {self._button_type.__name__} and {builder._button_type.__name__}" + ) + self._markup.extend(builder.export()) + return self + + +def repeat_last(items: Iterable[T]) -> Generator[T, None, None]: + items_iter = iter(items) + try: + value = next(items_iter) + except StopIteration: # pragma: no cover + # Possible case but not in place where this function is used + return + yield value + finished = False + while True: + if not finished: + try: + value = next(items_iter) + except StopIteration: + finished = True + yield value + + +class InlineKeyboardBuilder(KeyboardBuilder[InlineKeyboardButton]): + """ + Inline keyboard builder inherits all methods from generic builder + """ + + max_width: int = 8 + min_width: int = 1 + max_buttons: int = 100 + + def button( + self, + *, + text: str, + url: Optional[str] = None, + callback_data: Optional[Union[str, CallbackData]] = None, + web_app: Optional[WebAppInfo] = None, + login_url: Optional[LoginUrl] = None, + switch_inline_query: Optional[str] = None, + switch_inline_query_current_chat: Optional[str] = None, + switch_inline_query_chosen_chat: Optional[SwitchInlineQueryChosenChat] = None, + callback_game: Optional[CallbackGame] = None, + pay: Optional[bool] = None, + **kwargs: Any, + ) -> "InlineKeyboardBuilder": + return cast( + InlineKeyboardBuilder, + self._button( + text=text, + url=url, + callback_data=callback_data, + web_app=web_app, + login_url=login_url, + switch_inline_query=switch_inline_query, + switch_inline_query_current_chat=switch_inline_query_current_chat, + switch_inline_query_chosen_chat=switch_inline_query_chosen_chat, + callback_game=callback_game, + pay=pay, + **kwargs, + ), + ) + + if TYPE_CHECKING: + + def as_markup(self, **kwargs: Any) -> InlineKeyboardMarkup: + """Construct an InlineKeyboardMarkup""" + ... + + def __init__(self, markup: Optional[List[List[InlineKeyboardButton]]] = None) -> None: + super().__init__(button_type=InlineKeyboardButton, markup=markup) + + def copy(self: "InlineKeyboardBuilder") -> "InlineKeyboardBuilder": + """ + Make full copy of current builder with markup + + :return: + """ + return InlineKeyboardBuilder(markup=self.export()) + + @classmethod + def from_markup( + cls: Type["InlineKeyboardBuilder"], markup: InlineKeyboardMarkup + ) -> "InlineKeyboardBuilder": + """ + Create builder from existing markup + + :param markup: + :return: + """ + return cls(markup=markup.inline_keyboard) + + +class ReplyKeyboardBuilder(KeyboardBuilder[KeyboardButton]): + """ + Reply keyboard builder inherits all methods from generic builder + """ + + max_width: int = 10 + min_width: int = 1 + max_buttons: int = 300 + + def button( + self, + *, + text: str, + request_users: Optional[KeyboardButtonRequestUsers] = None, + request_chat: Optional[KeyboardButtonRequestChat] = None, + request_contact: Optional[bool] = None, + request_location: Optional[bool] = None, + request_poll: Optional[KeyboardButtonPollType] = None, + web_app: Optional[WebAppInfo] = None, + **kwargs: Any, + ) -> "ReplyKeyboardBuilder": + return cast( + ReplyKeyboardBuilder, + self._button( + text=text, + request_users=request_users, + request_chat=request_chat, + request_contact=request_contact, + request_location=request_location, + request_poll=request_poll, + web_app=web_app, + **kwargs, + ), + ) + + if TYPE_CHECKING: + + def as_markup(self, **kwargs: Any) -> ReplyKeyboardMarkup: ... + + def __init__(self, markup: Optional[List[List[KeyboardButton]]] = None) -> None: + super().__init__(button_type=KeyboardButton, markup=markup) + + def copy(self: "ReplyKeyboardBuilder") -> "ReplyKeyboardBuilder": + """ + Make full copy of current builder with markup + + :return: + """ + return ReplyKeyboardBuilder(markup=self.export()) + + @classmethod + def from_markup(cls, markup: ReplyKeyboardMarkup) -> "ReplyKeyboardBuilder": + """ + Create builder from existing markup + + :param markup: + :return: + """ + return cls(markup=markup.keyboard) diff --git a/env/Lib/site-packages/aiogram/utils/link.py b/env/Lib/site-packages/aiogram/utils/link.py new file mode 100644 index 0000000..051247f --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/link.py @@ -0,0 +1,74 @@ +from typing import Any, Optional +from urllib.parse import urlencode, urljoin + +BASE_DOCS_URL = "https://docs.aiogram.dev/" +BRANCH = "dev-3.x" + +BASE_PAGE_URL = f"{BASE_DOCS_URL}/en/{BRANCH}/" + + +def _format_url(url: str, *path: str, fragment_: Optional[str] = None, **query: Any) -> str: + url = urljoin(url, "/".join(path), allow_fragments=True) + if query: + url += "?" + urlencode(query) + if fragment_: + url += "#" + fragment_ + return url + + +def docs_url(*path: str, fragment_: Optional[str] = None, **query: Any) -> str: + return _format_url(BASE_PAGE_URL, *path, fragment_=fragment_, **query) + + +def create_tg_link(link: str, **kwargs: Any) -> str: + return _format_url(f"tg://{link}", **kwargs) + + +def create_telegram_link(*path: str, **kwargs: Any) -> str: + return _format_url("https://t.me", *path, **kwargs) + + +def create_channel_bot_link( + username: str, + parameter: Optional[str] = None, + change_info: bool = False, + post_messages: bool = False, + edit_messages: bool = False, + delete_messages: bool = False, + restrict_members: bool = False, + invite_users: bool = False, + pin_messages: bool = False, + promote_members: bool = False, + manage_video_chats: bool = False, + anonymous: bool = False, + manage_chat: bool = False, +) -> str: + params = {} + if parameter is not None: + params["startgroup"] = parameter + permissions = [] + if change_info: + permissions.append("change_info") + if post_messages: + permissions.append("post_messages") + if edit_messages: + permissions.append("edit_messages") + if delete_messages: + permissions.append("delete_messages") + if restrict_members: + permissions.append("restrict_members") + if invite_users: + permissions.append("invite_users") + if pin_messages: + permissions.append("pin_messages") + if promote_members: + permissions.append("promote_members") + if manage_video_chats: + permissions.append("manage_video_chats") + if anonymous: + permissions.append("anonymous") + if manage_chat: + permissions.append("manage_chat") + if permissions: + params["admin"] = "+".join(permissions) + return create_telegram_link(username, **params) diff --git a/env/Lib/site-packages/aiogram/utils/magic_filter.py b/env/Lib/site-packages/aiogram/utils/magic_filter.py new file mode 100644 index 0000000..94c9207 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/magic_filter.py @@ -0,0 +1,22 @@ +from typing import Any, Iterable + +from magic_filter import MagicFilter as _MagicFilter +from magic_filter import MagicT as _MagicT +from magic_filter.operations import BaseOperation + + +class AsFilterResultOperation(BaseOperation): + __slots__ = ("name",) + + def __init__(self, name: str) -> None: + self.name = name + + def resolve(self, value: Any, initial_value: Any) -> Any: + if value is None or (isinstance(value, Iterable) and not value): + return None + return {self.name: value} + + +class MagicFilter(_MagicFilter): + def as_(self: _MagicT, name: str) -> _MagicT: + return self._extend(AsFilterResultOperation(name=name)) diff --git a/env/Lib/site-packages/aiogram/utils/markdown.py b/env/Lib/site-packages/aiogram/utils/markdown.py new file mode 100644 index 0000000..52c6e1d --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/markdown.py @@ -0,0 +1,209 @@ +from typing import Any + +from .text_decorations import html_decoration, markdown_decoration + + +def _join(*content: Any, sep: str = " ") -> str: + return sep.join(map(str, content)) + + +def text(*content: Any, sep: str = " ") -> str: + """ + Join all elements with a separator + + :param content: + :param sep: + :return: + """ + return _join(*content, sep=sep) + + +def bold(*content: Any, sep: str = " ") -> str: + """ + Make bold text (Markdown) + + :param content: + :param sep: + :return: + """ + return markdown_decoration.bold(value=markdown_decoration.quote(_join(*content, sep=sep))) + + +def hbold(*content: Any, sep: str = " ") -> str: + """ + Make bold text (HTML) + + :param content: + :param sep: + :return: + """ + return html_decoration.bold(value=html_decoration.quote(_join(*content, sep=sep))) + + +def italic(*content: Any, sep: str = " ") -> str: + """ + Make italic text (Markdown) + + :param content: + :param sep: + :return: + """ + return markdown_decoration.italic(value=markdown_decoration.quote(_join(*content, sep=sep))) + + +def hitalic(*content: Any, sep: str = " ") -> str: + """ + Make italic text (HTML) + + :param content: + :param sep: + :return: + """ + return html_decoration.italic(value=html_decoration.quote(_join(*content, sep=sep))) + + +def code(*content: Any, sep: str = " ") -> str: + """ + Make mono-width text (Markdown) + + :param content: + :param sep: + :return: + """ + return markdown_decoration.code(value=markdown_decoration.quote(_join(*content, sep=sep))) + + +def hcode(*content: Any, sep: str = " ") -> str: + """ + Make mono-width text (HTML) + + :param content: + :param sep: + :return: + """ + return html_decoration.code(value=html_decoration.quote(_join(*content, sep=sep))) + + +def pre(*content: Any, sep: str = "\n") -> str: + """ + Make mono-width text block (Markdown) + + :param content: + :param sep: + :return: + """ + return markdown_decoration.pre(value=markdown_decoration.quote(_join(*content, sep=sep))) + + +def hpre(*content: Any, sep: str = "\n") -> str: + """ + Make mono-width text block (HTML) + + :param content: + :param sep: + :return: + """ + return html_decoration.pre(value=html_decoration.quote(_join(*content, sep=sep))) + + +def underline(*content: Any, sep: str = " ") -> str: + """ + Make underlined text (Markdown) + + :param content: + :param sep: + :return: + """ + return markdown_decoration.underline(value=markdown_decoration.quote(_join(*content, sep=sep))) + + +def hunderline(*content: Any, sep: str = " ") -> str: + """ + Make underlined text (HTML) + + :param content: + :param sep: + :return: + """ + return html_decoration.underline(value=html_decoration.quote(_join(*content, sep=sep))) + + +def strikethrough(*content: Any, sep: str = " ") -> str: + """ + Make strikethrough text (Markdown) + + :param content: + :param sep: + :return: + """ + return markdown_decoration.strikethrough( + value=markdown_decoration.quote(_join(*content, sep=sep)) + ) + + +def hstrikethrough(*content: Any, sep: str = " ") -> str: + """ + Make strikethrough text (HTML) + + :param content: + :param sep: + :return: + """ + return html_decoration.strikethrough(value=html_decoration.quote(_join(*content, sep=sep))) + + +def link(title: str, url: str) -> str: + """ + Format URL (Markdown) + + :param title: + :param url: + :return: + """ + return markdown_decoration.link(value=markdown_decoration.quote(title), link=url) + + +def hlink(title: str, url: str) -> str: + """ + Format URL (HTML) + + :param title: + :param url: + :return: + """ + return html_decoration.link(value=html_decoration.quote(title), link=url) + + +def blockquote(*content: Any, sep: str = "\n") -> str: + """ + Make blockquote (Markdown) + + :param content: + :param sep: + :return: + """ + return markdown_decoration.blockquote( + value=markdown_decoration.quote(_join(*content, sep=sep)) + ) + + +def hblockquote(*content: Any, sep: str = "\n") -> str: + """ + Make blockquote (HTML) + + :param content: + :param sep: + :return: + """ + return html_decoration.blockquote(value=html_decoration.quote(_join(*content, sep=sep))) + + +def hide_link(url: str) -> str: + """ + Hide URL (HTML only) + Can be used for adding an image to a text message + + :param url: + :return: + """ + return f'' diff --git a/env/Lib/site-packages/aiogram/utils/media_group.py b/env/Lib/site-packages/aiogram/utils/media_group.py new file mode 100644 index 0000000..ff98525 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/media_group.py @@ -0,0 +1,368 @@ +from typing import Any, Dict, List, Literal, Optional, Union, overload + +from aiogram.enums import InputMediaType +from aiogram.types import ( + UNSET_PARSE_MODE, + InputFile, + InputMedia, + InputMediaAudio, + InputMediaDocument, + InputMediaPhoto, + InputMediaVideo, + MessageEntity, +) + +MediaType = Union[ + InputMediaAudio, + InputMediaPhoto, + InputMediaVideo, + InputMediaDocument, +] + +MAX_MEDIA_GROUP_SIZE = 10 + + +class MediaGroupBuilder: + # Animated media is not supported yet in Bot API to send as a media group + + def __init__( + self, + media: Optional[List[MediaType]] = None, + caption: Optional[str] = None, + caption_entities: Optional[List[MessageEntity]] = None, + ) -> None: + """ + Helper class for building media groups. + + :param media: A list of media elements to add to the media group. (optional) + :param caption: Caption for the media group. (optional) + :param caption_entities: List of special entities in the caption, + like usernames, URLs, etc. (optional) + """ + self._media: List[MediaType] = [] + self.caption = caption + self.caption_entities = caption_entities + + self._extend(media or []) + + def _add(self, media: MediaType) -> None: + if not isinstance(media, InputMedia): + raise ValueError("Media must be instance of InputMedia") + + if len(self._media) >= MAX_MEDIA_GROUP_SIZE: + raise ValueError("Media group can't contain more than 10 elements") + + self._media.append(media) + + def _extend(self, media: List[MediaType]) -> None: + for m in media: + self._add(m) + + @overload + def add( + self, + *, + type: Literal[InputMediaType.AUDIO], + media: Union[str, InputFile], + caption: Optional[str] = None, + parse_mode: Optional[str] = UNSET_PARSE_MODE, + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + **kwargs: Any, + ) -> None: + pass + + @overload + def add( + self, + *, + type: Literal[InputMediaType.PHOTO], + media: Union[str, InputFile], + caption: Optional[str] = None, + parse_mode: Optional[str] = UNSET_PARSE_MODE, + caption_entities: Optional[List[MessageEntity]] = None, + has_spoiler: Optional[bool] = None, + **kwargs: Any, + ) -> None: + pass + + @overload + def add( + self, + *, + type: Literal[InputMediaType.VIDEO], + media: Union[str, InputFile], + thumbnail: Optional[Union[InputFile, str]] = None, + caption: Optional[str] = None, + parse_mode: Optional[str] = UNSET_PARSE_MODE, + caption_entities: Optional[List[MessageEntity]] = None, + width: Optional[int] = None, + height: Optional[int] = None, + duration: Optional[int] = None, + supports_streaming: Optional[bool] = None, + has_spoiler: Optional[bool] = None, + **kwargs: Any, + ) -> None: + pass + + @overload + def add( + self, + *, + type: Literal[InputMediaType.DOCUMENT], + media: Union[str, InputFile], + thumbnail: Optional[Union[InputFile, str]] = None, + caption: Optional[str] = None, + parse_mode: Optional[str] = UNSET_PARSE_MODE, + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + **kwargs: Any, + ) -> None: + pass + + def add(self, **kwargs: Any) -> None: + """ + Add a media object to the media group. + + :param kwargs: Keyword arguments for the media object. + The available keyword arguments depend on the media type. + :return: None + """ + type_ = kwargs.pop("type", None) + if type_ == InputMediaType.AUDIO: + self.add_audio(**kwargs) + elif type_ == InputMediaType.PHOTO: + self.add_photo(**kwargs) + elif type_ == InputMediaType.VIDEO: + self.add_video(**kwargs) + elif type_ == InputMediaType.DOCUMENT: + self.add_document(**kwargs) + else: + raise ValueError(f"Unknown media type: {type_!r}") + + def add_audio( + self, + media: Union[str, InputFile], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[str] = UNSET_PARSE_MODE, + caption_entities: Optional[List[MessageEntity]] = None, + duration: Optional[int] = None, + performer: Optional[str] = None, + title: Optional[str] = None, + **kwargs: Any, + ) -> None: + """ + Add an audio file to the media group. + + :param media: File to send. Pass a file_id to send a file that exists on the + Telegram servers (recommended), pass an HTTP URL for Telegram to get a file from + the Internet, or pass 'attach://' to upload a new one using + multipart/form-data under name. + :ref:`More information on Sending Files » ` + :param thumbnail: *Optional*. Thumbnail of the file sent; can be ignored if + thumbnail generation for the file is supported server-side. The thumbnail should + be in JPEG format and less than 200 kB in size. A thumbnail's width and height + should not exceed 320. + :param caption: *Optional*. Caption of the audio to be sent, 0-1024 characters + after entities parsing + :param parse_mode: *Optional*. Mode for parsing entities in the audio caption. + See `formatting options `_ + for more details. + :param caption_entities: *Optional*. List of special entities that appear in the caption, + which can be specified instead of *parse_mode* + :param duration: *Optional*. Duration of the audio in seconds + :param performer: *Optional*. Performer of the audio + :param title: *Optional*. Title of the audio + :return: None + """ + self._add( + InputMediaAudio( + media=media, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + duration=duration, + performer=performer, + title=title, + **kwargs, + ) + ) + + def add_photo( + self, + media: Union[str, InputFile], + caption: Optional[str] = None, + parse_mode: Optional[str] = UNSET_PARSE_MODE, + caption_entities: Optional[List[MessageEntity]] = None, + has_spoiler: Optional[bool] = None, + **kwargs: Any, + ) -> None: + """ + Add a photo to the media group. + + :param media: File to send. Pass a file_id to send a file that exists on the + Telegram servers (recommended), pass an HTTP URL for Telegram to get a file + from the Internet, or pass 'attach://' to upload a new + one using multipart/form-data under name. + :ref:`More information on Sending Files » ` + :param caption: *Optional*. Caption of the photo to be sent, 0-1024 characters + after entities parsing + :param parse_mode: *Optional*. Mode for parsing entities in the photo caption. + See `formatting options `_ + for more details. + :param caption_entities: *Optional*. List of special entities that appear in the caption, + which can be specified instead of *parse_mode* + :param has_spoiler: *Optional*. Pass :code:`True` if the photo needs to be covered + with a spoiler animation + :return: None + """ + self._add( + InputMediaPhoto( + media=media, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + has_spoiler=has_spoiler, + **kwargs, + ) + ) + + def add_video( + self, + media: Union[str, InputFile], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[str] = UNSET_PARSE_MODE, + caption_entities: Optional[List[MessageEntity]] = None, + width: Optional[int] = None, + height: Optional[int] = None, + duration: Optional[int] = None, + supports_streaming: Optional[bool] = None, + has_spoiler: Optional[bool] = None, + **kwargs: Any, + ) -> None: + """ + Add a video to the media group. + + :param media: File to send. Pass a file_id to send a file that exists on the + Telegram servers (recommended), pass an HTTP URL for Telegram to get a file + from the Internet, or pass 'attach://' to upload a new one + using multipart/form-data under name. + :ref:`More information on Sending Files » ` + :param thumbnail: *Optional*. Thumbnail of the file sent; can be ignored if thumbnail + generation for the file is supported server-side. The thumbnail should be in JPEG + format and less than 200 kB in size. A thumbnail's width and height should + not exceed 320. Ignored if the file is not uploaded using multipart/form-data. + Thumbnails can't be reused and can be only uploaded as a new file, so you + can pass 'attach://' if the thumbnail was uploaded using + multipart/form-data under . + :ref:`More information on Sending Files » ` + :param caption: *Optional*. Caption of the video to be sent, + 0-1024 characters after entities parsing + :param parse_mode: *Optional*. Mode for parsing entities in the video caption. + See `formatting options `_ + for more details. + :param caption_entities: *Optional*. List of special entities that appear in the caption, + which can be specified instead of *parse_mode* + :param width: *Optional*. Video width + :param height: *Optional*. Video height + :param duration: *Optional*. Video duration in seconds + :param supports_streaming: *Optional*. Pass :code:`True` if the uploaded video is + suitable for streaming + :param has_spoiler: *Optional*. Pass :code:`True` if the video needs to be covered + with a spoiler animation + :return: None + """ + self._add( + InputMediaVideo( + media=media, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + width=width, + height=height, + duration=duration, + supports_streaming=supports_streaming, + has_spoiler=has_spoiler, + **kwargs, + ) + ) + + def add_document( + self, + media: Union[str, InputFile], + thumbnail: Optional[InputFile] = None, + caption: Optional[str] = None, + parse_mode: Optional[str] = UNSET_PARSE_MODE, + caption_entities: Optional[List[MessageEntity]] = None, + disable_content_type_detection: Optional[bool] = None, + **kwargs: Any, + ) -> None: + """ + Add a document to the media group. + + :param media: File to send. Pass a file_id to send a file that exists on the + Telegram servers (recommended), pass an HTTP URL for Telegram to get a file + from the Internet, or pass 'attach://' to upload a new one using + multipart/form-data under name. + :ref:`More information on Sending Files » ` + :param thumbnail: *Optional*. Thumbnail of the file sent; can be ignored + if thumbnail generation for the file is supported server-side. + The thumbnail should be in JPEG format and less than 200 kB in size. + A thumbnail's width and height should not exceed 320. + Ignored if the file is not uploaded using multipart/form-data. + Thumbnails can't be reused and can be only uploaded as a new file, + so you can pass 'attach://' if the thumbnail was uploaded + using multipart/form-data under . + :ref:`More information on Sending Files » ` + :param caption: *Optional*. Caption of the document to be sent, + 0-1024 characters after entities parsing + :param parse_mode: *Optional*. Mode for parsing entities in the document caption. + See `formatting options `_ + for more details. + :param caption_entities: *Optional*. List of special entities that appear + in the caption, which can be specified instead of *parse_mode* + :param disable_content_type_detection: *Optional*. Disables automatic server-side + content type detection for files uploaded using multipart/form-data. + Always :code:`True`, if the document is sent as part of an album. + :return: None + + """ + self._add( + InputMediaDocument( + media=media, + thumbnail=thumbnail, + caption=caption, + parse_mode=parse_mode, + caption_entities=caption_entities, + disable_content_type_detection=disable_content_type_detection, + **kwargs, + ) + ) + + def build(self) -> List[MediaType]: + """ + Builds a list of media objects for a media group. + + Adds the caption to the first media object if it is present. + + :return: List of media objects. + """ + update_first_media: Dict[str, Any] = {"caption": self.caption} + if self.caption_entities is not None: + update_first_media["caption_entities"] = self.caption_entities + update_first_media["parse_mode"] = None + + return [ + ( + media.model_copy(update=update_first_media) + if index == 0 and self.caption is not None + else media + ) + for index, media in enumerate(self._media) + ] diff --git a/env/Lib/site-packages/aiogram/utils/mixins.py b/env/Lib/site-packages/aiogram/utils/mixins.py new file mode 100644 index 0000000..86b3ed8 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/mixins.py @@ -0,0 +1,95 @@ +from __future__ import annotations + +import contextvars +from typing import TYPE_CHECKING, Any, Dict, Generic, Optional, TypeVar, cast, overload + +if TYPE_CHECKING: + from typing_extensions import Literal + +__all__ = ("ContextInstanceMixin", "DataMixin") + + +class DataMixin: + @property + def data(self) -> Dict[str, Any]: + data: Optional[Dict[str, Any]] = getattr(self, "_data", None) + if data is None: + data = {} + setattr(self, "_data", data) + return data + + def __getitem__(self, key: str) -> Any: + return self.data[key] + + def __setitem__(self, key: str, value: Any) -> None: + self.data[key] = value + + def __delitem__(self, key: str) -> None: + del self.data[key] + + def __contains__(self, key: str) -> bool: + return key in self.data + + def get(self, key: str, default: Optional[Any] = None) -> Optional[Any]: + return self.data.get(key, default) + + +ContextInstance = TypeVar("ContextInstance") + + +class ContextInstanceMixin(Generic[ContextInstance]): + __context_instance: contextvars.ContextVar[ContextInstance] + + def __init_subclass__(cls, **kwargs: Any) -> None: + super().__init_subclass__() + cls.__context_instance = contextvars.ContextVar(f"instance_{cls.__name__}") + + @overload # noqa: F811 + @classmethod + def get_current(cls) -> Optional[ContextInstance]: # pragma: no cover # noqa: F811 + ... + + @overload # noqa: F811 + @classmethod + def get_current( # noqa: F811 + cls, no_error: Literal[True] + ) -> Optional[ContextInstance]: # pragma: no cover # noqa: F811 + ... + + @overload # noqa: F811 + @classmethod + def get_current( # noqa: F811 + cls, no_error: Literal[False] + ) -> ContextInstance: # pragma: no cover # noqa: F811 + ... + + @classmethod # noqa: F811 + def get_current( # noqa: F811 + cls, no_error: bool = True + ) -> Optional[ContextInstance]: # pragma: no cover # noqa: F811 + # on mypy 0.770 I catch that contextvars.ContextVar always contextvars.ContextVar[Any] + cls.__context_instance = cast( + contextvars.ContextVar[ContextInstance], cls.__context_instance + ) + + try: + current: Optional[ContextInstance] = cls.__context_instance.get() + except LookupError: + if no_error: + current = None + else: + raise + + return current + + @classmethod + def set_current(cls, value: ContextInstance) -> contextvars.Token[ContextInstance]: + if not isinstance(value, cls): + raise TypeError( + f"Value should be instance of {cls.__name__!r} not {type(value).__name__!r}" + ) + return cls.__context_instance.set(value) + + @classmethod + def reset_current(cls, token: contextvars.Token[ContextInstance]) -> None: + cls.__context_instance.reset(token) diff --git a/env/Lib/site-packages/aiogram/utils/mypy_hacks.py b/env/Lib/site-packages/aiogram/utils/mypy_hacks.py new file mode 100644 index 0000000..ea47a9d --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/mypy_hacks.py @@ -0,0 +1,16 @@ +import functools +from typing import Callable, TypeVar + +T = TypeVar("T") + + +def lru_cache(maxsize: int = 128, typed: bool = False) -> Callable[[T], T]: + """ + fix: lru_cache annotation doesn't work with a property + this hack is only needed for the property, so type annotations are as they are + """ + + def wrapper(func: T) -> T: + return functools.lru_cache(maxsize, typed)(func) # type: ignore + + return wrapper diff --git a/env/Lib/site-packages/aiogram/utils/payload.py b/env/Lib/site-packages/aiogram/utils/payload.py new file mode 100644 index 0000000..dbdba65 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/payload.py @@ -0,0 +1,109 @@ +""" +Payload preparing + +We have added some utils to make work with payload easier. + +Basic encode example: + + .. code-block:: python + + from aiogram.utils.payload import encode_payload + + encoded = encode_payload("foo") + + # result: "Zm9v" + +Basic decode it back example: + + .. code-block:: python + + from aiogram.utils.payload import decode_payload + + encoded = "Zm9v" + decoded = decode_payload(encoded) + # result: "foo" + +Encoding and decoding with your own methods: + + 1. Create your own cryptor + + .. code-block:: python + + from Cryptodome.Cipher import AES + from Cryptodome.Util.Padding import pad, unpad + + class Cryptor: + def __init__(self, key: str): + self.key = key.encode("utf-8") + self.mode = AES.MODE_ECB # never use ECB in strong systems obviously + self.size = 32 + + @property + def cipher(self): + return AES.new(self.key, self.mode) + + def encrypt(self, data: bytes) -> bytes: + return self.cipher.encrypt(pad(data, self.size)) + + def decrypt(self, data: bytes) -> bytes: + decrypted_data = self.cipher.decrypt(data) + return unpad(decrypted_data, self.size) + + 2. Pass cryptor callable methods to aiogram payload tools + + .. code-block:: python + + cryptor = Cryptor("abcdefghijklmnop") + encoded = encode_payload("foo", encoder=cryptor.encrypt) + decoded = decode_payload(encoded_payload, decoder=cryptor.decrypt) + + # result: decoded == "foo" + +""" + +from base64 import urlsafe_b64decode, urlsafe_b64encode +from typing import Callable, Optional + + +def encode_payload( + payload: str, + encoder: Optional[Callable[[bytes], bytes]] = None, +) -> str: + """Encode payload with encoder. + + Result also will be encoded with URL-safe base64url. + """ + if not isinstance(payload, str): + payload = str(payload) + + payload_bytes = payload.encode("utf-8") + if encoder is not None: + payload_bytes = encoder(payload_bytes) + + return _encode_b64(payload_bytes) + + +def decode_payload( + payload: str, + decoder: Optional[Callable[[bytes], bytes]] = None, +) -> str: + """Decode URL-safe base64url payload with decoder.""" + original_payload = _decode_b64(payload) + + if decoder is None: + return original_payload.decode() + + return decoder(original_payload).decode() + + +def _encode_b64(payload: bytes) -> str: + """Encode with URL-safe base64url.""" + bytes_payload: bytes = urlsafe_b64encode(payload) + str_payload = bytes_payload.decode() + return str_payload.replace("=", "") + + +def _decode_b64(payload: str) -> bytes: + """Decode with URL-safe base64url.""" + payload += "=" * (4 - len(payload) % 4) + return urlsafe_b64decode(payload.encode()) diff --git a/env/Lib/site-packages/aiogram/utils/serialization.py b/env/Lib/site-packages/aiogram/utils/serialization.py new file mode 100644 index 0000000..cc6ef8a --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/serialization.py @@ -0,0 +1,89 @@ +from dataclasses import dataclass +from typing import Any, Dict, Optional + +from pydantic import BaseModel + +from aiogram import Bot +from aiogram.client.default import DefaultBotProperties +from aiogram.methods import TelegramMethod +from aiogram.types import InputFile + + +def _get_fake_bot(default: Optional[DefaultBotProperties] = None) -> Bot: + if default is None: + default = DefaultBotProperties() + return Bot(token="42:Fake", default=default) + + +@dataclass +class DeserializedTelegramObject: + """ + Represents a dumped Telegram object. + + :param data: The dumped data of the Telegram object. + :type data: Any + :param files: The dictionary containing the file names as keys + and the corresponding `InputFile` objects as values. + :type files: Dict[str, InputFile] + """ + + data: Any + files: Dict[str, InputFile] + + +def deserialize_telegram_object( + obj: Any, + default: Optional[DefaultBotProperties] = None, + include_api_method_name: bool = True, +) -> DeserializedTelegramObject: + """ + Deserialize Telegram Object to JSON compatible Python object. + + :param obj: The object to be deserialized. + :param default: Default bot properties + should be passed only if you want to use custom defaults. + :param include_api_method_name: Whether to include the API method name in the result. + :return: The deserialized Telegram object. + """ + extends = {} + if include_api_method_name and isinstance(obj, TelegramMethod): + extends["method"] = obj.__api_method__ + + if isinstance(obj, BaseModel): + obj = obj.model_dump(mode="python", warnings=False) + + # Fake bot is needed to exclude global defaults from the object. + fake_bot = _get_fake_bot(default=default) + + files: Dict[str, InputFile] = {} + prepared = fake_bot.session.prepare_value( + obj, + bot=fake_bot, + files=files, + _dumps_json=False, + ) + + if isinstance(prepared, dict): + prepared.update(extends) + return DeserializedTelegramObject(data=prepared, files=files) + + +def deserialize_telegram_object_to_python( + obj: Any, + default: Optional[DefaultBotProperties] = None, + include_api_method_name: bool = True, +) -> Any: + """ + Deserialize telegram object to JSON compatible Python object excluding files. + + :param obj: The telegram object to be deserialized. + :param default: Default bot properties + should be passed only if you want to use custom defaults. + :param include_api_method_name: Whether to include the API method name in the result. + :return: The deserialized telegram object. + """ + return deserialize_telegram_object( + obj, + default=default, + include_api_method_name=include_api_method_name, + ).data diff --git a/env/Lib/site-packages/aiogram/utils/text_decorations.py b/env/Lib/site-packages/aiogram/utils/text_decorations.py new file mode 100644 index 0000000..440fffa --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/text_decorations.py @@ -0,0 +1,274 @@ +from __future__ import annotations + +import html +import re +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Generator, List, Optional, Pattern, cast + +from aiogram.enums import MessageEntityType + +if TYPE_CHECKING: + from aiogram.types import MessageEntity + +__all__ = ( + "HtmlDecoration", + "MarkdownDecoration", + "TextDecoration", + "html_decoration", + "markdown_decoration", + "add_surrogates", + "remove_surrogates", +) + + +def add_surrogates(text: str) -> bytes: + return text.encode("utf-16-le") + + +def remove_surrogates(text: bytes) -> str: + return text.decode("utf-16-le") + + +class TextDecoration(ABC): + def apply_entity(self, entity: MessageEntity, text: str) -> str: + """ + Apply single entity to text + + :param entity: + :param text: + :return: + """ + if entity.type in { + MessageEntityType.BOT_COMMAND, + MessageEntityType.URL, + MessageEntityType.MENTION, + MessageEntityType.PHONE_NUMBER, + MessageEntityType.HASHTAG, + MessageEntityType.CASHTAG, + MessageEntityType.EMAIL, + }: + # These entities should not be changed + return text + if entity.type in { + MessageEntityType.BOLD, + MessageEntityType.ITALIC, + MessageEntityType.CODE, + MessageEntityType.UNDERLINE, + MessageEntityType.STRIKETHROUGH, + MessageEntityType.SPOILER, + MessageEntityType.BLOCKQUOTE, + MessageEntityType.EXPANDABLE_BLOCKQUOTE, + }: + return cast(str, getattr(self, entity.type)(value=text)) + if entity.type == MessageEntityType.PRE: + return ( + self.pre_language(value=text, language=entity.language) + if entity.language + else self.pre(value=text) + ) + if entity.type == MessageEntityType.TEXT_MENTION: + from aiogram.types import User + + user = cast(User, entity.user) + return self.link(value=text, link=f"tg://user?id={user.id}") + if entity.type == MessageEntityType.TEXT_LINK: + return self.link(value=text, link=cast(str, entity.url)) + if entity.type == MessageEntityType.CUSTOM_EMOJI: + return self.custom_emoji(value=text, custom_emoji_id=cast(str, entity.custom_emoji_id)) + + # This case is not possible because of `if` above, but if any new entity is added to + # API it will be here too + return self.quote(text) + + def unparse(self, text: str, entities: Optional[List[MessageEntity]] = None) -> str: + """ + Unparse message entities + + :param text: raw text + :param entities: Array of MessageEntities + :return: + """ + return "".join( + self._unparse_entities( + add_surrogates(text), + sorted(entities, key=lambda item: item.offset) if entities else [], + ) + ) + + def _unparse_entities( + self, + text: bytes, + entities: List[MessageEntity], + offset: Optional[int] = None, + length: Optional[int] = None, + ) -> Generator[str, None, None]: + if offset is None: + offset = 0 + length = length or len(text) + + for index, entity in enumerate(entities): + if entity.offset * 2 < offset: + continue + if entity.offset * 2 > offset: + yield self.quote(remove_surrogates(text[offset : entity.offset * 2])) + start = entity.offset * 2 + offset = entity.offset * 2 + entity.length * 2 + + sub_entities = list( + filter(lambda e: e.offset * 2 < (offset or 0), entities[index + 1 :]) + ) + yield self.apply_entity( + entity, + "".join(self._unparse_entities(text, sub_entities, offset=start, length=offset)), + ) + + if offset < length: + yield self.quote(remove_surrogates(text[offset:length])) + + @abstractmethod + def link(self, value: str, link: str) -> str: + pass + + @abstractmethod + def bold(self, value: str) -> str: + pass + + @abstractmethod + def italic(self, value: str) -> str: + pass + + @abstractmethod + def code(self, value: str) -> str: + pass + + @abstractmethod + def pre(self, value: str) -> str: + pass + + @abstractmethod + def pre_language(self, value: str, language: str) -> str: + pass + + @abstractmethod + def underline(self, value: str) -> str: + pass + + @abstractmethod + def strikethrough(self, value: str) -> str: + pass + + @abstractmethod + def spoiler(self, value: str) -> str: + pass + + @abstractmethod + def quote(self, value: str) -> str: + pass + + @abstractmethod + def custom_emoji(self, value: str, custom_emoji_id: str) -> str: + pass + + @abstractmethod + def blockquote(self, value: str) -> str: + pass + + @abstractmethod + def expandable_blockquote(self, value: str) -> str: + pass + + +class HtmlDecoration(TextDecoration): + BOLD_TAG = "b" + ITALIC_TAG = "i" + UNDERLINE_TAG = "u" + STRIKETHROUGH_TAG = "s" + SPOILER_TAG = "tg-spoiler" + EMOJI_TAG = "tg-emoji" + BLOCKQUOTE_TAG = "blockquote" + + def link(self, value: str, link: str) -> str: + return f'{value}' + + def bold(self, value: str) -> str: + return f"<{self.BOLD_TAG}>{value}" + + def italic(self, value: str) -> str: + return f"<{self.ITALIC_TAG}>{value}" + + def code(self, value: str) -> str: + return f"{value}" + + def pre(self, value: str) -> str: + return f"
{value}
" + + def pre_language(self, value: str, language: str) -> str: + return f'
{value}
' + + def underline(self, value: str) -> str: + return f"<{self.UNDERLINE_TAG}>{value}" + + def strikethrough(self, value: str) -> str: + return f"<{self.STRIKETHROUGH_TAG}>{value}" + + def spoiler(self, value: str) -> str: + return f"<{self.SPOILER_TAG}>{value}" + + def quote(self, value: str) -> str: + return html.escape(value, quote=False) + + def custom_emoji(self, value: str, custom_emoji_id: str) -> str: + return f'<{self.EMOJI_TAG} emoji-id="{custom_emoji_id}">{value}' + + def blockquote(self, value: str) -> str: + return f"<{self.BLOCKQUOTE_TAG}>{value}" + + def expandable_blockquote(self, value: str) -> str: + return f"<{self.BLOCKQUOTE_TAG} expandable>{value}" + + +class MarkdownDecoration(TextDecoration): + MARKDOWN_QUOTE_PATTERN: Pattern[str] = re.compile(r"([_*\[\]()~`>#+\-=|{}.!\\])") + + def link(self, value: str, link: str) -> str: + return f"[{value}]({link})" + + def bold(self, value: str) -> str: + return f"*{value}*" + + def italic(self, value: str) -> str: + return f"_\r{value}_\r" + + def code(self, value: str) -> str: + return f"`{value}`" + + def pre(self, value: str) -> str: + return f"```\n{value}\n```" + + def pre_language(self, value: str, language: str) -> str: + return f"```{language}\n{value}\n```" + + def underline(self, value: str) -> str: + return f"__\r{value}__\r" + + def strikethrough(self, value: str) -> str: + return f"~{value}~" + + def spoiler(self, value: str) -> str: + return f"||{value}||" + + def quote(self, value: str) -> str: + return re.sub(pattern=self.MARKDOWN_QUOTE_PATTERN, repl=r"\\\1", string=value) + + def custom_emoji(self, value: str, custom_emoji_id: str) -> str: + return f'!{self.link(value=value, link=f"tg://emoji?id={custom_emoji_id}")}' + + def blockquote(self, value: str) -> str: + return "\n".join(f">{line}" for line in value.splitlines()) + + def expandable_blockquote(self, value: str) -> str: + return "\n".join(f">{line}" for line in value.splitlines()) + "||" + + +html_decoration = HtmlDecoration() +markdown_decoration = MarkdownDecoration() diff --git a/env/Lib/site-packages/aiogram/utils/token.py b/env/Lib/site-packages/aiogram/utils/token.py new file mode 100644 index 0000000..c073846 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/token.py @@ -0,0 +1,42 @@ +from functools import lru_cache + + +class TokenValidationError(Exception): + pass + + +@lru_cache() +def validate_token(token: str) -> bool: + """ + Validate Telegram token + + :param token: + :return: + """ + if not isinstance(token, str): + raise TokenValidationError( + f"Token is invalid! It must be 'str' type instead of {type(token)} type." + ) + + if any(x.isspace() for x in token): + message = "Token is invalid! It can't contains spaces." + raise TokenValidationError(message) + + left, sep, right = token.partition(":") + if (not sep) or (not left.isdigit()) or (not right): + raise TokenValidationError("Token is invalid!") + + return True + + +@lru_cache() +def extract_bot_id(token: str) -> int: + """ + Extract bot ID from Telegram token + + :param token: + :return: + """ + validate_token(token) + raw_bot_id, *_ = token.split(":") + return int(raw_bot_id) diff --git a/env/Lib/site-packages/aiogram/utils/warnings.py b/env/Lib/site-packages/aiogram/utils/warnings.py new file mode 100644 index 0000000..3099fc3 --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/warnings.py @@ -0,0 +1,6 @@ +class AiogramWarning(Warning): + pass + + +class Recommendation(AiogramWarning): + pass diff --git a/env/Lib/site-packages/aiogram/utils/web_app.py b/env/Lib/site-packages/aiogram/utils/web_app.py new file mode 100644 index 0000000..192776f --- /dev/null +++ b/env/Lib/site-packages/aiogram/utils/web_app.py @@ -0,0 +1,183 @@ +import hashlib +import hmac +import json +from datetime import datetime +from operator import itemgetter +from typing import Any, Callable, Optional +from urllib.parse import parse_qsl + +from aiogram.types import TelegramObject + + +class WebAppChat(TelegramObject): + """ + This object represents a chat. + + Source: https://core.telegram.org/bots/webapps#webappchat + """ + + id: int + """Unique identifier for this chat. This number may have more than 32 significant bits + and some programming languages may have difficulty/silent defects in interpreting it. + But it has at most 52 significant bits, so a signed 64-bit integer or double-precision + float type are safe for storing this identifier.""" + type: str + """Type of chat, can be either “group”, “supergroup” or “channel”""" + title: str + """Title of the chat""" + username: Optional[str] = None + """Username of the chat""" + photo_url: Optional[str] = None + """URL of the chat’s photo. The photo can be in .jpeg or .svg formats. + Only returned for Web Apps launched from the attachment menu.""" + + +class WebAppUser(TelegramObject): + """ + This object contains the data of the Web App user. + + Source: https://core.telegram.org/bots/webapps#webappuser + """ + + id: int + """A unique identifier for the user or bot. This number may have more than 32 significant bits + and some programming languages may have difficulty/silent defects in interpreting it. + It has at most 52 significant bits, so a 64-bit integer or a double-precision float type + is safe for storing this identifier.""" + is_bot: Optional[bool] = None + """True, if this user is a bot. Returns in the receiver field only.""" + first_name: str + """First name of the user or bot.""" + last_name: Optional[str] = None + """Last name of the user or bot.""" + username: Optional[str] = None + """Username of the user or bot.""" + language_code: Optional[str] = None + """IETF language tag of the user's language. Returns in user field only.""" + is_premium: Optional[bool] = None + """True, if this user is a Telegram Premium user.""" + added_to_attachment_menu: Optional[bool] = None + """True, if this user added the bot to the attachment menu.""" + allows_write_to_pm: Optional[bool] = None + """True, if this user allowed the bot to message them.""" + photo_url: Optional[str] = None + """URL of the user’s profile photo. The photo can be in .jpeg or .svg formats. + Only returned for Web Apps launched from the attachment menu.""" + + +class WebAppInitData(TelegramObject): + """ + This object contains data that is transferred to the Web App when it is opened. + It is empty if the Web App was launched from a keyboard button. + + Source: https://core.telegram.org/bots/webapps#webappinitdata + """ + + query_id: Optional[str] = None + """A unique identifier for the Web App session, required for sending messages + via the answerWebAppQuery method.""" + user: Optional[WebAppUser] = None + """An object containing data about the current user.""" + receiver: Optional[WebAppUser] = None + """An object containing data about the chat partner of the current user in the chat where + the bot was launched via the attachment menu. + Returned only for Web Apps launched via the attachment menu.""" + chat: Optional[WebAppChat] = None + """An object containing data about the chat where the bot was launched via the attachment menu. + Returned for supergroups, channels, and group chats – only for Web Apps launched via the + attachment menu.""" + chat_type: Optional[str] = None + """Type of the chat from which the Web App was opened. + Can be either “sender” for a private chat with the user opening the link, + “private”, “group”, “supergroup”, or “channel”. + Returned only for Web Apps launched from direct links.""" + chat_instance: Optional[str] = None + """Global identifier, uniquely corresponding to the chat from which the Web App was opened. + Returned only for Web Apps launched from a direct link.""" + start_param: Optional[str] = None + """The value of the startattach parameter, passed via link. + Only returned for Web Apps when launched from the attachment menu via link. + The value of the start_param parameter will also be passed in the GET-parameter + tgWebAppStartParam, so the Web App can load the correct interface right away.""" + can_send_after: Optional[int] = None + """Time in seconds, after which a message can be sent via the answerWebAppQuery method.""" + auth_date: datetime + """Unix time when the form was opened.""" + hash: str + """A hash of all passed parameters, which the bot server can use to check their validity.""" + + +def check_webapp_signature(token: str, init_data: str) -> bool: + """ + Check incoming WebApp init data signature + + Source: https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app + + :param token: bot Token + :param init_data: data from frontend to be validated + :return: + """ + try: + parsed_data = dict(parse_qsl(init_data, strict_parsing=True)) + except ValueError: # pragma: no cover + # Init data is not a valid query string + return False + if "hash" not in parsed_data: + # Hash is not present in init data + return False + hash_ = parsed_data.pop("hash") + + data_check_string = "\n".join( + f"{k}={v}" for k, v in sorted(parsed_data.items(), key=itemgetter(0)) + ) + secret_key = hmac.new(key=b"WebAppData", msg=token.encode(), digestmod=hashlib.sha256) + calculated_hash = hmac.new( + key=secret_key.digest(), msg=data_check_string.encode(), digestmod=hashlib.sha256 + ).hexdigest() + return calculated_hash == hash_ + + +def parse_webapp_init_data( + init_data: str, + *, + loads: Callable[..., Any] = json.loads, +) -> WebAppInitData: + """ + Parse WebApp init data and return it as WebAppInitData object + + This method doesn't make any security check, so you shall not trust to this data, + use :code:`safe_parse_webapp_init_data` instead. + + :param init_data: data from frontend to be parsed + :param loads: + :return: + """ + result = {} + for key, value in parse_qsl(init_data): + if (value.startswith("[") and value.endswith("]")) or ( + value.startswith("{") and value.endswith("}") + ): + value = loads(value) + result[key] = value + return WebAppInitData(**result) + + +def safe_parse_webapp_init_data( + token: str, + init_data: str, + *, + loads: Callable[..., Any] = json.loads, +) -> WebAppInitData: + """ + Validate raw WebApp init data and return it as WebAppInitData object + + Raise :obj:`ValueError` when data is invalid + + :param token: bot token + :param init_data: data from frontend to be parsed and validated + :param loads: + :return: + """ + if check_webapp_signature(token, init_data): + return parse_webapp_init_data(init_data, loads=loads) + raise ValueError("Invalid init data signature") diff --git a/env/Lib/site-packages/aiogram/webhook/__init__.py b/env/Lib/site-packages/aiogram/webhook/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiogram/webhook/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiogram/webhook/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..dccb9ce Binary files /dev/null and b/env/Lib/site-packages/aiogram/webhook/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/webhook/__pycache__/aiohttp_server.cpython-311.pyc b/env/Lib/site-packages/aiogram/webhook/__pycache__/aiohttp_server.cpython-311.pyc new file mode 100644 index 0000000..64bab52 Binary files /dev/null and b/env/Lib/site-packages/aiogram/webhook/__pycache__/aiohttp_server.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/webhook/__pycache__/security.cpython-311.pyc b/env/Lib/site-packages/aiogram/webhook/__pycache__/security.cpython-311.pyc new file mode 100644 index 0000000..80137c4 Binary files /dev/null and b/env/Lib/site-packages/aiogram/webhook/__pycache__/security.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiogram/webhook/aiohttp_server.py b/env/Lib/site-packages/aiogram/webhook/aiohttp_server.py new file mode 100644 index 0000000..7caa0e1 --- /dev/null +++ b/env/Lib/site-packages/aiogram/webhook/aiohttp_server.py @@ -0,0 +1,295 @@ +import asyncio +import secrets +from abc import ABC, abstractmethod +from asyncio import Transport +from typing import Any, Awaitable, Callable, Dict, Optional, Set, Tuple, cast + +from aiohttp import MultipartWriter, web +from aiohttp.abc import Application +from aiohttp.typedefs import Handler +from aiohttp.web_middlewares import middleware + +from aiogram import Bot, Dispatcher, loggers +from aiogram.methods import TelegramMethod +from aiogram.methods.base import TelegramType +from aiogram.types import InputFile +from aiogram.webhook.security import IPFilter + + +def setup_application(app: Application, dispatcher: Dispatcher, /, **kwargs: Any) -> None: + """ + This function helps to configure a startup-shutdown process + + :param app: aiohttp application + :param dispatcher: aiogram dispatcher + :param kwargs: additional data + :return: + """ + workflow_data = { + "app": app, + "dispatcher": dispatcher, + **dispatcher.workflow_data, + **kwargs, + } + + async def on_startup(*a: Any, **kw: Any) -> None: # pragma: no cover + await dispatcher.emit_startup(**workflow_data) + + async def on_shutdown(*a: Any, **kw: Any) -> None: # pragma: no cover + await dispatcher.emit_shutdown(**workflow_data) + + app.on_startup.append(on_startup) + app.on_shutdown.append(on_shutdown) + + +def check_ip(ip_filter: IPFilter, request: web.Request) -> Tuple[str, bool]: + # Try to resolve client IP over reverse proxy + if forwarded_for := request.headers.get("X-Forwarded-For", ""): + # Get the left-most ip when there is multiple ips + # (request got through multiple proxy/load balancers) + # https://github.com/aiogram/aiogram/issues/672 + forwarded_for, *_ = forwarded_for.split(",", maxsplit=1) + return forwarded_for, forwarded_for in ip_filter + + # When reverse proxy is not configured IP address can be resolved from incoming connection + if peer_name := cast(Transport, request.transport).get_extra_info("peername"): + host, _ = peer_name + return host, host in ip_filter + + # Potentially impossible case + return "", False # pragma: no cover + + +def ip_filter_middleware( + ip_filter: IPFilter, +) -> Callable[[web.Request, Handler], Awaitable[Any]]: + """ + + :param ip_filter: + :return: + """ + + @middleware + async def _ip_filter_middleware(request: web.Request, handler: Handler) -> Any: + ip_address, accept = check_ip(ip_filter=ip_filter, request=request) + if not accept: + loggers.webhook.warning("Blocking request from an unauthorized IP: %s", ip_address) + raise web.HTTPUnauthorized() + return await handler(request) + + return _ip_filter_middleware + + +class BaseRequestHandler(ABC): + def __init__( + self, + dispatcher: Dispatcher, + handle_in_background: bool = False, + **data: Any, + ) -> None: + """ + Base handler that helps to handle incoming request from aiohttp + and propagate it to the Dispatcher + + :param dispatcher: instance of :class:`aiogram.dispatcher.dispatcher.Dispatcher` + :param handle_in_background: immediately responds to the Telegram instead of + a waiting end of a handler process + """ + self.dispatcher = dispatcher + self.handle_in_background = handle_in_background + self.data = data + self._background_feed_update_tasks: Set[asyncio.Task[Any]] = set() + + def register(self, app: Application, /, path: str, **kwargs: Any) -> None: + """ + Register route and shutdown callback + + :param app: instance of aiohttp Application + :param path: route path + :param kwargs: + """ + app.on_shutdown.append(self._handle_close) + app.router.add_route("POST", path, self.handle, **kwargs) + + async def _handle_close(self, app: Application) -> None: + await self.close() + + @abstractmethod + async def close(self) -> None: + pass + + @abstractmethod + async def resolve_bot(self, request: web.Request) -> Bot: + """ + This method should be implemented in subclasses of this class. + + Resolve Bot instance from request. + + :param request: + :return: Bot instance + """ + pass + + @abstractmethod + def verify_secret(self, telegram_secret_token: str, bot: Bot) -> bool: + pass + + async def _background_feed_update(self, bot: Bot, update: Dict[str, Any]) -> None: + result = await self.dispatcher.feed_raw_update(bot=bot, update=update, **self.data) + if isinstance(result, TelegramMethod): + await self.dispatcher.silent_call_request(bot=bot, result=result) + + async def _handle_request_background(self, bot: Bot, request: web.Request) -> web.Response: + feed_update_task = asyncio.create_task( + self._background_feed_update( + bot=bot, update=await request.json(loads=bot.session.json_loads) + ) + ) + self._background_feed_update_tasks.add(feed_update_task) + feed_update_task.add_done_callback(self._background_feed_update_tasks.discard) + return web.json_response({}, dumps=bot.session.json_dumps) + + def _build_response_writer( + self, bot: Bot, result: Optional[TelegramMethod[TelegramType]] + ) -> MultipartWriter: + writer = MultipartWriter( + "form-data", + boundary=f"webhookBoundary{secrets.token_urlsafe(16)}", + ) + if not result: + return writer + + payload = writer.append(result.__api_method__) + payload.set_content_disposition("form-data", name="method") + + files: Dict[str, InputFile] = {} + for key, value in result.model_dump(warnings=False).items(): + value = bot.session.prepare_value(value, bot=bot, files=files) + if not value: + continue + payload = writer.append(value) + payload.set_content_disposition("form-data", name=key) + + for key, value in files.items(): + payload = writer.append(value.read(bot)) + payload.set_content_disposition( + "form-data", + name=key, + filename=value.filename or key, + ) + + return writer + + async def _handle_request(self, bot: Bot, request: web.Request) -> web.Response: + result: Optional[TelegramMethod[Any]] = await self.dispatcher.feed_webhook_update( + bot, + await request.json(loads=bot.session.json_loads), + **self.data, + ) + return web.Response(body=self._build_response_writer(bot=bot, result=result)) + + async def handle(self, request: web.Request) -> web.Response: + bot = await self.resolve_bot(request) + if not self.verify_secret(request.headers.get("X-Telegram-Bot-Api-Secret-Token", ""), bot): + return web.Response(body="Unauthorized", status=401) + if self.handle_in_background: + return await self._handle_request_background(bot=bot, request=request) + return await self._handle_request(bot=bot, request=request) + + __call__ = handle + + +class SimpleRequestHandler(BaseRequestHandler): + def __init__( + self, + dispatcher: Dispatcher, + bot: Bot, + handle_in_background: bool = True, + secret_token: Optional[str] = None, + **data: Any, + ) -> None: + """ + Handler for single Bot instance + + :param dispatcher: instance of :class:`aiogram.dispatcher.dispatcher.Dispatcher` + :param handle_in_background: immediately responds to the Telegram instead of + a waiting end of handler process + :param bot: instance of :class:`aiogram.client.bot.Bot` + """ + super().__init__(dispatcher=dispatcher, handle_in_background=handle_in_background, **data) + self.bot = bot + self.secret_token = secret_token + + def verify_secret(self, telegram_secret_token: str, bot: Bot) -> bool: + if self.secret_token: + return secrets.compare_digest(telegram_secret_token, self.secret_token) + return True + + async def close(self) -> None: + """ + Close bot session + """ + await self.bot.session.close() + + async def resolve_bot(self, request: web.Request) -> Bot: + return self.bot + + +class TokenBasedRequestHandler(BaseRequestHandler): + def __init__( + self, + dispatcher: Dispatcher, + handle_in_background: bool = True, + bot_settings: Optional[Dict[str, Any]] = None, + **data: Any, + ) -> None: + """ + Handler that supports multiple bots the context will be resolved + from path variable 'bot_token' + + .. note:: + + This handler is not recommended in due to token is available in URL + and can be logged by reverse proxy server or other middleware. + + :param dispatcher: instance of :class:`aiogram.dispatcher.dispatcher.Dispatcher` + :param handle_in_background: immediately responds to the Telegram instead of + a waiting end of handler process + :param bot_settings: kwargs that will be passed to new Bot instance + """ + super().__init__(dispatcher=dispatcher, handle_in_background=handle_in_background, **data) + if bot_settings is None: + bot_settings = {} + self.bot_settings = bot_settings + self.bots: Dict[str, Bot] = {} + + def verify_secret(self, telegram_secret_token: str, bot: Bot) -> bool: + return True + + async def close(self) -> None: + for bot in self.bots.values(): + await bot.session.close() + + def register(self, app: Application, /, path: str, **kwargs: Any) -> None: + """ + Validate path, register route and shutdown callback + + :param app: instance of aiohttp Application + :param path: route path + :param kwargs: + """ + if "{bot_token}" not in path: + raise ValueError("Path should contains '{bot_token}' substring") + super().register(app, path=path, **kwargs) + + async def resolve_bot(self, request: web.Request) -> Bot: + """ + Get bot token from a path and create or get from cache Bot instance + + :param request: + :return: + """ + token = request.match_info["bot_token"] + if token not in self.bots: + self.bots[token] = Bot(token=token, **self.bot_settings) + return self.bots[token] diff --git a/env/Lib/site-packages/aiogram/webhook/security.py b/env/Lib/site-packages/aiogram/webhook/security.py new file mode 100644 index 0000000..91d3820 --- /dev/null +++ b/env/Lib/site-packages/aiogram/webhook/security.py @@ -0,0 +1,41 @@ +from ipaddress import IPv4Address, IPv4Network +from typing import Optional, Sequence, Set, Union + +DEFAULT_TELEGRAM_NETWORKS = [ + IPv4Network("149.154.160.0/20"), + IPv4Network("91.108.4.0/22"), +] + + +class IPFilter: + def __init__(self, ips: Optional[Sequence[Union[str, IPv4Network, IPv4Address]]] = None): + self._allowed_ips: Set[IPv4Address] = set() + + if ips: + self.allow(*ips) + + def allow(self, *ips: Union[str, IPv4Network, IPv4Address]) -> None: + for ip in ips: + self.allow_ip(ip) + + def allow_ip(self, ip: Union[str, IPv4Network, IPv4Address]) -> None: + if isinstance(ip, str): + ip = IPv4Network(ip) if "/" in ip else IPv4Address(ip) + if isinstance(ip, IPv4Address): + self._allowed_ips.add(ip) + elif isinstance(ip, IPv4Network): + self._allowed_ips.update(ip.hosts()) + else: + raise ValueError(f"Invalid type of ipaddress: {type(ip)} ('{ip}')") + + @classmethod + def default(cls) -> "IPFilter": + return cls(DEFAULT_TELEGRAM_NETWORKS) + + def check(self, ip: Union[str, IPv4Address]) -> bool: + if not isinstance(ip, IPv4Address): + ip = IPv4Address(ip) + return ip in self._allowed_ips + + def __contains__(self, item: Union[str, IPv4Address]) -> bool: + return self.check(item) diff --git a/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/INSTALLER b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/LICENSE b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/LICENSE new file mode 100644 index 0000000..f26bcf4 --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/LICENSE @@ -0,0 +1,279 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/METADATA b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/METADATA new file mode 100644 index 0000000..f4ba195 --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/METADATA @@ -0,0 +1,122 @@ +Metadata-Version: 2.1 +Name: aiohappyeyeballs +Version: 2.4.0 +Summary: Happy Eyeballs for asyncio +Home-page: https://github.com/aio-libs/aiohappyeyeballs +License: Python-2.0.1 +Author: J. Nick Koston +Author-email: nick@koston.org +Requires-Python: >=3.8 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Python Software Foundation License +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Software Development :: Libraries +Project-URL: Bug Tracker, https://github.com/aio-libs/aiohappyeyeballs/issues +Project-URL: Changelog, https://github.com/aio-libs/aiohappyeyeballs/blob/main/CHANGELOG.md +Project-URL: Documentation, https://aiohappyeyeballs.readthedocs.io +Project-URL: Repository, https://github.com/aio-libs/aiohappyeyeballs +Description-Content-Type: text/markdown + +# aiohappyeyeballs + +

+ + CI Status + + + Documentation Status + + + Test coverage percentage + +

+

+ + Poetry + + + black + + + pre-commit + +

+

+ + PyPI Version + + Supported Python versions + License +

+ +--- + +**Documentation**: https://aiohappyeyeballs.readthedocs.io + +**Source Code**: https://github.com/aio-libs/aiohappyeyeballs + +--- + +[Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs) +([RFC 8305](https://www.rfc-editor.org/rfc/rfc8305.html)) + +## Use case + +This library exists to allow connecting with +[Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs) +([RFC 8305](https://www.rfc-editor.org/rfc/rfc8305.html)) +when you +already have a list of addrinfo and not a DNS name. + +The stdlib version of `loop.create_connection()` +will only work when you pass in an unresolved name which +is not a good fit when using DNS caching or resolving +names via another method such as `zeroconf`. + +## Installation + +Install this via pip (or your favourite package manager): + +`pip install aiohappyeyeballs` + +## Example usage + +```python + +addr_infos = await loop.getaddrinfo("example.org", 80) + +socket = await start_connection(addr_infos) +socket = await start_connection(addr_infos, local_addr_infos=local_addr_infos, happy_eyeballs_delay=0.2) + +transport, protocol = await loop.create_connection( + MyProtocol, sock=socket, ...) + +# Remove the first address for each family from addr_info +pop_addr_infos_interleave(addr_info, 1) + +# Remove all matching address from addr_info +remove_addr_infos(addr_info, "dead::beef::") + +# Convert a local_addr to local_addr_infos +local_addr_infos = addr_to_addr_infos(("127.0.0.1",0)) +``` + +## Credits + +This package contains code from cpython and is licensed under the same terms as cpython itself. + +This package was created with +[Copier](https://copier.readthedocs.io/) and the +[browniebroke/pypackage-template](https://github.com/browniebroke/pypackage-template) +project template. + diff --git a/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/RECORD b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/RECORD new file mode 100644 index 0000000..f5db522 --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/RECORD @@ -0,0 +1,14 @@ +aiohappyeyeballs-2.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiohappyeyeballs-2.4.0.dist-info/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936 +aiohappyeyeballs-2.4.0.dist-info/METADATA,sha256=kBvy0zd3Thv-cT_rqGcgRCxvVqzXGRh8ghTC3zZfiLY,5901 +aiohappyeyeballs-2.4.0.dist-info/RECORD,, +aiohappyeyeballs-2.4.0.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88 +aiohappyeyeballs/__init__.py,sha256=OF-GJ4MGsl3QqO_2efe6UL11FAxRmzTDyDiwE6hgGc0,317 +aiohappyeyeballs/__pycache__/__init__.cpython-311.pyc,, +aiohappyeyeballs/__pycache__/impl.cpython-311.pyc,, +aiohappyeyeballs/__pycache__/types.cpython-311.pyc,, +aiohappyeyeballs/__pycache__/utils.cpython-311.pyc,, +aiohappyeyeballs/impl.py,sha256=dcYq05g3lGkkoxxd1KFnyXj4FKUaLfeplnJ93dLnoQQ,7289 +aiohappyeyeballs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiohappyeyeballs/types.py,sha256=iYPiBTl5J7YEjnIqEOVUTRPzz2DwqSHBRhvbAlM0zv0,234 +aiohappyeyeballs/utils.py,sha256=W_Oaf1iP8wYRHo6B95eYx-ZxbjpxyWwYgTdkhWqGF5c,3026 diff --git a/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/WHEEL b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/WHEEL new file mode 100644 index 0000000..d73ccaa --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs-2.4.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: poetry-core 1.9.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/env/Lib/site-packages/aiohappyeyeballs/__init__.py b/env/Lib/site-packages/aiohappyeyeballs/__init__.py new file mode 100644 index 0000000..9c98be9 --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs/__init__.py @@ -0,0 +1,13 @@ +__version__ = "2.4.0" + +from .impl import start_connection +from .types import AddrInfoType +from .utils import addr_to_addr_infos, pop_addr_infos_interleave, remove_addr_infos + +__all__ = ( + "start_connection", + "AddrInfoType", + "remove_addr_infos", + "pop_addr_infos_interleave", + "addr_to_addr_infos", +) diff --git a/env/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..1d121b1 Binary files /dev/null and b/env/Lib/site-packages/aiohappyeyeballs/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-311.pyc b/env/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-311.pyc new file mode 100644 index 0000000..0f55603 Binary files /dev/null and b/env/Lib/site-packages/aiohappyeyeballs/__pycache__/impl.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-311.pyc b/env/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000..43b967d Binary files /dev/null and b/env/Lib/site-packages/aiohappyeyeballs/__pycache__/types.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-311.pyc b/env/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000..0defec1 Binary files /dev/null and b/env/Lib/site-packages/aiohappyeyeballs/__pycache__/utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohappyeyeballs/impl.py b/env/Lib/site-packages/aiohappyeyeballs/impl.py new file mode 100644 index 0000000..64aff8c --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs/impl.py @@ -0,0 +1,205 @@ +"""Base implementation.""" + +import asyncio +import collections +import functools +import itertools +import socket +import sys +from asyncio import staggered +from typing import List, Optional, Sequence + +from .types import AddrInfoType + +if sys.version_info < (3, 8, 2): # noqa: UP036 + # asyncio.staggered is broken in Python 3.8.0 and 3.8.1 + # so it must be patched: + # https://github.com/aio-libs/aiohttp/issues/8556 + # https://bugs.python.org/issue39129 + # https://github.com/python/cpython/pull/17693 + import asyncio.futures + + asyncio.futures.TimeoutError = asyncio.TimeoutError # type: ignore[attr-defined] + + +async def start_connection( + addr_infos: Sequence[AddrInfoType], + *, + local_addr_infos: Optional[Sequence[AddrInfoType]] = None, + happy_eyeballs_delay: Optional[float] = None, + interleave: Optional[int] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, +) -> socket.socket: + """ + Connect to a TCP server. + + Create a socket connection to a specified destination. The + destination is specified as a list of AddrInfoType tuples as + returned from getaddrinfo(). + + The arguments are, in order: + + * ``family``: the address family, e.g. ``socket.AF_INET`` or + ``socket.AF_INET6``. + * ``type``: the socket type, e.g. ``socket.SOCK_STREAM`` or + ``socket.SOCK_DGRAM``. + * ``proto``: the protocol, e.g. ``socket.IPPROTO_TCP`` or + ``socket.IPPROTO_UDP``. + * ``canonname``: the canonical name of the address, e.g. + ``"www.python.org"``. + * ``sockaddr``: the socket address + + This method is a coroutine which will try to establish the connection + in the background. When successful, the coroutine returns a + socket. + + The expected use case is to use this method in conjunction with + loop.create_connection() to establish a connection to a server:: + + socket = await start_connection(addr_infos) + transport, protocol = await loop.create_connection( + MyProtocol, sock=socket, ...) + """ + if not (current_loop := loop): + current_loop = asyncio.get_running_loop() + + single_addr_info = len(addr_infos) == 1 + + if happy_eyeballs_delay is not None and interleave is None: + # If using happy eyeballs, default to interleave addresses by family + interleave = 1 + + if interleave and not single_addr_info: + addr_infos = _interleave_addrinfos(addr_infos, interleave) + + sock: Optional[socket.socket] = None + exceptions: List[List[OSError]] = [] + if happy_eyeballs_delay is None or single_addr_info: + # not using happy eyeballs + for addrinfo in addr_infos: + try: + sock = await _connect_sock( + current_loop, exceptions, addrinfo, local_addr_infos + ) + break + except OSError: + continue + else: # using happy eyeballs + sock, _, _ = await staggered.staggered_race( + ( + functools.partial( + _connect_sock, current_loop, exceptions, addrinfo, local_addr_infos + ) + for addrinfo in addr_infos + ), + happy_eyeballs_delay, + loop=current_loop, + ) + + if sock is None: + all_exceptions = [exc for sub in exceptions for exc in sub] + try: + first_exception = all_exceptions[0] + if len(all_exceptions) == 1: + raise first_exception + else: + # If they all have the same str(), raise one. + model = str(first_exception) + if all(str(exc) == model for exc in all_exceptions): + raise first_exception + # Raise a combined exception so the user can see all + # the various error messages. + msg = "Multiple exceptions: {}".format( + ", ".join(str(exc) for exc in all_exceptions) + ) + # If the errno is the same for all exceptions, raise + # an OSError with that errno. + first_errno = first_exception.errno + if all( + isinstance(exc, OSError) and exc.errno == first_errno + for exc in all_exceptions + ): + raise OSError(first_errno, msg) + raise OSError(msg) + finally: + all_exceptions = None # type: ignore[assignment] + exceptions = None # type: ignore[assignment] + + return sock + + +async def _connect_sock( + loop: asyncio.AbstractEventLoop, + exceptions: List[List[OSError]], + addr_info: AddrInfoType, + local_addr_infos: Optional[Sequence[AddrInfoType]] = None, +) -> socket.socket: + """Create, bind and connect one socket.""" + my_exceptions: list[OSError] = [] + exceptions.append(my_exceptions) + family, type_, proto, _, address = addr_info + sock = None + try: + sock = socket.socket(family=family, type=type_, proto=proto) + sock.setblocking(False) + if local_addr_infos is not None: + for lfamily, _, _, _, laddr in local_addr_infos: + # skip local addresses of different family + if lfamily != family: + continue + try: + sock.bind(laddr) + break + except OSError as exc: + msg = ( + f"error while attempting to bind on " + f"address {laddr!r}: " + f"{exc.strerror.lower()}" + ) + exc = OSError(exc.errno, msg) + my_exceptions.append(exc) + else: # all bind attempts failed + if my_exceptions: + raise my_exceptions.pop() + else: + raise OSError(f"no matching local address with {family=} found") + await loop.sock_connect(sock, address) + return sock + except OSError as exc: + my_exceptions.append(exc) + if sock is not None: + sock.close() + raise + except: + if sock is not None: + sock.close() + raise + finally: + exceptions = my_exceptions = None # type: ignore[assignment] + + +def _interleave_addrinfos( + addrinfos: Sequence[AddrInfoType], first_address_family_count: int = 1 +) -> List[AddrInfoType]: + """Interleave list of addrinfo tuples by family.""" + # Group addresses by family + addrinfos_by_family: collections.OrderedDict[int, List[AddrInfoType]] = ( + collections.OrderedDict() + ) + for addr in addrinfos: + family = addr[0] + if family not in addrinfos_by_family: + addrinfos_by_family[family] = [] + addrinfos_by_family[family].append(addr) + addrinfos_lists = list(addrinfos_by_family.values()) + + reordered: List[AddrInfoType] = [] + if first_address_family_count > 1: + reordered.extend(addrinfos_lists[0][: first_address_family_count - 1]) + del addrinfos_lists[0][: first_address_family_count - 1] + reordered.extend( + a + for a in itertools.chain.from_iterable(itertools.zip_longest(*addrinfos_lists)) + if a is not None + ) + return reordered diff --git a/env/Lib/site-packages/aiohappyeyeballs/py.typed b/env/Lib/site-packages/aiohappyeyeballs/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/aiohappyeyeballs/types.py b/env/Lib/site-packages/aiohappyeyeballs/types.py new file mode 100644 index 0000000..01d79a2 --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs/types.py @@ -0,0 +1,12 @@ +"""Types for aiohappyeyeballs.""" + +import socket +from typing import Tuple, Union + +AddrInfoType = Tuple[ + Union[int, socket.AddressFamily], + Union[int, socket.SocketKind], + int, + str, + Tuple, # type: ignore[type-arg] +] diff --git a/env/Lib/site-packages/aiohappyeyeballs/utils.py b/env/Lib/site-packages/aiohappyeyeballs/utils.py new file mode 100644 index 0000000..b5745ae --- /dev/null +++ b/env/Lib/site-packages/aiohappyeyeballs/utils.py @@ -0,0 +1,97 @@ +"""Utility functions for aiohappyeyeballs.""" + +import ipaddress +import socket +from typing import Dict, List, Optional, Tuple, Union + +from .types import AddrInfoType + + +def addr_to_addr_infos( + addr: Optional[ + Union[Tuple[str, int, int, int], Tuple[str, int, int], Tuple[str, int]] + ] +) -> Optional[List[AddrInfoType]]: + """Convert an address tuple to a list of addr_info tuples.""" + if addr is None: + return None + host = addr[0] + port = addr[1] + is_ipv6 = ":" in host + if is_ipv6: + flowinfo = 0 + scopeid = 0 + addr_len = len(addr) + if addr_len >= 4: + scopeid = addr[3] # type: ignore[misc] + if addr_len >= 3: + flowinfo = addr[2] # type: ignore[misc] + addr = (host, port, flowinfo, scopeid) + family = socket.AF_INET6 + else: + addr = (host, port) + family = socket.AF_INET + return [(family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr)] + + +def pop_addr_infos_interleave( + addr_infos: List[AddrInfoType], interleave: Optional[int] = None +) -> None: + """ + Pop addr_info from the list of addr_infos by family up to interleave times. + + The interleave parameter is used to know how many addr_infos for + each family should be popped of the top of the list. + """ + seen: Dict[int, int] = {} + if interleave is None: + interleave = 1 + to_remove: List[AddrInfoType] = [] + for addr_info in addr_infos: + family = addr_info[0] + if family not in seen: + seen[family] = 0 + if seen[family] < interleave: + to_remove.append(addr_info) + seen[family] += 1 + for addr_info in to_remove: + addr_infos.remove(addr_info) + + +def _addr_tuple_to_ip_address( + addr: Union[Tuple[str, int], Tuple[str, int, int, int]] +) -> Union[ + Tuple[ipaddress.IPv4Address, int], Tuple[ipaddress.IPv6Address, int, int, int] +]: + """Convert an address tuple to an IPv4Address.""" + return (ipaddress.ip_address(addr[0]), *addr[1:]) + + +def remove_addr_infos( + addr_infos: List[AddrInfoType], + addr: Union[Tuple[str, int], Tuple[str, int, int, int]], +) -> None: + """ + Remove an address from the list of addr_infos. + + The addr value is typically the return value of + sock.getpeername(). + """ + bad_addrs_infos: List[AddrInfoType] = [] + for addr_info in addr_infos: + if addr_info[-1] == addr: + bad_addrs_infos.append(addr_info) + if bad_addrs_infos: + for bad_addr_info in bad_addrs_infos: + addr_infos.remove(bad_addr_info) + return + # Slow path in case addr is formatted differently + match_addr = _addr_tuple_to_ip_address(addr) + for addr_info in addr_infos: + if match_addr == _addr_tuple_to_ip_address(addr_info[-1]): + bad_addrs_infos.append(addr_info) + if bad_addrs_infos: + for bad_addr_info in bad_addrs_infos: + addr_infos.remove(bad_addr_info) + return + raise ValueError(f"Address {addr} not found in addr_infos") diff --git a/env/Lib/site-packages/aiohttp-3.10.5.dist-info/INSTALLER b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/aiohttp-3.10.5.dist-info/LICENSE.txt b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/LICENSE.txt new file mode 100644 index 0000000..e497a32 --- /dev/null +++ b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/LICENSE.txt @@ -0,0 +1,13 @@ + Copyright aio-libs contributors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/env/Lib/site-packages/aiohttp-3.10.5.dist-info/METADATA b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/METADATA new file mode 100644 index 0000000..01beba7 --- /dev/null +++ b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/METADATA @@ -0,0 +1,246 @@ +Metadata-Version: 2.1 +Name: aiohttp +Version: 3.10.5 +Summary: Async http client/server framework (asyncio) +Home-page: https://github.com/aio-libs/aiohttp +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache 2 +Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org +Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org +Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp +Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html +Project-URL: Docs: RTD, https://docs.aiohttp.org +Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp +Classifier: Development Status :: 5 - Production/Stable +Classifier: Framework :: AsyncIO +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE.txt +Requires-Dist: aiohappyeyeballs >=2.3.0 +Requires-Dist: aiosignal >=1.1.2 +Requires-Dist: attrs >=17.3.0 +Requires-Dist: frozenlist >=1.1.1 +Requires-Dist: multidict <7.0,>=4.5 +Requires-Dist: yarl <2.0,>=1.0 +Requires-Dist: async-timeout <5.0,>=4.0 ; python_version < "3.11" +Provides-Extra: speedups +Requires-Dist: brotlicffi ; (platform_python_implementation != "CPython") and extra == 'speedups' +Requires-Dist: Brotli ; (platform_python_implementation == "CPython") and extra == 'speedups' +Requires-Dist: aiodns >=3.2.0 ; (sys_platform == "linux" or sys_platform == "darwin") and extra == 'speedups' + +================================== +Async http client/server framework +================================== + +.. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg + :height: 64px + :width: 64px + :alt: aiohttp logo + +| + +.. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg + :target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI + :alt: GitHub Actions status for master branch + +.. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/aiohttp + :alt: codecov.io status for master branch + +.. image:: https://badge.fury.io/py/aiohttp.svg + :target: https://pypi.org/project/aiohttp + :alt: Latest PyPI package version + +.. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest + :target: https://docs.aiohttp.org/ + :alt: Latest Read The Docs + +.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs:matrix.org + :alt: Matrix Room — #aio-libs:matrix.org + +.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs-space:matrix.org + :alt: Matrix Space — #aio-libs-space:matrix.org + + +Key Features +============ + +- Supports both client and server side of HTTP protocol. +- Supports both client and server Web-Sockets out-of-the-box and avoids + Callback Hell. +- Provides Web-server with middleware and pluggable routing. + + +Getting started +=============== + +Client +------ + +To get something from the web: + +.. code-block:: python + + import aiohttp + import asyncio + + async def main(): + + async with aiohttp.ClientSession() as session: + async with session.get('http://python.org') as response: + + print("Status:", response.status) + print("Content-type:", response.headers['content-type']) + + html = await response.text() + print("Body:", html[:15], "...") + + asyncio.run(main()) + +This prints: + +.. code-block:: + + Status: 200 + Content-type: text/html; charset=utf-8 + Body: ... + +Coming from `requests `_ ? Read `why we need so many lines `_. + +Server +------ + +An example using a simple server: + +.. code-block:: python + + # examples/server_simple.py + from aiohttp import web + + async def handle(request): + name = request.match_info.get('name', "Anonymous") + text = "Hello, " + name + return web.Response(text=text) + + async def wshandle(request): + ws = web.WebSocketResponse() + await ws.prepare(request) + + async for msg in ws: + if msg.type == web.WSMsgType.text: + await ws.send_str("Hello, {}".format(msg.data)) + elif msg.type == web.WSMsgType.binary: + await ws.send_bytes(msg.data) + elif msg.type == web.WSMsgType.close: + break + + return ws + + + app = web.Application() + app.add_routes([web.get('/', handle), + web.get('/echo', wshandle), + web.get('/{name}', handle)]) + + if __name__ == '__main__': + web.run_app(app) + + +Documentation +============= + +https://aiohttp.readthedocs.io/ + + +Demos +===== + +https://github.com/aio-libs/aiohttp-demos + + +External links +============== + +* `Third party libraries + `_ +* `Built with aiohttp + `_ +* `Powered by aiohttp + `_ + +Feel free to make a Pull Request for adding your link to these pages! + + +Communication channels +====================== + +*aio-libs Discussions*: https://github.com/aio-libs/aiohttp/discussions + +*Matrix*: `#aio-libs:matrix.org `_ + +We support `Stack Overflow +`_. +Please add *aiohttp* tag to your question there. + +Requirements +============ + +- async-timeout_ +- attrs_ +- multidict_ +- yarl_ +- frozenlist_ + +Optionally you may install the aiodns_ library (highly recommended for sake of speed). + +.. _aiodns: https://pypi.python.org/pypi/aiodns +.. _attrs: https://github.com/python-attrs/attrs +.. _multidict: https://pypi.python.org/pypi/multidict +.. _frozenlist: https://pypi.org/project/frozenlist/ +.. _yarl: https://pypi.python.org/pypi/yarl +.. _async-timeout: https://pypi.python.org/pypi/async_timeout + +License +======= + +``aiohttp`` is offered under the Apache 2 license. + + +Keepsafe +======== + +The aiohttp community would like to thank Keepsafe +(https://www.getkeepsafe.com) for its support in the early days of +the project. + + +Source code +=========== + +The latest developer version is available in a GitHub repository: +https://github.com/aio-libs/aiohttp + +Benchmarks +========== + +If you are interested in efficiency, the AsyncIO community maintains a +list of benchmarks on the official wiki: +https://github.com/python/asyncio/wiki/Benchmarks diff --git a/env/Lib/site-packages/aiohttp-3.10.5.dist-info/RECORD b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/RECORD new file mode 100644 index 0000000..43a54be --- /dev/null +++ b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/RECORD @@ -0,0 +1,119 @@ +aiohttp-3.10.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiohttp-3.10.5.dist-info/LICENSE.txt,sha256=wUk-nxDVnR-6n53ygAjhVX4zz5-6yM4SY6ozk5goA94,601 +aiohttp-3.10.5.dist-info/METADATA,sha256=IrmDXPIC5CEFgnNv8nQdliPEHM1cUUw-R_wuSwjA2tA,7784 +aiohttp-3.10.5.dist-info/RECORD,, +aiohttp-3.10.5.dist-info/WHEEL,sha256=dCuJ4f0faaLdEJehgDqauYbxfYcPtrcUnDoQw-il14k,101 +aiohttp-3.10.5.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8 +aiohttp/.hash/_cparser.pxd.hash,sha256=dVGMrCmyJM_owqoRLPezK095md0X5R319koTuhUN6DQ,64 +aiohttp/.hash/_find_header.pxd.hash,sha256=W5qRPWDc55gArGZkriI5tztmQHkrdwR6NdQfRQfTxIg,64 +aiohttp/.hash/_helpers.pyi.hash,sha256=bAsxbXsjcZ5gbj1c561GYcRtQ5REXxrCihR-HN0XKPk,64 +aiohttp/.hash/_helpers.pyx.hash,sha256=-DfrN0XUqBhyb8bp2fJQVb1Lo9S1S-psob-7MJBM18c,64 +aiohttp/.hash/_http_parser.pyx.hash,sha256=zqi4Dj2ahyHj_TgwxkJ_9GPy9Vo_oNekL0_JshY-6ZY,64 +aiohttp/.hash/_http_writer.pyx.hash,sha256=z39c0hUcdud-ZCon2d9bWpxrFMVdW1dvjtCgxW4RDnI,64 +aiohttp/.hash/_websocket.pyx.hash,sha256=90x5ulhWiFtw2wAri2_82Zas5i3iEkJ-flYJK9Xx-SY,64 +aiohttp/.hash/hdrs.py.hash,sha256=QBHPUkJcp8iPZv3ENUbevgpJzljxoP2qwkBeX3nQ82o,64 +aiohttp/__init__.py,sha256=68WmyslV950A4d5X2ZDFT85PU4W-Zeuo0A8qGTosrV4,7781 +aiohttp/__pycache__/__init__.cpython-311.pyc,, +aiohttp/__pycache__/abc.cpython-311.pyc,, +aiohttp/__pycache__/base_protocol.cpython-311.pyc,, +aiohttp/__pycache__/client.cpython-311.pyc,, +aiohttp/__pycache__/client_exceptions.cpython-311.pyc,, +aiohttp/__pycache__/client_proto.cpython-311.pyc,, +aiohttp/__pycache__/client_reqrep.cpython-311.pyc,, +aiohttp/__pycache__/client_ws.cpython-311.pyc,, +aiohttp/__pycache__/compression_utils.cpython-311.pyc,, +aiohttp/__pycache__/connector.cpython-311.pyc,, +aiohttp/__pycache__/cookiejar.cpython-311.pyc,, +aiohttp/__pycache__/formdata.cpython-311.pyc,, +aiohttp/__pycache__/hdrs.cpython-311.pyc,, +aiohttp/__pycache__/helpers.cpython-311.pyc,, +aiohttp/__pycache__/http.cpython-311.pyc,, +aiohttp/__pycache__/http_exceptions.cpython-311.pyc,, +aiohttp/__pycache__/http_parser.cpython-311.pyc,, +aiohttp/__pycache__/http_websocket.cpython-311.pyc,, +aiohttp/__pycache__/http_writer.cpython-311.pyc,, +aiohttp/__pycache__/locks.cpython-311.pyc,, +aiohttp/__pycache__/log.cpython-311.pyc,, +aiohttp/__pycache__/multipart.cpython-311.pyc,, +aiohttp/__pycache__/payload.cpython-311.pyc,, +aiohttp/__pycache__/payload_streamer.cpython-311.pyc,, +aiohttp/__pycache__/pytest_plugin.cpython-311.pyc,, +aiohttp/__pycache__/resolver.cpython-311.pyc,, +aiohttp/__pycache__/streams.cpython-311.pyc,, +aiohttp/__pycache__/tcp_helpers.cpython-311.pyc,, +aiohttp/__pycache__/test_utils.cpython-311.pyc,, +aiohttp/__pycache__/tracing.cpython-311.pyc,, +aiohttp/__pycache__/typedefs.cpython-311.pyc,, +aiohttp/__pycache__/web.cpython-311.pyc,, +aiohttp/__pycache__/web_app.cpython-311.pyc,, +aiohttp/__pycache__/web_exceptions.cpython-311.pyc,, +aiohttp/__pycache__/web_fileresponse.cpython-311.pyc,, +aiohttp/__pycache__/web_log.cpython-311.pyc,, +aiohttp/__pycache__/web_middlewares.cpython-311.pyc,, +aiohttp/__pycache__/web_protocol.cpython-311.pyc,, +aiohttp/__pycache__/web_request.cpython-311.pyc,, +aiohttp/__pycache__/web_response.cpython-311.pyc,, +aiohttp/__pycache__/web_routedef.cpython-311.pyc,, +aiohttp/__pycache__/web_runner.cpython-311.pyc,, +aiohttp/__pycache__/web_server.cpython-311.pyc,, +aiohttp/__pycache__/web_urldispatcher.cpython-311.pyc,, +aiohttp/__pycache__/web_ws.cpython-311.pyc,, +aiohttp/__pycache__/worker.cpython-311.pyc,, +aiohttp/_cparser.pxd,sha256=W6-cu0SyHhOEPeb475NvxagQ1Jz9pWqyZJvwEqTLNs0,4476 +aiohttp/_find_header.pxd,sha256=BFUSmxhemBtblqxzjzH3x03FfxaWlTyuAIOz8YZ5_nM,70 +aiohttp/_headers.pxi,sha256=1MhCe6Un_KI1tpO85HnDfzVO94BhcirLanAOys5FIHA,2090 +aiohttp/_helpers.cp311-win_amd64.pyd,sha256=WzS2tywYKnRAfaTW6ESVnrOWmdAxPM1rjLzK7s7aqPM,54784 +aiohttp/_helpers.pyi,sha256=2Hd5IC0Zf4YTEJ412suyyhsh1kVyVDv5g4stgyo2Ksc,208 +aiohttp/_helpers.pyx,sha256=tgl7fZh0QMT6cjf4jSJ8iaO6DdQD3GON2-SH4N5_ETg,1084 +aiohttp/_http_parser.cp311-win_amd64.pyd,sha256=MTnxWQoyV1L51bC9YitigbltpukH0lwPD8SsY4iSJSw,266240 +aiohttp/_http_parser.pyx,sha256=gukaWoH-X5k2e5qaZnxzDpzwROijbXde2s73xtLStF4,29236 +aiohttp/_http_writer.cp311-win_amd64.pyd,sha256=hrgbtvHh3yolDTcdP49HdUKIp-fxRmojcFLScl5d9T4,49152 +aiohttp/_http_writer.pyx,sha256=8CBLytO2rx1kdpWe9HYSznhLXdeZWyE-3xI7jaGasag,4738 +aiohttp/_websocket.cp311-win_amd64.pyd,sha256=_qMBjD30-S2Ygcz0rKjzzZi4RFnWU5w46UnA2SJmO_o,36864 +aiohttp/_websocket.pyx,sha256=o9J7yi9c2-jTBjE3dUkXxhDWKvRWJz5GZfyLsgJQa38,1617 +aiohttp/abc.py,sha256=ZZW_iR6jajNyfW3vktthecqV4FyaKvCv_0W9xIT1W5I,6331 +aiohttp/base_protocol.py,sha256=N4IzuMQLGHG7AJji9um-2gqQxKGo41P3aCZwrvegumc,2971 +aiohttp/client.py,sha256=HjV18OwmQlahPwW9w3qY7ypUR-kskCEHQcMX-S9uftU,54180 +aiohttp/client_exceptions.py,sha256=Rat0bV5BjGlmp-3gU3GtW9GGrdhYMnNLLWT-j0HtHbo,11125 +aiohttp/client_proto.py,sha256=7tAgGcEJwd7VEWHyTyrhQ_DQkwj9T34rGC1G_9PJCRk,10445 +aiohttp/client_reqrep.py,sha256=tChBwbMyZUiyd9CSckMBP52hHAtPrFPCnYCRc9jTviI,42168 +aiohttp/client_ws.py,sha256=oxUScZbcggPQmeRqSBo-XJWv3_O7mAq9dVIDxtBktZo,14327 +aiohttp/compression_utils.py,sha256=majGJXsz7hoxjhdOK9HTvcPwOYpCbtN0VxYRg4inwKo,5214 +aiohttp/connector.py,sha256=cObqWwS65TO-l-hO-o4muyf-gzXu2F97f4bLvhiJLYY,59558 +aiohttp/cookiejar.py,sha256=O9fDAlTLsdaxWYY_5i-9Sbnwxzf2nRweqXGAGdP7VN8,14985 +aiohttp/formdata.py,sha256=XRu5kZi8MqEMoct2KGBrVetaHVthIRI__0o3UQfctzc,6703 +aiohttp/hdrs.py,sha256=_JN4MBE-UoBXGWGoSCKhIviTRc2IXS4fyk5nnuox0Ak,4721 +aiohttp/helpers.py,sha256=xc_sYCUrdW_YyA5QaD_E9gd-XHPJS5yuIC7SIJgUsOM,31282 +aiohttp/http.py,sha256=DGKcwDbgIMpasv7s2jeKCRuixyj7W-RIrihRFjj0xcY,1914 +aiohttp/http_exceptions.py,sha256=Mvk7SkZ4a7enFQ_koyXx2Dy3E5uoW8M8tndV4bC6Qs8,2820 +aiohttp/http_parser.py,sha256=TtyBKUpf2SRY6hFTSL-Pk6xvt_oiGtO_v_GPI5VwzOI,36820 +aiohttp/http_websocket.py,sha256=0FSqqFqnMvI1g7X4z-sotEomwrD6x-119-yfogoQhVI,26668 +aiohttp/http_writer.py,sha256=p8H39HhtilQEE90njvtJHc94Am95zjHNoS8T1JcNXJc,6131 +aiohttp/locks.py,sha256=vp1Z4zx0SvooSffw88dkZ-7qpk2CqRf5vWh2dpKagTA,1177 +aiohttp/log.py,sha256=zYUTvXsMQ9Sz1yNN8kXwd5Qxu49a1FzjZ_wQqriEc8M,333 +aiohttp/multipart.py,sha256=IIwqrT_tUBFfS3GJJKC-xL97A-03fSGgN-dnJydnW7s,37559 +aiohttp/payload.py,sha256=9wzXARKXbec81DHYfiCr354mcHTY3isfqVqmusRSXXM,14029 +aiohttp/payload_streamer.py,sha256=rBb3jAFcwAK1QOgbhya2y4zGjhT11oQrepdcffA1_jM,2162 +aiohttp/py.typed,sha256=3VVwXUAWVEVX7sDwyYDnW5ZdBC9_Z9AJAFfLCleUW0k,8 +aiohttp/pytest_plugin.py,sha256=XvkgjZNMUTEGaYglCgeOIDnN-ePIanED1nrX9GSwEdg,12328 +aiohttp/resolver.py,sha256=ZAmhwsoNfweKy8C9M-VOEUpZKyAZM5CjAKAgUDTKWlY,6585 +aiohttp/streams.py,sha256=v9GkCFn9mynR1yGB1Xl6mwxEJXsOC4T-DzoL4IC0XOU,21812 +aiohttp/tcp_helpers.py,sha256=K-hhGh3jd6qCEnHJo8LvFyfJwBjh99UKI7A0aSRVhj4,998 +aiohttp/test_utils.py,sha256=isd4eSUqdS0uPxIZ1IhOliE4nttE8PKNLZQL5S7s44A,22614 +aiohttp/tracing.py,sha256=c3C8lnLZ0G1Jj3Iv1GgV-Op8PwcM4m6d931w502hSgI,15607 +aiohttp/typedefs.py,sha256=psCpiYoYBCl22EqlqihhPhjEQlPiAx6Von8RpKgY674,1691 +aiohttp/web.py,sha256=4JPfYt8EUmw-tSKmASCQjXSJlY-ImhGCh_i0ajD6VEk,18641 +aiohttp/web_app.py,sha256=EVqAwfU9ma8ZU4xiT7gmA3fmH0gzlPRsGy03lHPp6uE,18921 +aiohttp/web_exceptions.py,sha256=itNRhCMDJFhnMWftr5SyTsoqh-i0n9rzTj0sjcAEUjo,10812 +aiohttp/web_fileresponse.py,sha256=0mQthdMhD_1pM7gfQ14WN0qfiE3gaSjOPZskAyPfq0M,14052 +aiohttp/web_log.py,sha256=w81HIudhfSxfodo2Fjkok7jWT56XXIrVMJN6ihYnLo0,8014 +aiohttp/web_middlewares.py,sha256=rYWtxDZ2AM3C2FvNuNyffpfmMfcHrxkSZMaTcsG1T_Q,4148 +aiohttp/web_protocol.py,sha256=vDlBoA58FRUlBkIu1IT_Jh8hnE1_dMQ_VfeY_Y-LEKc,24597 +aiohttp/web_request.py,sha256=1_BVNJUm5Q6xzX0Hmkl1gr45hDa3oSb4E4SuS1MYdT4,30458 +aiohttp/web_response.py,sha256=hIrfUaB5EhsXgnt1LP-HhozhcxXgDAs5CDwAVTQjuG8,28728 +aiohttp/web_routedef.py,sha256=nRRvg7i5VtJJlyqxvGBzpEO2qIMgPEWueTB3bhX3l9U,6330 +aiohttp/web_runner.py,sha256=Z6odFUNBAE4lqcIB9zl1YtDLyZ6QKTRouB3YjmA7WCc,12084 +aiohttp/web_server.py,sha256=aHycxJrS1nytAj1IjIpKeDCQWsAgrDxm1_hRUmumqpI,2846 +aiohttp/web_urldispatcher.py,sha256=VAoqh9F2QPlUywBJIpWcjtQER0WL-CgtsbcshfY3IFk,45073 +aiohttp/web_ws.py,sha256=AcAFbWqUE2S7gi9o7os-myrfVecigSVySaYQ-oUdczU,22254 +aiohttp/worker.py,sha256=vDMxlk-Mo3rzN4yubw2-c8T6yg7PRY8Mv0NLuRm8lWw,8212 diff --git a/env/Lib/site-packages/aiohttp-3.10.5.dist-info/WHEEL b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/WHEEL new file mode 100644 index 0000000..7ba121b --- /dev/null +++ b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (72.2.0) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/env/Lib/site-packages/aiohttp-3.10.5.dist-info/top_level.txt b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/top_level.txt new file mode 100644 index 0000000..ee4ba4f --- /dev/null +++ b/env/Lib/site-packages/aiohttp-3.10.5.dist-info/top_level.txt @@ -0,0 +1 @@ +aiohttp diff --git a/env/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash b/env/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash new file mode 100644 index 0000000..1dc9b9a --- /dev/null +++ b/env/Lib/site-packages/aiohttp/.hash/_cparser.pxd.hash @@ -0,0 +1 @@ +5baf9cbb44b21e13843de6f8ef936fc5a810d49cfda56ab2649bf012a4cb36cd \ No newline at end of file diff --git a/env/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash b/env/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash new file mode 100644 index 0000000..ab9d476 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/.hash/_find_header.pxd.hash @@ -0,0 +1 @@ +0455129b185e981b5b96ac738f31f7c74dc57f1696953cae0083b3f18679fe73 \ No newline at end of file diff --git a/env/Lib/site-packages/aiohttp/.hash/_helpers.pyi.hash b/env/Lib/site-packages/aiohttp/.hash/_helpers.pyi.hash new file mode 100644 index 0000000..c304d37 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/.hash/_helpers.pyi.hash @@ -0,0 +1 @@ +d87779202d197f8613109e35dacbb2ca1b21d64572543bf9838b2d832a362ac7 \ No newline at end of file diff --git a/env/Lib/site-packages/aiohttp/.hash/_helpers.pyx.hash b/env/Lib/site-packages/aiohttp/.hash/_helpers.pyx.hash new file mode 100644 index 0000000..8164dbb --- /dev/null +++ b/env/Lib/site-packages/aiohttp/.hash/_helpers.pyx.hash @@ -0,0 +1 @@ +b6097b7d987440c4fa7237f88d227c89a3ba0dd403dc638ddbe487e0de7f1138 \ No newline at end of file diff --git a/env/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash b/env/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash new file mode 100644 index 0000000..b332ee3 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/.hash/_http_parser.pyx.hash @@ -0,0 +1 @@ +82e91a5a81fe5f99367b9a9a667c730e9cf044e8a36d775edacef7c6d2d2b45e \ No newline at end of file diff --git a/env/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash b/env/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash new file mode 100644 index 0000000..10d8347 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/.hash/_http_writer.pyx.hash @@ -0,0 +1 @@ +f0204bcad3b6af1d6476959ef47612ce784b5dd7995b213edf123b8da19ab1a8 \ No newline at end of file diff --git a/env/Lib/site-packages/aiohttp/.hash/_websocket.pyx.hash b/env/Lib/site-packages/aiohttp/.hash/_websocket.pyx.hash new file mode 100644 index 0000000..511f26f --- /dev/null +++ b/env/Lib/site-packages/aiohttp/.hash/_websocket.pyx.hash @@ -0,0 +1 @@ +a3d27bca2f5cdbe8d3063137754917c610d62af456273e4665fc8bb202506b7f \ No newline at end of file diff --git a/env/Lib/site-packages/aiohttp/.hash/hdrs.py.hash b/env/Lib/site-packages/aiohttp/.hash/hdrs.py.hash new file mode 100644 index 0000000..b032e6e --- /dev/null +++ b/env/Lib/site-packages/aiohttp/.hash/hdrs.py.hash @@ -0,0 +1 @@ +fc937830113e5280571961a84822a122f89345cd885d2e1fca4e679eea31d009 \ No newline at end of file diff --git a/env/Lib/site-packages/aiohttp/__init__.py b/env/Lib/site-packages/aiohttp/__init__.py new file mode 100644 index 0000000..bd65f92 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/__init__.py @@ -0,0 +1,254 @@ +__version__ = "3.10.5" + +from typing import TYPE_CHECKING, Tuple + +from . import hdrs as hdrs +from .client import ( + BaseConnector, + ClientConnectionError, + ClientConnectorCertificateError, + ClientConnectorError, + ClientConnectorSSLError, + ClientError, + ClientHttpProxyError, + ClientOSError, + ClientPayloadError, + ClientProxyConnectionError, + ClientRequest, + ClientResponse, + ClientResponseError, + ClientSession, + ClientSSLError, + ClientTimeout, + ClientWebSocketResponse, + ConnectionTimeoutError, + ContentTypeError, + Fingerprint, + InvalidURL, + InvalidUrlClientError, + InvalidUrlRedirectClientError, + NamedPipeConnector, + NonHttpUrlClientError, + NonHttpUrlRedirectClientError, + RedirectClientError, + RequestInfo, + ServerConnectionError, + ServerDisconnectedError, + ServerFingerprintMismatch, + ServerTimeoutError, + SocketTimeoutError, + TCPConnector, + TooManyRedirects, + UnixConnector, + WSServerHandshakeError, + request, +) +from .cookiejar import CookieJar as CookieJar, DummyCookieJar as DummyCookieJar +from .formdata import FormData as FormData +from .helpers import BasicAuth, ChainMapProxy, ETag +from .http import ( + HttpVersion as HttpVersion, + HttpVersion10 as HttpVersion10, + HttpVersion11 as HttpVersion11, + WebSocketError as WebSocketError, + WSCloseCode as WSCloseCode, + WSMessage as WSMessage, + WSMsgType as WSMsgType, +) +from .multipart import ( + BadContentDispositionHeader as BadContentDispositionHeader, + BadContentDispositionParam as BadContentDispositionParam, + BodyPartReader as BodyPartReader, + MultipartReader as MultipartReader, + MultipartWriter as MultipartWriter, + content_disposition_filename as content_disposition_filename, + parse_content_disposition as parse_content_disposition, +) +from .payload import ( + PAYLOAD_REGISTRY as PAYLOAD_REGISTRY, + AsyncIterablePayload as AsyncIterablePayload, + BufferedReaderPayload as BufferedReaderPayload, + BytesIOPayload as BytesIOPayload, + BytesPayload as BytesPayload, + IOBasePayload as IOBasePayload, + JsonPayload as JsonPayload, + Payload as Payload, + StringIOPayload as StringIOPayload, + StringPayload as StringPayload, + TextIOPayload as TextIOPayload, + get_payload as get_payload, + payload_type as payload_type, +) +from .payload_streamer import streamer as streamer +from .resolver import ( + AsyncResolver as AsyncResolver, + DefaultResolver as DefaultResolver, + ThreadedResolver as ThreadedResolver, +) +from .streams import ( + EMPTY_PAYLOAD as EMPTY_PAYLOAD, + DataQueue as DataQueue, + EofStream as EofStream, + FlowControlDataQueue as FlowControlDataQueue, + StreamReader as StreamReader, +) +from .tracing import ( + TraceConfig as TraceConfig, + TraceConnectionCreateEndParams as TraceConnectionCreateEndParams, + TraceConnectionCreateStartParams as TraceConnectionCreateStartParams, + TraceConnectionQueuedEndParams as TraceConnectionQueuedEndParams, + TraceConnectionQueuedStartParams as TraceConnectionQueuedStartParams, + TraceConnectionReuseconnParams as TraceConnectionReuseconnParams, + TraceDnsCacheHitParams as TraceDnsCacheHitParams, + TraceDnsCacheMissParams as TraceDnsCacheMissParams, + TraceDnsResolveHostEndParams as TraceDnsResolveHostEndParams, + TraceDnsResolveHostStartParams as TraceDnsResolveHostStartParams, + TraceRequestChunkSentParams as TraceRequestChunkSentParams, + TraceRequestEndParams as TraceRequestEndParams, + TraceRequestExceptionParams as TraceRequestExceptionParams, + TraceRequestRedirectParams as TraceRequestRedirectParams, + TraceRequestStartParams as TraceRequestStartParams, + TraceResponseChunkReceivedParams as TraceResponseChunkReceivedParams, +) + +if TYPE_CHECKING: + # At runtime these are lazy-loaded at the bottom of the file. + from .worker import ( + GunicornUVLoopWebWorker as GunicornUVLoopWebWorker, + GunicornWebWorker as GunicornWebWorker, + ) + +__all__: Tuple[str, ...] = ( + "hdrs", + # client + "BaseConnector", + "ClientConnectionError", + "ClientConnectorCertificateError", + "ClientConnectorError", + "ClientConnectorSSLError", + "ClientError", + "ClientHttpProxyError", + "ClientOSError", + "ClientPayloadError", + "ClientProxyConnectionError", + "ClientResponse", + "ClientRequest", + "ClientResponseError", + "ClientSSLError", + "ClientSession", + "ClientTimeout", + "ClientWebSocketResponse", + "ConnectionTimeoutError", + "ContentTypeError", + "Fingerprint", + "InvalidURL", + "InvalidUrlClientError", + "InvalidUrlRedirectClientError", + "NonHttpUrlClientError", + "NonHttpUrlRedirectClientError", + "RedirectClientError", + "RequestInfo", + "ServerConnectionError", + "ServerDisconnectedError", + "ServerFingerprintMismatch", + "ServerTimeoutError", + "SocketTimeoutError", + "TCPConnector", + "TooManyRedirects", + "UnixConnector", + "NamedPipeConnector", + "WSServerHandshakeError", + "request", + # cookiejar + "CookieJar", + "DummyCookieJar", + # formdata + "FormData", + # helpers + "BasicAuth", + "ChainMapProxy", + "ETag", + # http + "HttpVersion", + "HttpVersion10", + "HttpVersion11", + "WSMsgType", + "WSCloseCode", + "WSMessage", + "WebSocketError", + # multipart + "BadContentDispositionHeader", + "BadContentDispositionParam", + "BodyPartReader", + "MultipartReader", + "MultipartWriter", + "content_disposition_filename", + "parse_content_disposition", + # payload + "AsyncIterablePayload", + "BufferedReaderPayload", + "BytesIOPayload", + "BytesPayload", + "IOBasePayload", + "JsonPayload", + "PAYLOAD_REGISTRY", + "Payload", + "StringIOPayload", + "StringPayload", + "TextIOPayload", + "get_payload", + "payload_type", + # payload_streamer + "streamer", + # resolver + "AsyncResolver", + "DefaultResolver", + "ThreadedResolver", + # streams + "DataQueue", + "EMPTY_PAYLOAD", + "EofStream", + "FlowControlDataQueue", + "StreamReader", + # tracing + "TraceConfig", + "TraceConnectionCreateEndParams", + "TraceConnectionCreateStartParams", + "TraceConnectionQueuedEndParams", + "TraceConnectionQueuedStartParams", + "TraceConnectionReuseconnParams", + "TraceDnsCacheHitParams", + "TraceDnsCacheMissParams", + "TraceDnsResolveHostEndParams", + "TraceDnsResolveHostStartParams", + "TraceRequestChunkSentParams", + "TraceRequestEndParams", + "TraceRequestExceptionParams", + "TraceRequestRedirectParams", + "TraceRequestStartParams", + "TraceResponseChunkReceivedParams", + # workers (imported lazily with __getattr__) + "GunicornUVLoopWebWorker", + "GunicornWebWorker", +) + + +def __dir__() -> Tuple[str, ...]: + return __all__ + ("__author__", "__doc__") + + +def __getattr__(name: str) -> object: + global GunicornUVLoopWebWorker, GunicornWebWorker + + # Importing gunicorn takes a long time (>100ms), so only import if actually needed. + if name in ("GunicornUVLoopWebWorker", "GunicornWebWorker"): + try: + from .worker import GunicornUVLoopWebWorker as guv, GunicornWebWorker as gw + except ImportError: + return None + + GunicornUVLoopWebWorker = guv # type: ignore[misc] + GunicornWebWorker = gw # type: ignore[misc] + return guv if name == "GunicornUVLoopWebWorker" else gw + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/env/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..dff8502 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/abc.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/abc.cpython-311.pyc new file mode 100644 index 0000000..a632066 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/abc.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-311.pyc new file mode 100644 index 0000000..5cd2d7d Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/base_protocol.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/client.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/client.cpython-311.pyc new file mode 100644 index 0000000..6b935bc Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/client.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-311.pyc new file mode 100644 index 0000000..d002e3e Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/client_exceptions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-311.pyc new file mode 100644 index 0000000..9dab2d0 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/client_proto.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-311.pyc new file mode 100644 index 0000000..6be71d9 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/client_reqrep.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-311.pyc new file mode 100644 index 0000000..de32e73 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/client_ws.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-311.pyc new file mode 100644 index 0000000..409d13c Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/compression_utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/connector.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/connector.cpython-311.pyc new file mode 100644 index 0000000..e2c9708 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/connector.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-311.pyc new file mode 100644 index 0000000..ee194c8 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/cookiejar.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-311.pyc new file mode 100644 index 0000000..45ba008 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/formdata.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-311.pyc new file mode 100644 index 0000000..e8eae79 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/hdrs.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-311.pyc new file mode 100644 index 0000000..39d2e8b Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/helpers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/http.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/http.cpython-311.pyc new file mode 100644 index 0000000..856e51b Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/http.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-311.pyc new file mode 100644 index 0000000..eb26157 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/http_exceptions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-311.pyc new file mode 100644 index 0000000..9a745ec Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/http_parser.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-311.pyc new file mode 100644 index 0000000..9959e8d Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/http_websocket.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-311.pyc new file mode 100644 index 0000000..564bfb6 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/http_writer.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/locks.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/locks.cpython-311.pyc new file mode 100644 index 0000000..558c9ef Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/locks.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/log.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/log.cpython-311.pyc new file mode 100644 index 0000000..9b138a2 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/log.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-311.pyc new file mode 100644 index 0000000..9fc70c1 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/multipart.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/payload.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/payload.cpython-311.pyc new file mode 100644 index 0000000..8741237 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/payload.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-311.pyc new file mode 100644 index 0000000..46b5a9c Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/payload_streamer.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-311.pyc new file mode 100644 index 0000000..12e7519 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/pytest_plugin.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-311.pyc new file mode 100644 index 0000000..de270f3 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/resolver.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/streams.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/streams.cpython-311.pyc new file mode 100644 index 0000000..de98f47 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/streams.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-311.pyc new file mode 100644 index 0000000..036d399 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/tcp_helpers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-311.pyc new file mode 100644 index 0000000..3cb9417 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/test_utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-311.pyc new file mode 100644 index 0000000..6f045a3 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/tracing.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-311.pyc new file mode 100644 index 0000000..4a24b0a Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/typedefs.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web.cpython-311.pyc new file mode 100644 index 0000000..16e700a Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-311.pyc new file mode 100644 index 0000000..55acadb Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_app.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-311.pyc new file mode 100644 index 0000000..182ce67 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_exceptions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-311.pyc new file mode 100644 index 0000000..451899d Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_fileresponse.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-311.pyc new file mode 100644 index 0000000..0b6efa9 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_log.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-311.pyc new file mode 100644 index 0000000..9243f17 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_middlewares.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-311.pyc new file mode 100644 index 0000000..275ab37 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_protocol.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-311.pyc new file mode 100644 index 0000000..dbb23d0 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_request.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-311.pyc new file mode 100644 index 0000000..04c0c07 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_response.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-311.pyc new file mode 100644 index 0000000..f7ce753 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_routedef.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-311.pyc new file mode 100644 index 0000000..078b091 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_runner.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-311.pyc new file mode 100644 index 0000000..5672228 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_server.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-311.pyc new file mode 100644 index 0000000..b507947 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_urldispatcher.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-311.pyc new file mode 100644 index 0000000..8dfd646 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/web_ws.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/__pycache__/worker.cpython-311.pyc b/env/Lib/site-packages/aiohttp/__pycache__/worker.cpython-311.pyc new file mode 100644 index 0000000..5e058c9 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/__pycache__/worker.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiohttp/_cparser.pxd b/env/Lib/site-packages/aiohttp/_cparser.pxd new file mode 100644 index 0000000..c2cd5a9 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/_cparser.pxd @@ -0,0 +1,158 @@ +from libc.stdint cimport int32_t, uint8_t, uint16_t, uint64_t + + +cdef extern from "../vendor/llhttp/build/llhttp.h": + + struct llhttp__internal_s: + int32_t _index + void* _span_pos0 + void* _span_cb0 + int32_t error + const char* reason + const char* error_pos + void* data + void* _current + uint64_t content_length + uint8_t type + uint8_t method + uint8_t http_major + uint8_t http_minor + uint8_t header_state + uint8_t lenient_flags + uint8_t upgrade + uint8_t finish + uint16_t flags + uint16_t status_code + void* settings + + ctypedef llhttp__internal_s llhttp__internal_t + ctypedef llhttp__internal_t llhttp_t + + ctypedef int (*llhttp_data_cb)(llhttp_t*, const char *at, size_t length) except -1 + ctypedef int (*llhttp_cb)(llhttp_t*) except -1 + + struct llhttp_settings_s: + llhttp_cb on_message_begin + llhttp_data_cb on_url + llhttp_data_cb on_status + llhttp_data_cb on_header_field + llhttp_data_cb on_header_value + llhttp_cb on_headers_complete + llhttp_data_cb on_body + llhttp_cb on_message_complete + llhttp_cb on_chunk_header + llhttp_cb on_chunk_complete + + llhttp_cb on_url_complete + llhttp_cb on_status_complete + llhttp_cb on_header_field_complete + llhttp_cb on_header_value_complete + + ctypedef llhttp_settings_s llhttp_settings_t + + enum llhttp_errno: + HPE_OK, + HPE_INTERNAL, + HPE_STRICT, + HPE_LF_EXPECTED, + HPE_UNEXPECTED_CONTENT_LENGTH, + HPE_CLOSED_CONNECTION, + HPE_INVALID_METHOD, + HPE_INVALID_URL, + HPE_INVALID_CONSTANT, + HPE_INVALID_VERSION, + HPE_INVALID_HEADER_TOKEN, + HPE_INVALID_CONTENT_LENGTH, + HPE_INVALID_CHUNK_SIZE, + HPE_INVALID_STATUS, + HPE_INVALID_EOF_STATE, + HPE_INVALID_TRANSFER_ENCODING, + HPE_CB_MESSAGE_BEGIN, + HPE_CB_HEADERS_COMPLETE, + HPE_CB_MESSAGE_COMPLETE, + HPE_CB_CHUNK_HEADER, + HPE_CB_CHUNK_COMPLETE, + HPE_PAUSED, + HPE_PAUSED_UPGRADE, + HPE_USER + + ctypedef llhttp_errno llhttp_errno_t + + enum llhttp_flags: + F_CHUNKED, + F_CONTENT_LENGTH + + enum llhttp_type: + HTTP_REQUEST, + HTTP_RESPONSE, + HTTP_BOTH + + enum llhttp_method: + HTTP_DELETE, + HTTP_GET, + HTTP_HEAD, + HTTP_POST, + HTTP_PUT, + HTTP_CONNECT, + HTTP_OPTIONS, + HTTP_TRACE, + HTTP_COPY, + HTTP_LOCK, + HTTP_MKCOL, + HTTP_MOVE, + HTTP_PROPFIND, + HTTP_PROPPATCH, + HTTP_SEARCH, + HTTP_UNLOCK, + HTTP_BIND, + HTTP_REBIND, + HTTP_UNBIND, + HTTP_ACL, + HTTP_REPORT, + HTTP_MKACTIVITY, + HTTP_CHECKOUT, + HTTP_MERGE, + HTTP_MSEARCH, + HTTP_NOTIFY, + HTTP_SUBSCRIBE, + HTTP_UNSUBSCRIBE, + HTTP_PATCH, + HTTP_PURGE, + HTTP_MKCALENDAR, + HTTP_LINK, + HTTP_UNLINK, + HTTP_SOURCE, + HTTP_PRI, + HTTP_DESCRIBE, + HTTP_ANNOUNCE, + HTTP_SETUP, + HTTP_PLAY, + HTTP_PAUSE, + HTTP_TEARDOWN, + HTTP_GET_PARAMETER, + HTTP_SET_PARAMETER, + HTTP_REDIRECT, + HTTP_RECORD, + HTTP_FLUSH + + ctypedef llhttp_method llhttp_method_t; + + void llhttp_settings_init(llhttp_settings_t* settings) + void llhttp_init(llhttp_t* parser, llhttp_type type, + const llhttp_settings_t* settings) + + llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) + + int llhttp_should_keep_alive(const llhttp_t* parser) + + void llhttp_resume_after_upgrade(llhttp_t* parser) + + llhttp_errno_t llhttp_get_errno(const llhttp_t* parser) + const char* llhttp_get_error_reason(const llhttp_t* parser) + const char* llhttp_get_error_pos(const llhttp_t* parser) + + const char* llhttp_method_name(llhttp_method_t method) + + void llhttp_set_lenient_headers(llhttp_t* parser, int enabled) + void llhttp_set_lenient_optional_cr_before_lf(llhttp_t* parser, int enabled) + void llhttp_set_lenient_spaces_after_chunk_size(llhttp_t* parser, int enabled) diff --git a/env/Lib/site-packages/aiohttp/_find_header.pxd b/env/Lib/site-packages/aiohttp/_find_header.pxd new file mode 100644 index 0000000..37a6c37 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/_find_header.pxd @@ -0,0 +1,2 @@ +cdef extern from "_find_header.h": + int find_header(char *, int) diff --git a/env/Lib/site-packages/aiohttp/_headers.pxi b/env/Lib/site-packages/aiohttp/_headers.pxi new file mode 100644 index 0000000..3744721 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/_headers.pxi @@ -0,0 +1,83 @@ +# The file is autogenerated from aiohttp/hdrs.py +# Run ./tools/gen.py to update it after the origin changing. + +from . import hdrs +cdef tuple headers = ( + hdrs.ACCEPT, + hdrs.ACCEPT_CHARSET, + hdrs.ACCEPT_ENCODING, + hdrs.ACCEPT_LANGUAGE, + hdrs.ACCEPT_RANGES, + hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, + hdrs.ACCESS_CONTROL_ALLOW_HEADERS, + hdrs.ACCESS_CONTROL_ALLOW_METHODS, + hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, + hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, + hdrs.ACCESS_CONTROL_MAX_AGE, + hdrs.ACCESS_CONTROL_REQUEST_HEADERS, + hdrs.ACCESS_CONTROL_REQUEST_METHOD, + hdrs.AGE, + hdrs.ALLOW, + hdrs.AUTHORIZATION, + hdrs.CACHE_CONTROL, + hdrs.CONNECTION, + hdrs.CONTENT_DISPOSITION, + hdrs.CONTENT_ENCODING, + hdrs.CONTENT_LANGUAGE, + hdrs.CONTENT_LENGTH, + hdrs.CONTENT_LOCATION, + hdrs.CONTENT_MD5, + hdrs.CONTENT_RANGE, + hdrs.CONTENT_TRANSFER_ENCODING, + hdrs.CONTENT_TYPE, + hdrs.COOKIE, + hdrs.DATE, + hdrs.DESTINATION, + hdrs.DIGEST, + hdrs.ETAG, + hdrs.EXPECT, + hdrs.EXPIRES, + hdrs.FORWARDED, + hdrs.FROM, + hdrs.HOST, + hdrs.IF_MATCH, + hdrs.IF_MODIFIED_SINCE, + hdrs.IF_NONE_MATCH, + hdrs.IF_RANGE, + hdrs.IF_UNMODIFIED_SINCE, + hdrs.KEEP_ALIVE, + hdrs.LAST_EVENT_ID, + hdrs.LAST_MODIFIED, + hdrs.LINK, + hdrs.LOCATION, + hdrs.MAX_FORWARDS, + hdrs.ORIGIN, + hdrs.PRAGMA, + hdrs.PROXY_AUTHENTICATE, + hdrs.PROXY_AUTHORIZATION, + hdrs.RANGE, + hdrs.REFERER, + hdrs.RETRY_AFTER, + hdrs.SEC_WEBSOCKET_ACCEPT, + hdrs.SEC_WEBSOCKET_EXTENSIONS, + hdrs.SEC_WEBSOCKET_KEY, + hdrs.SEC_WEBSOCKET_KEY1, + hdrs.SEC_WEBSOCKET_PROTOCOL, + hdrs.SEC_WEBSOCKET_VERSION, + hdrs.SERVER, + hdrs.SET_COOKIE, + hdrs.TE, + hdrs.TRAILER, + hdrs.TRANSFER_ENCODING, + hdrs.URI, + hdrs.UPGRADE, + hdrs.USER_AGENT, + hdrs.VARY, + hdrs.VIA, + hdrs.WWW_AUTHENTICATE, + hdrs.WANT_DIGEST, + hdrs.WARNING, + hdrs.X_FORWARDED_FOR, + hdrs.X_FORWARDED_HOST, + hdrs.X_FORWARDED_PROTO, +) diff --git a/env/Lib/site-packages/aiohttp/_helpers.cp311-win_amd64.pyd b/env/Lib/site-packages/aiohttp/_helpers.cp311-win_amd64.pyd new file mode 100644 index 0000000..ed52ac2 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/_helpers.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/aiohttp/_helpers.pyi b/env/Lib/site-packages/aiohttp/_helpers.pyi new file mode 100644 index 0000000..1e35893 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/_helpers.pyi @@ -0,0 +1,6 @@ +from typing import Any + +class reify: + def __init__(self, wrapped: Any) -> None: ... + def __get__(self, inst: Any, owner: Any) -> Any: ... + def __set__(self, inst: Any, value: Any) -> None: ... diff --git a/env/Lib/site-packages/aiohttp/_helpers.pyx b/env/Lib/site-packages/aiohttp/_helpers.pyx new file mode 100644 index 0000000..665f367 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/_helpers.pyx @@ -0,0 +1,35 @@ +cdef class reify: + """Use as a class method decorator. It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + + """ + + cdef object wrapped + cdef object name + + def __init__(self, wrapped): + self.wrapped = wrapped + self.name = wrapped.__name__ + + @property + def __doc__(self): + return self.wrapped.__doc__ + + def __get__(self, inst, owner): + try: + try: + return inst._cache[self.name] + except KeyError: + val = self.wrapped(inst) + inst._cache[self.name] = val + return val + except AttributeError: + if inst is None: + return self + raise + + def __set__(self, inst, value): + raise AttributeError("reified property is read-only") diff --git a/env/Lib/site-packages/aiohttp/_http_parser.cp311-win_amd64.pyd b/env/Lib/site-packages/aiohttp/_http_parser.cp311-win_amd64.pyd new file mode 100644 index 0000000..a3143e2 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/_http_parser.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/aiohttp/_http_parser.pyx b/env/Lib/site-packages/aiohttp/_http_parser.pyx new file mode 100644 index 0000000..dd317ed --- /dev/null +++ b/env/Lib/site-packages/aiohttp/_http_parser.pyx @@ -0,0 +1,841 @@ +#cython: language_level=3 +# +# Based on https://github.com/MagicStack/httptools +# + +from cpython cimport ( + Py_buffer, + PyBUF_SIMPLE, + PyBuffer_Release, + PyBytes_AsString, + PyBytes_AsStringAndSize, + PyObject_GetBuffer, +) +from cpython.mem cimport PyMem_Free, PyMem_Malloc +from libc.limits cimport ULLONG_MAX +from libc.string cimport memcpy + +from multidict import CIMultiDict as _CIMultiDict, CIMultiDictProxy as _CIMultiDictProxy +from yarl import URL as _URL + +from aiohttp import hdrs +from aiohttp.helpers import DEBUG, set_exception + +from .http_exceptions import ( + BadHttpMessage, + BadStatusLine, + ContentLengthError, + InvalidHeader, + InvalidURLError, + LineTooLong, + PayloadEncodingError, + TransferEncodingError, +) +from .http_parser import DeflateBuffer as _DeflateBuffer +from .http_writer import ( + HttpVersion as _HttpVersion, + HttpVersion10 as _HttpVersion10, + HttpVersion11 as _HttpVersion11, +) +from .streams import EMPTY_PAYLOAD as _EMPTY_PAYLOAD, StreamReader as _StreamReader + +cimport cython + +from aiohttp cimport _cparser as cparser + +include "_headers.pxi" + +from aiohttp cimport _find_header + +ALLOWED_UPGRADES = frozenset({"websocket"}) +DEF DEFAULT_FREELIST_SIZE = 250 + +cdef extern from "Python.h": + int PyByteArray_Resize(object, Py_ssize_t) except -1 + Py_ssize_t PyByteArray_Size(object) except -1 + char* PyByteArray_AsString(object) + +__all__ = ('HttpRequestParser', 'HttpResponseParser', + 'RawRequestMessage', 'RawResponseMessage') + +cdef object URL = _URL +cdef object URL_build = URL.build +cdef object CIMultiDict = _CIMultiDict +cdef object CIMultiDictProxy = _CIMultiDictProxy +cdef object HttpVersion = _HttpVersion +cdef object HttpVersion10 = _HttpVersion10 +cdef object HttpVersion11 = _HttpVersion11 +cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1 +cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING +cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD +cdef object StreamReader = _StreamReader +cdef object DeflateBuffer = _DeflateBuffer + + +cdef inline object extend(object buf, const char* at, size_t length): + cdef Py_ssize_t s + cdef char* ptr + s = PyByteArray_Size(buf) + PyByteArray_Resize(buf, s + length) + ptr = PyByteArray_AsString(buf) + memcpy(ptr + s, at, length) + + +DEF METHODS_COUNT = 46; + +cdef list _http_method = [] + +for i in range(METHODS_COUNT): + _http_method.append( + cparser.llhttp_method_name( i).decode('ascii')) + + +cdef inline str http_method_str(int i): + if i < METHODS_COUNT: + return _http_method[i] + else: + return "" + +cdef inline object find_header(bytes raw_header): + cdef Py_ssize_t size + cdef char *buf + cdef int idx + PyBytes_AsStringAndSize(raw_header, &buf, &size) + idx = _find_header.find_header(buf, size) + if idx == -1: + return raw_header.decode('utf-8', 'surrogateescape') + return headers[idx] + + +@cython.freelist(DEFAULT_FREELIST_SIZE) +cdef class RawRequestMessage: + cdef readonly str method + cdef readonly str path + cdef readonly object version # HttpVersion + cdef readonly object headers # CIMultiDict + cdef readonly object raw_headers # tuple + cdef readonly object should_close + cdef readonly object compression + cdef readonly object upgrade + cdef readonly object chunked + cdef readonly object url # yarl.URL + + def __init__(self, method, path, version, headers, raw_headers, + should_close, compression, upgrade, chunked, url): + self.method = method + self.path = path + self.version = version + self.headers = headers + self.raw_headers = raw_headers + self.should_close = should_close + self.compression = compression + self.upgrade = upgrade + self.chunked = chunked + self.url = url + + def __repr__(self): + info = [] + info.append(("method", self.method)) + info.append(("path", self.path)) + info.append(("version", self.version)) + info.append(("headers", self.headers)) + info.append(("raw_headers", self.raw_headers)) + info.append(("should_close", self.should_close)) + info.append(("compression", self.compression)) + info.append(("upgrade", self.upgrade)) + info.append(("chunked", self.chunked)) + info.append(("url", self.url)) + sinfo = ', '.join(name + '=' + repr(val) for name, val in info) + return '' + + def _replace(self, **dct): + cdef RawRequestMessage ret + ret = _new_request_message(self.method, + self.path, + self.version, + self.headers, + self.raw_headers, + self.should_close, + self.compression, + self.upgrade, + self.chunked, + self.url) + if "method" in dct: + ret.method = dct["method"] + if "path" in dct: + ret.path = dct["path"] + if "version" in dct: + ret.version = dct["version"] + if "headers" in dct: + ret.headers = dct["headers"] + if "raw_headers" in dct: + ret.raw_headers = dct["raw_headers"] + if "should_close" in dct: + ret.should_close = dct["should_close"] + if "compression" in dct: + ret.compression = dct["compression"] + if "upgrade" in dct: + ret.upgrade = dct["upgrade"] + if "chunked" in dct: + ret.chunked = dct["chunked"] + if "url" in dct: + ret.url = dct["url"] + return ret + +cdef _new_request_message(str method, + str path, + object version, + object headers, + object raw_headers, + bint should_close, + object compression, + bint upgrade, + bint chunked, + object url): + cdef RawRequestMessage ret + ret = RawRequestMessage.__new__(RawRequestMessage) + ret.method = method + ret.path = path + ret.version = version + ret.headers = headers + ret.raw_headers = raw_headers + ret.should_close = should_close + ret.compression = compression + ret.upgrade = upgrade + ret.chunked = chunked + ret.url = url + return ret + + +@cython.freelist(DEFAULT_FREELIST_SIZE) +cdef class RawResponseMessage: + cdef readonly object version # HttpVersion + cdef readonly int code + cdef readonly str reason + cdef readonly object headers # CIMultiDict + cdef readonly object raw_headers # tuple + cdef readonly object should_close + cdef readonly object compression + cdef readonly object upgrade + cdef readonly object chunked + + def __init__(self, version, code, reason, headers, raw_headers, + should_close, compression, upgrade, chunked): + self.version = version + self.code = code + self.reason = reason + self.headers = headers + self.raw_headers = raw_headers + self.should_close = should_close + self.compression = compression + self.upgrade = upgrade + self.chunked = chunked + + def __repr__(self): + info = [] + info.append(("version", self.version)) + info.append(("code", self.code)) + info.append(("reason", self.reason)) + info.append(("headers", self.headers)) + info.append(("raw_headers", self.raw_headers)) + info.append(("should_close", self.should_close)) + info.append(("compression", self.compression)) + info.append(("upgrade", self.upgrade)) + info.append(("chunked", self.chunked)) + sinfo = ', '.join(name + '=' + repr(val) for name, val in info) + return '' + + +cdef _new_response_message(object version, + int code, + str reason, + object headers, + object raw_headers, + bint should_close, + object compression, + bint upgrade, + bint chunked): + cdef RawResponseMessage ret + ret = RawResponseMessage.__new__(RawResponseMessage) + ret.version = version + ret.code = code + ret.reason = reason + ret.headers = headers + ret.raw_headers = raw_headers + ret.should_close = should_close + ret.compression = compression + ret.upgrade = upgrade + ret.chunked = chunked + return ret + + +@cython.internal +cdef class HttpParser: + + cdef: + cparser.llhttp_t* _cparser + cparser.llhttp_settings_t* _csettings + + bytearray _raw_name + bytearray _raw_value + bint _has_value + + object _protocol + object _loop + object _timer + + size_t _max_line_size + size_t _max_field_size + size_t _max_headers + bint _response_with_body + bint _read_until_eof + + bint _started + object _url + bytearray _buf + str _path + str _reason + object _headers + list _raw_headers + bint _upgraded + list _messages + object _payload + bint _payload_error + object _payload_exception + object _last_error + bint _auto_decompress + int _limit + + str _content_encoding + + Py_buffer py_buf + + def __cinit__(self): + self._cparser = \ + PyMem_Malloc(sizeof(cparser.llhttp_t)) + if self._cparser is NULL: + raise MemoryError() + + self._csettings = \ + PyMem_Malloc(sizeof(cparser.llhttp_settings_t)) + if self._csettings is NULL: + raise MemoryError() + + def __dealloc__(self): + PyMem_Free(self._cparser) + PyMem_Free(self._csettings) + + cdef _init( + self, cparser.llhttp_type mode, + object protocol, object loop, int limit, + object timer=None, + size_t max_line_size=8190, size_t max_headers=32768, + size_t max_field_size=8190, payload_exception=None, + bint response_with_body=True, bint read_until_eof=False, + bint auto_decompress=True, + ): + cparser.llhttp_settings_init(self._csettings) + cparser.llhttp_init(self._cparser, mode, self._csettings) + self._cparser.data = self + self._cparser.content_length = 0 + + self._protocol = protocol + self._loop = loop + self._timer = timer + + self._buf = bytearray() + self._payload = None + self._payload_error = 0 + self._payload_exception = payload_exception + self._messages = [] + + self._raw_name = bytearray() + self._raw_value = bytearray() + self._has_value = False + + self._max_line_size = max_line_size + self._max_headers = max_headers + self._max_field_size = max_field_size + self._response_with_body = response_with_body + self._read_until_eof = read_until_eof + self._upgraded = False + self._auto_decompress = auto_decompress + self._content_encoding = None + + self._csettings.on_url = cb_on_url + self._csettings.on_status = cb_on_status + self._csettings.on_header_field = cb_on_header_field + self._csettings.on_header_value = cb_on_header_value + self._csettings.on_headers_complete = cb_on_headers_complete + self._csettings.on_body = cb_on_body + self._csettings.on_message_begin = cb_on_message_begin + self._csettings.on_message_complete = cb_on_message_complete + self._csettings.on_chunk_header = cb_on_chunk_header + self._csettings.on_chunk_complete = cb_on_chunk_complete + + self._last_error = None + self._limit = limit + + cdef _process_header(self): + if self._raw_name: + raw_name = bytes(self._raw_name) + raw_value = bytes(self._raw_value) + + name = find_header(raw_name) + value = raw_value.decode('utf-8', 'surrogateescape') + + self._headers.add(name, value) + + if name is CONTENT_ENCODING: + self._content_encoding = value + + PyByteArray_Resize(self._raw_name, 0) + PyByteArray_Resize(self._raw_value, 0) + self._has_value = False + self._raw_headers.append((raw_name, raw_value)) + + cdef _on_header_field(self, char* at, size_t length): + cdef Py_ssize_t size + cdef char *buf + if self._has_value: + self._process_header() + + size = PyByteArray_Size(self._raw_name) + PyByteArray_Resize(self._raw_name, size + length) + buf = PyByteArray_AsString(self._raw_name) + memcpy(buf + size, at, length) + + cdef _on_header_value(self, char* at, size_t length): + cdef Py_ssize_t size + cdef char *buf + + size = PyByteArray_Size(self._raw_value) + PyByteArray_Resize(self._raw_value, size + length) + buf = PyByteArray_AsString(self._raw_value) + memcpy(buf + size, at, length) + self._has_value = True + + cdef _on_headers_complete(self): + self._process_header() + + should_close = not cparser.llhttp_should_keep_alive(self._cparser) + upgrade = self._cparser.upgrade + chunked = self._cparser.flags & cparser.F_CHUNKED + + raw_headers = tuple(self._raw_headers) + headers = CIMultiDictProxy(self._headers) + + if self._cparser.type == cparser.HTTP_REQUEST: + allowed = upgrade and headers.get("upgrade", "").lower() in ALLOWED_UPGRADES + if allowed or self._cparser.method == cparser.HTTP_CONNECT: + self._upgraded = True + else: + if upgrade and self._cparser.status_code == 101: + self._upgraded = True + + # do not support old websocket spec + if SEC_WEBSOCKET_KEY1 in headers: + raise InvalidHeader(SEC_WEBSOCKET_KEY1) + + encoding = None + enc = self._content_encoding + if enc is not None: + self._content_encoding = None + enc = enc.lower() + if enc in ('gzip', 'deflate', 'br'): + encoding = enc + + if self._cparser.type == cparser.HTTP_REQUEST: + method = http_method_str(self._cparser.method) + msg = _new_request_message( + method, self._path, + self.http_version(), headers, raw_headers, + should_close, encoding, upgrade, chunked, self._url) + else: + msg = _new_response_message( + self.http_version(), self._cparser.status_code, self._reason, + headers, raw_headers, should_close, encoding, + upgrade, chunked) + + if ( + ULLONG_MAX > self._cparser.content_length > 0 or chunked or + self._cparser.method == cparser.HTTP_CONNECT or + (self._cparser.status_code >= 199 and + self._cparser.content_length == 0 and + self._read_until_eof) + ): + payload = StreamReader( + self._protocol, timer=self._timer, loop=self._loop, + limit=self._limit) + else: + payload = EMPTY_PAYLOAD + + self._payload = payload + if encoding is not None and self._auto_decompress: + self._payload = DeflateBuffer(payload, encoding) + + if not self._response_with_body: + payload = EMPTY_PAYLOAD + + self._messages.append((msg, payload)) + + cdef _on_message_complete(self): + self._payload.feed_eof() + self._payload = None + + cdef _on_chunk_header(self): + self._payload.begin_http_chunk_receiving() + + cdef _on_chunk_complete(self): + self._payload.end_http_chunk_receiving() + + cdef object _on_status_complete(self): + pass + + cdef inline http_version(self): + cdef cparser.llhttp_t* parser = self._cparser + + if parser.http_major == 1: + if parser.http_minor == 0: + return HttpVersion10 + elif parser.http_minor == 1: + return HttpVersion11 + + return HttpVersion(parser.http_major, parser.http_minor) + + ### Public API ### + + def feed_eof(self): + cdef bytes desc + + if self._payload is not None: + if self._cparser.flags & cparser.F_CHUNKED: + raise TransferEncodingError( + "Not enough data for satisfy transfer length header.") + elif self._cparser.flags & cparser.F_CONTENT_LENGTH: + raise ContentLengthError( + "Not enough data for satisfy content length header.") + elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK: + desc = cparser.llhttp_get_error_reason(self._cparser) + raise PayloadEncodingError(desc.decode('latin-1')) + else: + self._payload.feed_eof() + elif self._started: + self._on_headers_complete() + if self._messages: + return self._messages[-1][0] + + def feed_data(self, data): + cdef: + size_t data_len + size_t nb + cdef cparser.llhttp_errno_t errno + + PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) + data_len = self.py_buf.len + + errno = cparser.llhttp_execute( + self._cparser, + self.py_buf.buf, + data_len) + + if errno is cparser.HPE_PAUSED_UPGRADE: + cparser.llhttp_resume_after_upgrade(self._cparser) + + nb = cparser.llhttp_get_error_pos(self._cparser) - self.py_buf.buf + + PyBuffer_Release(&self.py_buf) + + if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): + if self._payload_error == 0: + if self._last_error is not None: + ex = self._last_error + self._last_error = None + else: + after = cparser.llhttp_get_error_pos(self._cparser) + before = data[:after - self.py_buf.buf] + after_b = after.split(b"\r\n", 1)[0] + before = before.rsplit(b"\r\n", 1)[-1] + data = before + after_b + pointer = " " * (len(repr(before))-1) + "^" + ex = parser_error_from_errno(self._cparser, data, pointer) + self._payload = None + raise ex + + if self._messages: + messages = self._messages + self._messages = [] + else: + messages = () + + if self._upgraded: + return messages, True, data[nb:] + else: + return messages, False, b"" + + def set_upgraded(self, val): + self._upgraded = val + + +cdef class HttpRequestParser(HttpParser): + + def __init__( + self, protocol, loop, int limit, timer=None, + size_t max_line_size=8190, size_t max_headers=32768, + size_t max_field_size=8190, payload_exception=None, + bint response_with_body=True, bint read_until_eof=False, + bint auto_decompress=True, + ): + self._init(cparser.HTTP_REQUEST, protocol, loop, limit, timer, + max_line_size, max_headers, max_field_size, + payload_exception, response_with_body, read_until_eof, + auto_decompress) + + cdef object _on_status_complete(self): + cdef int idx1, idx2 + if not self._buf: + return + self._path = self._buf.decode('utf-8', 'surrogateescape') + try: + idx3 = len(self._path) + if self._cparser.method == cparser.HTTP_CONNECT: + # authority-form, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3 + self._url = URL.build(authority=self._path, encoded=True) + elif idx3 > 1 and self._path[0] == '/': + # origin-form, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1 + idx1 = self._path.find("?") + if idx1 == -1: + query = "" + idx2 = self._path.find("#") + if idx2 == -1: + path = self._path + fragment = "" + else: + path = self._path[0: idx2] + fragment = self._path[idx2+1:] + + else: + path = self._path[0:idx1] + idx1 += 1 + idx2 = self._path.find("#", idx1+1) + if idx2 == -1: + query = self._path[idx1:] + fragment = "" + else: + query = self._path[idx1: idx2] + fragment = self._path[idx2+1:] + + self._url = URL.build( + path=path, + query_string=query, + fragment=fragment, + encoded=True, + ) + else: + # absolute-form for proxy maybe, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2 + self._url = URL(self._path, encoded=True) + finally: + PyByteArray_Resize(self._buf, 0) + + +cdef class HttpResponseParser(HttpParser): + + def __init__( + self, protocol, loop, int limit, timer=None, + size_t max_line_size=8190, size_t max_headers=32768, + size_t max_field_size=8190, payload_exception=None, + bint response_with_body=True, bint read_until_eof=False, + bint auto_decompress=True + ): + self._init(cparser.HTTP_RESPONSE, protocol, loop, limit, timer, + max_line_size, max_headers, max_field_size, + payload_exception, response_with_body, read_until_eof, + auto_decompress) + # Use strict parsing on dev mode, so users are warned about broken servers. + if not DEBUG: + cparser.llhttp_set_lenient_headers(self._cparser, 1) + cparser.llhttp_set_lenient_optional_cr_before_lf(self._cparser, 1) + cparser.llhttp_set_lenient_spaces_after_chunk_size(self._cparser, 1) + + cdef object _on_status_complete(self): + if self._buf: + self._reason = self._buf.decode('utf-8', 'surrogateescape') + PyByteArray_Resize(self._buf, 0) + else: + self._reason = self._reason or '' + +cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + + pyparser._started = True + pyparser._headers = CIMultiDict() + pyparser._raw_headers = [] + PyByteArray_Resize(pyparser._buf, 0) + pyparser._path = None + pyparser._reason = None + return 0 + + +cdef int cb_on_url(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + try: + if length > pyparser._max_line_size: + raise LineTooLong( + 'Status line is too long', pyparser._max_line_size, length) + extend(pyparser._buf, at, length) + except BaseException as ex: + pyparser._last_error = ex + return -1 + else: + return 0 + + +cdef int cb_on_status(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + cdef str reason + try: + if length > pyparser._max_line_size: + raise LineTooLong( + 'Status line is too long', pyparser._max_line_size, length) + extend(pyparser._buf, at, length) + except BaseException as ex: + pyparser._last_error = ex + return -1 + else: + return 0 + + +cdef int cb_on_header_field(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + cdef Py_ssize_t size + try: + pyparser._on_status_complete() + size = len(pyparser._raw_name) + length + if size > pyparser._max_field_size: + raise LineTooLong( + 'Header name is too long', pyparser._max_field_size, size) + pyparser._on_header_field(at, length) + except BaseException as ex: + pyparser._last_error = ex + return -1 + else: + return 0 + + +cdef int cb_on_header_value(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + cdef Py_ssize_t size + try: + size = len(pyparser._raw_value) + length + if size > pyparser._max_field_size: + raise LineTooLong( + 'Header value is too long', pyparser._max_field_size, size) + pyparser._on_header_value(at, length) + except BaseException as ex: + pyparser._last_error = ex + return -1 + else: + return 0 + + +cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + try: + pyparser._on_status_complete() + pyparser._on_headers_complete() + except BaseException as exc: + pyparser._last_error = exc + return -1 + else: + if pyparser._upgraded or pyparser._cparser.method == cparser.HTTP_CONNECT: + return 2 + else: + return 0 + + +cdef int cb_on_body(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + cdef bytes body = at[:length] + try: + pyparser._payload.feed_data(body, length) + except BaseException as underlying_exc: + reraised_exc = underlying_exc + if pyparser._payload_exception is not None: + reraised_exc = pyparser._payload_exception(str(underlying_exc)) + + set_exception(pyparser._payload, reraised_exc, underlying_exc) + + pyparser._payload_error = 1 + return -1 + else: + return 0 + + +cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + try: + pyparser._started = False + pyparser._on_message_complete() + except BaseException as exc: + pyparser._last_error = exc + return -1 + else: + return 0 + + +cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + try: + pyparser._on_chunk_header() + except BaseException as exc: + pyparser._last_error = exc + return -1 + else: + return 0 + + +cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + try: + pyparser._on_chunk_complete() + except BaseException as exc: + pyparser._last_error = exc + return -1 + else: + return 0 + + +cdef parser_error_from_errno(cparser.llhttp_t* parser, data, pointer): + cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser) + cdef bytes desc = cparser.llhttp_get_error_reason(parser) + + err_msg = "{}:\n\n {!r}\n {}".format(desc.decode("latin-1"), data, pointer) + + if errno in {cparser.HPE_CB_MESSAGE_BEGIN, + cparser.HPE_CB_HEADERS_COMPLETE, + cparser.HPE_CB_MESSAGE_COMPLETE, + cparser.HPE_CB_CHUNK_HEADER, + cparser.HPE_CB_CHUNK_COMPLETE, + cparser.HPE_INVALID_CONSTANT, + cparser.HPE_INVALID_HEADER_TOKEN, + cparser.HPE_INVALID_CONTENT_LENGTH, + cparser.HPE_INVALID_CHUNK_SIZE, + cparser.HPE_INVALID_EOF_STATE, + cparser.HPE_INVALID_TRANSFER_ENCODING}: + return BadHttpMessage(err_msg) + elif errno in {cparser.HPE_INVALID_STATUS, + cparser.HPE_INVALID_METHOD, + cparser.HPE_INVALID_VERSION}: + return BadStatusLine(error=err_msg) + elif errno == cparser.HPE_INVALID_URL: + return InvalidURLError(err_msg) + + return BadHttpMessage(err_msg) diff --git a/env/Lib/site-packages/aiohttp/_http_writer.cp311-win_amd64.pyd b/env/Lib/site-packages/aiohttp/_http_writer.cp311-win_amd64.pyd new file mode 100644 index 0000000..b38d534 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/_http_writer.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/aiohttp/_http_writer.pyx b/env/Lib/site-packages/aiohttp/_http_writer.pyx new file mode 100644 index 0000000..eff8521 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/_http_writer.pyx @@ -0,0 +1,163 @@ +from cpython.bytes cimport PyBytes_FromStringAndSize +from cpython.exc cimport PyErr_NoMemory +from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc +from cpython.object cimport PyObject_Str +from libc.stdint cimport uint8_t, uint64_t +from libc.string cimport memcpy + +from multidict import istr + +DEF BUF_SIZE = 16 * 1024 # 16KiB +cdef char BUFFER[BUF_SIZE] + +cdef object _istr = istr + + +# ----------------- writer --------------------------- + +cdef struct Writer: + char *buf + Py_ssize_t size + Py_ssize_t pos + + +cdef inline void _init_writer(Writer* writer): + writer.buf = &BUFFER[0] + writer.size = BUF_SIZE + writer.pos = 0 + + +cdef inline void _release_writer(Writer* writer): + if writer.buf != BUFFER: + PyMem_Free(writer.buf) + + +cdef inline int _write_byte(Writer* writer, uint8_t ch): + cdef char * buf + cdef Py_ssize_t size + + if writer.pos == writer.size: + # reallocate + size = writer.size + BUF_SIZE + if writer.buf == BUFFER: + buf = PyMem_Malloc(size) + if buf == NULL: + PyErr_NoMemory() + return -1 + memcpy(buf, writer.buf, writer.size) + else: + buf = PyMem_Realloc(writer.buf, size) + if buf == NULL: + PyErr_NoMemory() + return -1 + writer.buf = buf + writer.size = size + writer.buf[writer.pos] = ch + writer.pos += 1 + return 0 + + +cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): + cdef uint64_t utf = symbol + + if utf < 0x80: + return _write_byte(writer, utf) + elif utf < 0x800: + if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: + return -1 + return _write_byte(writer, (0x80 | (utf & 0x3f))) + elif 0xD800 <= utf <= 0xDFFF: + # surogate pair, ignored + return 0 + elif utf < 0x10000: + if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: + return -1 + if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: + return -1 + return _write_byte(writer, (0x80 | (utf & 0x3f))) + elif utf > 0x10FFFF: + # symbol is too large + return 0 + else: + if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: + return -1 + if _write_byte(writer, + (0x80 | ((utf >> 12) & 0x3f))) < 0: + return -1 + if _write_byte(writer, + (0x80 | ((utf >> 6) & 0x3f))) < 0: + return -1 + return _write_byte(writer, (0x80 | (utf & 0x3f))) + + +cdef inline int _write_str(Writer* writer, str s): + cdef Py_UCS4 ch + for ch in s: + if _write_utf8(writer, ch) < 0: + return -1 + + +# --------------- _serialize_headers ---------------------- + +cdef str to_str(object s): + typ = type(s) + if typ is str: + return s + elif typ is _istr: + return PyObject_Str(s) + elif not isinstance(s, str): + raise TypeError("Cannot serialize non-str key {!r}".format(s)) + else: + return str(s) + + +cdef void _safe_header(str string) except *: + if "\r" in string or "\n" in string: + raise ValueError( + "Newline or carriage return character detected in HTTP status message or " + "header. This is a potential security issue." + ) + + +def _serialize_headers(str status_line, headers): + cdef Writer writer + cdef object key + cdef object val + cdef bytes ret + + _init_writer(&writer) + + for key, val in headers.items(): + _safe_header(to_str(key)) + _safe_header(to_str(val)) + + try: + if _write_str(&writer, status_line) < 0: + raise + if _write_byte(&writer, b'\r') < 0: + raise + if _write_byte(&writer, b'\n') < 0: + raise + + for key, val in headers.items(): + if _write_str(&writer, to_str(key)) < 0: + raise + if _write_byte(&writer, b':') < 0: + raise + if _write_byte(&writer, b' ') < 0: + raise + if _write_str(&writer, to_str(val)) < 0: + raise + if _write_byte(&writer, b'\r') < 0: + raise + if _write_byte(&writer, b'\n') < 0: + raise + + if _write_byte(&writer, b'\r') < 0: + raise + if _write_byte(&writer, b'\n') < 0: + raise + + return PyBytes_FromStringAndSize(writer.buf, writer.pos) + finally: + _release_writer(&writer) diff --git a/env/Lib/site-packages/aiohttp/_websocket.cp311-win_amd64.pyd b/env/Lib/site-packages/aiohttp/_websocket.cp311-win_amd64.pyd new file mode 100644 index 0000000..011cfd9 Binary files /dev/null and b/env/Lib/site-packages/aiohttp/_websocket.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/aiohttp/_websocket.pyx b/env/Lib/site-packages/aiohttp/_websocket.pyx new file mode 100644 index 0000000..94318d2 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/_websocket.pyx @@ -0,0 +1,56 @@ +from cpython cimport PyBytes_AsString + + +#from cpython cimport PyByteArray_AsString # cython still not exports that +cdef extern from "Python.h": + char* PyByteArray_AsString(bytearray ba) except NULL + +from libc.stdint cimport uint32_t, uint64_t, uintmax_t + + +def _websocket_mask_cython(object mask, object data): + """Note, this function mutates its `data` argument + """ + cdef: + Py_ssize_t data_len, i + # bit operations on signed integers are implementation-specific + unsigned char * in_buf + const unsigned char * mask_buf + uint32_t uint32_msk + uint64_t uint64_msk + + assert len(mask) == 4 + + if not isinstance(mask, bytes): + mask = bytes(mask) + + if isinstance(data, bytearray): + data = data + else: + data = bytearray(data) + + data_len = len(data) + in_buf = PyByteArray_AsString(data) + mask_buf = PyBytes_AsString(mask) + uint32_msk = (mask_buf)[0] + + # TODO: align in_data ptr to achieve even faster speeds + # does it need in python ?! malloc() always aligns to sizeof(long) bytes + + if sizeof(size_t) >= 8: + uint64_msk = uint32_msk + uint64_msk = (uint64_msk << 32) | uint32_msk + + while data_len >= 8: + (in_buf)[0] ^= uint64_msk + in_buf += 8 + data_len -= 8 + + + while data_len >= 4: + (in_buf)[0] ^= uint32_msk + in_buf += 4 + data_len -= 4 + + for i in range(0, data_len): + in_buf[i] ^= mask_buf[i] diff --git a/env/Lib/site-packages/aiohttp/abc.py b/env/Lib/site-packages/aiohttp/abc.py new file mode 100644 index 0000000..3fb0240 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/abc.py @@ -0,0 +1,234 @@ +import asyncio +import logging +import socket +from abc import ABC, abstractmethod +from collections.abc import Sized +from http.cookies import BaseCookie, Morsel +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Dict, + Generator, + Iterable, + List, + Optional, + Tuple, + TypedDict, +) + +from multidict import CIMultiDict +from yarl import URL + +from .typedefs import LooseCookies + +if TYPE_CHECKING: + from .web_app import Application + from .web_exceptions import HTTPException + from .web_request import BaseRequest, Request + from .web_response import StreamResponse +else: + BaseRequest = Request = Application = StreamResponse = None + HTTPException = None + + +class AbstractRouter(ABC): + def __init__(self) -> None: + self._frozen = False + + def post_init(self, app: Application) -> None: + """Post init stage. + + Not an abstract method for sake of backward compatibility, + but if the router wants to be aware of the application + it can override this. + """ + + @property + def frozen(self) -> bool: + return self._frozen + + def freeze(self) -> None: + """Freeze router.""" + self._frozen = True + + @abstractmethod + async def resolve(self, request: Request) -> "AbstractMatchInfo": + """Return MATCH_INFO for given request""" + + +class AbstractMatchInfo(ABC): + @property # pragma: no branch + @abstractmethod + def handler(self) -> Callable[[Request], Awaitable[StreamResponse]]: + """Execute matched request handler""" + + @property + @abstractmethod + def expect_handler( + self, + ) -> Callable[[Request], Awaitable[Optional[StreamResponse]]]: + """Expect handler for 100-continue processing""" + + @property # pragma: no branch + @abstractmethod + def http_exception(self) -> Optional[HTTPException]: + """HTTPException instance raised on router's resolving, or None""" + + @abstractmethod # pragma: no branch + def get_info(self) -> Dict[str, Any]: + """Return a dict with additional info useful for introspection""" + + @property # pragma: no branch + @abstractmethod + def apps(self) -> Tuple[Application, ...]: + """Stack of nested applications. + + Top level application is left-most element. + + """ + + @abstractmethod + def add_app(self, app: Application) -> None: + """Add application to the nested apps stack.""" + + @abstractmethod + def freeze(self) -> None: + """Freeze the match info. + + The method is called after route resolution. + + After the call .add_app() is forbidden. + + """ + + +class AbstractView(ABC): + """Abstract class based view.""" + + def __init__(self, request: Request) -> None: + self._request = request + + @property + def request(self) -> Request: + """Request instance.""" + return self._request + + @abstractmethod + def __await__(self) -> Generator[Any, None, StreamResponse]: + """Execute the view handler.""" + + +class ResolveResult(TypedDict): + """Resolve result. + + This is the result returned from an AbstractResolver's + resolve method. + + :param hostname: The hostname that was provided. + :param host: The IP address that was resolved. + :param port: The port that was resolved. + :param family: The address family that was resolved. + :param proto: The protocol that was resolved. + :param flags: The flags that were resolved. + """ + + hostname: str + host: str + port: int + family: int + proto: int + flags: int + + +class AbstractResolver(ABC): + """Abstract DNS resolver.""" + + @abstractmethod + async def resolve( + self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET + ) -> List[ResolveResult]: + """Return IP address for given hostname""" + + @abstractmethod + async def close(self) -> None: + """Release resolver""" + + +if TYPE_CHECKING: + IterableBase = Iterable[Morsel[str]] +else: + IterableBase = Iterable + + +ClearCookiePredicate = Callable[["Morsel[str]"], bool] + + +class AbstractCookieJar(Sized, IterableBase): + """Abstract Cookie Jar.""" + + def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: + self._loop = loop or asyncio.get_running_loop() + + @abstractmethod + def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: + """Clear all cookies if no predicate is passed.""" + + @abstractmethod + def clear_domain(self, domain: str) -> None: + """Clear all cookies for domain and all subdomains.""" + + @abstractmethod + def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: + """Update cookies.""" + + @abstractmethod + def filter_cookies(self, request_url: URL) -> "BaseCookie[str]": + """Return the jar's cookies filtered by their attributes.""" + + +class AbstractStreamWriter(ABC): + """Abstract stream writer.""" + + buffer_size = 0 + output_size = 0 + length: Optional[int] = 0 + + @abstractmethod + async def write(self, chunk: bytes) -> None: + """Write chunk into stream.""" + + @abstractmethod + async def write_eof(self, chunk: bytes = b"") -> None: + """Write last chunk.""" + + @abstractmethod + async def drain(self) -> None: + """Flush the write buffer.""" + + @abstractmethod + def enable_compression(self, encoding: str = "deflate") -> None: + """Enable HTTP body compression""" + + @abstractmethod + def enable_chunking(self) -> None: + """Enable HTTP chunked mode""" + + @abstractmethod + async def write_headers( + self, status_line: str, headers: "CIMultiDict[str]" + ) -> None: + """Write HTTP headers""" + + +class AbstractAccessLogger(ABC): + """Abstract writer to access log.""" + + def __init__(self, logger: logging.Logger, log_format: str) -> None: + self.logger = logger + self.log_format = log_format + + @abstractmethod + def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None: + """Emit log to logger.""" diff --git a/env/Lib/site-packages/aiohttp/base_protocol.py b/env/Lib/site-packages/aiohttp/base_protocol.py new file mode 100644 index 0000000..dc1f24f --- /dev/null +++ b/env/Lib/site-packages/aiohttp/base_protocol.py @@ -0,0 +1,95 @@ +import asyncio +from typing import Optional, cast + +from .helpers import set_exception +from .tcp_helpers import tcp_nodelay + + +class BaseProtocol(asyncio.Protocol): + __slots__ = ( + "_loop", + "_paused", + "_drain_waiter", + "_connection_lost", + "_reading_paused", + "transport", + ) + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop: asyncio.AbstractEventLoop = loop + self._paused = False + self._drain_waiter: Optional[asyncio.Future[None]] = None + self._reading_paused = False + + self.transport: Optional[asyncio.Transport] = None + + @property + def connected(self) -> bool: + """Return True if the connection is open.""" + return self.transport is not None + + def pause_writing(self) -> None: + assert not self._paused + self._paused = True + + def resume_writing(self) -> None: + assert self._paused + self._paused = False + + waiter = self._drain_waiter + if waiter is not None: + self._drain_waiter = None + if not waiter.done(): + waiter.set_result(None) + + def pause_reading(self) -> None: + if not self._reading_paused and self.transport is not None: + try: + self.transport.pause_reading() + except (AttributeError, NotImplementedError, RuntimeError): + pass + self._reading_paused = True + + def resume_reading(self) -> None: + if self._reading_paused and self.transport is not None: + try: + self.transport.resume_reading() + except (AttributeError, NotImplementedError, RuntimeError): + pass + self._reading_paused = False + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + tr = cast(asyncio.Transport, transport) + tcp_nodelay(tr, True) + self.transport = tr + + def connection_lost(self, exc: Optional[BaseException]) -> None: + # Wake up the writer if currently paused. + self.transport = None + if not self._paused: + return + waiter = self._drain_waiter + if waiter is None: + return + self._drain_waiter = None + if waiter.done(): + return + if exc is None: + waiter.set_result(None) + else: + set_exception( + waiter, + ConnectionError("Connection lost"), + exc, + ) + + async def _drain_helper(self) -> None: + if not self.connected: + raise ConnectionResetError("Connection lost") + if not self._paused: + return + waiter = self._drain_waiter + if waiter is None: + waiter = self._loop.create_future() + self._drain_waiter = waiter + await asyncio.shield(waiter) diff --git a/env/Lib/site-packages/aiohttp/client.py b/env/Lib/site-packages/aiohttp/client.py new file mode 100644 index 0000000..3d1045f --- /dev/null +++ b/env/Lib/site-packages/aiohttp/client.py @@ -0,0 +1,1522 @@ +"""HTTP Client for asyncio.""" + +import asyncio +import base64 +import hashlib +import json +import os +import sys +import traceback +import warnings +from contextlib import suppress +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Coroutine, + Final, + FrozenSet, + Generator, + Generic, + Iterable, + List, + Mapping, + Optional, + Set, + Tuple, + Type, + TypedDict, + TypeVar, + Union, +) + +import attr +from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr +from yarl import URL + +from . import hdrs, http, payload +from .abc import AbstractCookieJar +from .client_exceptions import ( + ClientConnectionError, + ClientConnectorCertificateError, + ClientConnectorError, + ClientConnectorSSLError, + ClientError, + ClientHttpProxyError, + ClientOSError, + ClientPayloadError, + ClientProxyConnectionError, + ClientResponseError, + ClientSSLError, + ConnectionTimeoutError, + ContentTypeError, + InvalidURL, + InvalidUrlClientError, + InvalidUrlRedirectClientError, + NonHttpUrlClientError, + NonHttpUrlRedirectClientError, + RedirectClientError, + ServerConnectionError, + ServerDisconnectedError, + ServerFingerprintMismatch, + ServerTimeoutError, + SocketTimeoutError, + TooManyRedirects, + WSServerHandshakeError, +) +from .client_reqrep import ( + ClientRequest as ClientRequest, + ClientResponse as ClientResponse, + Fingerprint as Fingerprint, + RequestInfo as RequestInfo, + _merge_ssl_params, +) +from .client_ws import ClientWebSocketResponse as ClientWebSocketResponse +from .connector import ( + HTTP_AND_EMPTY_SCHEMA_SET, + BaseConnector as BaseConnector, + NamedPipeConnector as NamedPipeConnector, + TCPConnector as TCPConnector, + UnixConnector as UnixConnector, +) +from .cookiejar import CookieJar +from .helpers import ( + _SENTINEL, + DEBUG, + BasicAuth, + TimeoutHandle, + ceil_timeout, + get_env_proxy_for_url, + method_must_be_empty_body, + sentinel, + strip_auth_from_url, +) +from .http import WS_KEY, HttpVersion, WebSocketReader, WebSocketWriter +from .http_websocket import WSHandshakeError, WSMessage, ws_ext_gen, ws_ext_parse +from .streams import FlowControlDataQueue +from .tracing import Trace, TraceConfig +from .typedefs import JSONEncoder, LooseCookies, LooseHeaders, StrOrURL + +__all__ = ( + # client_exceptions + "ClientConnectionError", + "ClientConnectorCertificateError", + "ClientConnectorError", + "ClientConnectorSSLError", + "ClientError", + "ClientHttpProxyError", + "ClientOSError", + "ClientPayloadError", + "ClientProxyConnectionError", + "ClientResponseError", + "ClientSSLError", + "ConnectionTimeoutError", + "ContentTypeError", + "InvalidURL", + "InvalidUrlClientError", + "RedirectClientError", + "NonHttpUrlClientError", + "InvalidUrlRedirectClientError", + "NonHttpUrlRedirectClientError", + "ServerConnectionError", + "ServerDisconnectedError", + "ServerFingerprintMismatch", + "ServerTimeoutError", + "SocketTimeoutError", + "TooManyRedirects", + "WSServerHandshakeError", + # client_reqrep + "ClientRequest", + "ClientResponse", + "Fingerprint", + "RequestInfo", + # connector + "BaseConnector", + "TCPConnector", + "UnixConnector", + "NamedPipeConnector", + # client_ws + "ClientWebSocketResponse", + # client + "ClientSession", + "ClientTimeout", + "request", +) + + +if TYPE_CHECKING: + from ssl import SSLContext +else: + SSLContext = None + +if sys.version_info >= (3, 11) and TYPE_CHECKING: + from typing import Unpack + + +class _RequestOptions(TypedDict, total=False): + params: Union[Mapping[str, Union[str, int]], str, None] + data: Any + json: Any + cookies: Union[LooseCookies, None] + headers: Union[LooseHeaders, None] + skip_auto_headers: Union[Iterable[str], None] + auth: Union[BasicAuth, None] + allow_redirects: bool + max_redirects: int + compress: Union[str, None] + chunked: Union[bool, None] + expect100: bool + raise_for_status: Union[None, bool, Callable[[ClientResponse], Awaitable[None]]] + read_until_eof: bool + proxy: Union[StrOrURL, None] + proxy_auth: Union[BasicAuth, None] + timeout: "Union[ClientTimeout, _SENTINEL, None]" + ssl: Union[SSLContext, bool, Fingerprint] + server_hostname: Union[str, None] + proxy_headers: Union[LooseHeaders, None] + trace_request_ctx: Union[Mapping[str, str], None] + read_bufsize: Union[int, None] + auto_decompress: Union[bool, None] + max_line_size: Union[int, None] + max_field_size: Union[int, None] + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class ClientTimeout: + total: Optional[float] = None + connect: Optional[float] = None + sock_read: Optional[float] = None + sock_connect: Optional[float] = None + ceil_threshold: float = 5 + + # pool_queue_timeout: Optional[float] = None + # dns_resolution_timeout: Optional[float] = None + # socket_connect_timeout: Optional[float] = None + # connection_acquiring_timeout: Optional[float] = None + # new_connection_timeout: Optional[float] = None + # http_header_timeout: Optional[float] = None + # response_body_timeout: Optional[float] = None + + # to create a timeout specific for a single request, either + # - create a completely new one to overwrite the default + # - or use http://www.attrs.org/en/stable/api.html#attr.evolve + # to overwrite the defaults + + +# 5 Minute default read timeout +DEFAULT_TIMEOUT: Final[ClientTimeout] = ClientTimeout(total=5 * 60) + +# https://www.rfc-editor.org/rfc/rfc9110#section-9.2.2 +IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE", "PUT", "DELETE"}) + +_RetType = TypeVar("_RetType") +_CharsetResolver = Callable[[ClientResponse, bytes], str] + + +class ClientSession: + """First-class interface for making HTTP requests.""" + + ATTRS = frozenset( + [ + "_base_url", + "_source_traceback", + "_connector", + "requote_redirect_url", + "_loop", + "_cookie_jar", + "_connector_owner", + "_default_auth", + "_version", + "_json_serialize", + "_requote_redirect_url", + "_timeout", + "_raise_for_status", + "_auto_decompress", + "_trust_env", + "_default_headers", + "_skip_auto_headers", + "_request_class", + "_response_class", + "_ws_response_class", + "_trace_configs", + "_read_bufsize", + "_max_line_size", + "_max_field_size", + "_resolve_charset", + ] + ) + + _source_traceback: Optional[traceback.StackSummary] = None + _connector: Optional[BaseConnector] = None + + def __init__( + self, + base_url: Optional[StrOrURL] = None, + *, + connector: Optional[BaseConnector] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + cookies: Optional[LooseCookies] = None, + headers: Optional[LooseHeaders] = None, + skip_auto_headers: Optional[Iterable[str]] = None, + auth: Optional[BasicAuth] = None, + json_serialize: JSONEncoder = json.dumps, + request_class: Type[ClientRequest] = ClientRequest, + response_class: Type[ClientResponse] = ClientResponse, + ws_response_class: Type[ClientWebSocketResponse] = ClientWebSocketResponse, + version: HttpVersion = http.HttpVersion11, + cookie_jar: Optional[AbstractCookieJar] = None, + connector_owner: bool = True, + raise_for_status: Union[ + bool, Callable[[ClientResponse], Awaitable[None]] + ] = False, + read_timeout: Union[float, _SENTINEL] = sentinel, + conn_timeout: Optional[float] = None, + timeout: Union[object, ClientTimeout] = sentinel, + auto_decompress: bool = True, + trust_env: bool = False, + requote_redirect_url: bool = True, + trace_configs: Optional[List[TraceConfig]] = None, + read_bufsize: int = 2**16, + max_line_size: int = 8190, + max_field_size: int = 8190, + fallback_charset_resolver: _CharsetResolver = lambda r, b: "utf-8", + ) -> None: + # We initialise _connector to None immediately, as it's referenced in __del__() + # and could cause issues if an exception occurs during initialisation. + self._connector: Optional[BaseConnector] = None + + if loop is None: + if connector is not None: + loop = connector._loop + + loop = loop or asyncio.get_running_loop() + + if base_url is None or isinstance(base_url, URL): + self._base_url: Optional[URL] = base_url + else: + self._base_url = URL(base_url) + assert ( + self._base_url.origin() == self._base_url + ), "Only absolute URLs without path part are supported" + + if timeout is sentinel or timeout is None: + self._timeout = DEFAULT_TIMEOUT + if read_timeout is not sentinel: + warnings.warn( + "read_timeout is deprecated, " "use timeout argument instead", + DeprecationWarning, + stacklevel=2, + ) + self._timeout = attr.evolve(self._timeout, total=read_timeout) + if conn_timeout is not None: + self._timeout = attr.evolve(self._timeout, connect=conn_timeout) + warnings.warn( + "conn_timeout is deprecated, " "use timeout argument instead", + DeprecationWarning, + stacklevel=2, + ) + else: + if not isinstance(timeout, ClientTimeout): + raise ValueError( + f"timeout parameter cannot be of {type(timeout)} type, " + "please use 'timeout=ClientTimeout(...)'", + ) + self._timeout = timeout + if read_timeout is not sentinel: + raise ValueError( + "read_timeout and timeout parameters " + "conflict, please setup " + "timeout.read" + ) + if conn_timeout is not None: + raise ValueError( + "conn_timeout and timeout parameters " + "conflict, please setup " + "timeout.connect" + ) + + if connector is None: + connector = TCPConnector(loop=loop) + + if connector._loop is not loop: + raise RuntimeError("Session and connector has to use same event loop") + + self._loop = loop + + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + if cookie_jar is None: + cookie_jar = CookieJar(loop=loop) + self._cookie_jar = cookie_jar + + if cookies is not None: + self._cookie_jar.update_cookies(cookies) + + self._connector = connector + self._connector_owner = connector_owner + self._default_auth = auth + self._version = version + self._json_serialize = json_serialize + self._raise_for_status = raise_for_status + self._auto_decompress = auto_decompress + self._trust_env = trust_env + self._requote_redirect_url = requote_redirect_url + self._read_bufsize = read_bufsize + self._max_line_size = max_line_size + self._max_field_size = max_field_size + + # Convert to list of tuples + if headers: + real_headers: CIMultiDict[str] = CIMultiDict(headers) + else: + real_headers = CIMultiDict() + self._default_headers: CIMultiDict[str] = real_headers + if skip_auto_headers is not None: + self._skip_auto_headers = frozenset(istr(i) for i in skip_auto_headers) + else: + self._skip_auto_headers = frozenset() + + self._request_class = request_class + self._response_class = response_class + self._ws_response_class = ws_response_class + + self._trace_configs = trace_configs or [] + for trace_config in self._trace_configs: + trace_config.freeze() + + self._resolve_charset = fallback_charset_resolver + + def __init_subclass__(cls: Type["ClientSession"]) -> None: + warnings.warn( + "Inheritance class {} from ClientSession " + "is discouraged".format(cls.__name__), + DeprecationWarning, + stacklevel=2, + ) + + if DEBUG: + + def __setattr__(self, name: str, val: Any) -> None: + if name not in self.ATTRS: + warnings.warn( + "Setting custom ClientSession.{} attribute " + "is discouraged".format(name), + DeprecationWarning, + stacklevel=2, + ) + super().__setattr__(name, val) + + def __del__(self, _warnings: Any = warnings) -> None: + if not self.closed: + kwargs = {"source": self} + _warnings.warn( + f"Unclosed client session {self!r}", ResourceWarning, **kwargs + ) + context = {"client_session": self, "message": "Unclosed client session"} + if self._source_traceback is not None: + context["source_traceback"] = self._source_traceback + self._loop.call_exception_handler(context) + + if sys.version_info >= (3, 11) and TYPE_CHECKING: + + def request( + self, + method: str, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + else: + + def request( + self, method: str, url: StrOrURL, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP request.""" + return _RequestContextManager(self._request(method, url, **kwargs)) + + def _build_url(self, str_or_url: StrOrURL) -> URL: + url = URL(str_or_url) + if self._base_url is None: + return url + else: + assert not url.is_absolute() and url.path.startswith("/") + return self._base_url.join(url) + + async def _request( + self, + method: str, + str_or_url: StrOrURL, + *, + params: Optional[Mapping[str, str]] = None, + data: Any = None, + json: Any = None, + cookies: Optional[LooseCookies] = None, + headers: Optional[LooseHeaders] = None, + skip_auto_headers: Optional[Iterable[str]] = None, + auth: Optional[BasicAuth] = None, + allow_redirects: bool = True, + max_redirects: int = 10, + compress: Optional[str] = None, + chunked: Optional[bool] = None, + expect100: bool = False, + raise_for_status: Union[ + None, bool, Callable[[ClientResponse], Awaitable[None]] + ] = None, + read_until_eof: bool = True, + proxy: Optional[StrOrURL] = None, + proxy_auth: Optional[BasicAuth] = None, + timeout: Union[ClientTimeout, _SENTINEL] = sentinel, + verify_ssl: Optional[bool] = None, + fingerprint: Optional[bytes] = None, + ssl_context: Optional[SSLContext] = None, + ssl: Union[SSLContext, bool, Fingerprint] = True, + server_hostname: Optional[str] = None, + proxy_headers: Optional[LooseHeaders] = None, + trace_request_ctx: Optional[Mapping[str, str]] = None, + read_bufsize: Optional[int] = None, + auto_decompress: Optional[bool] = None, + max_line_size: Optional[int] = None, + max_field_size: Optional[int] = None, + ) -> ClientResponse: + + # NOTE: timeout clamps existing connect and read timeouts. We cannot + # set the default to None because we need to detect if the user wants + # to use the existing timeouts by setting timeout to None. + + if self.closed: + raise RuntimeError("Session is closed") + + ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) + + if data is not None and json is not None: + raise ValueError( + "data and json parameters can not be used at the same time" + ) + elif json is not None: + data = payload.JsonPayload(json, dumps=self._json_serialize) + + if not isinstance(chunked, bool) and chunked is not None: + warnings.warn("Chunk size is deprecated #1615", DeprecationWarning) + + redirects = 0 + history = [] + version = self._version + params = params or {} + + # Merge with default headers and transform to CIMultiDict + headers = self._prepare_headers(headers) + proxy_headers = self._prepare_headers(proxy_headers) + + try: + url = self._build_url(str_or_url) + except ValueError as e: + raise InvalidUrlClientError(str_or_url) from e + + assert self._connector is not None + if url.scheme not in self._connector.allowed_protocol_schema_set: + raise NonHttpUrlClientError(url) + + skip_headers = set(self._skip_auto_headers) + if skip_auto_headers is not None: + for i in skip_auto_headers: + skip_headers.add(istr(i)) + + if proxy is not None: + try: + proxy = URL(proxy) + except ValueError as e: + raise InvalidURL(proxy) from e + + if timeout is sentinel: + real_timeout: ClientTimeout = self._timeout + else: + if not isinstance(timeout, ClientTimeout): + real_timeout = ClientTimeout(total=timeout) + else: + real_timeout = timeout + # timeout is cumulative for all request operations + # (request, redirects, responses, data consuming) + tm = TimeoutHandle( + self._loop, real_timeout.total, ceil_threshold=real_timeout.ceil_threshold + ) + handle = tm.start() + + if read_bufsize is None: + read_bufsize = self._read_bufsize + + if auto_decompress is None: + auto_decompress = self._auto_decompress + + if max_line_size is None: + max_line_size = self._max_line_size + + if max_field_size is None: + max_field_size = self._max_field_size + + traces = [ + Trace( + self, + trace_config, + trace_config.trace_config_ctx(trace_request_ctx=trace_request_ctx), + ) + for trace_config in self._trace_configs + ] + + for trace in traces: + await trace.send_request_start(method, url.update_query(params), headers) + + timer = tm.timer() + try: + with timer: + # https://www.rfc-editor.org/rfc/rfc9112.html#name-retrying-requests + retry_persistent_connection = method in IDEMPOTENT_METHODS + while True: + url, auth_from_url = strip_auth_from_url(url) + if not url.raw_host: + # NOTE: Bail early, otherwise, causes `InvalidURL` through + # NOTE: `self._request_class()` below. + err_exc_cls = ( + InvalidUrlRedirectClientError + if redirects + else InvalidUrlClientError + ) + raise err_exc_cls(url) + if auth and auth_from_url: + raise ValueError( + "Cannot combine AUTH argument with " + "credentials encoded in URL" + ) + + if auth is None: + auth = auth_from_url + if auth is None: + auth = self._default_auth + # It would be confusing if we support explicit + # Authorization header with auth argument + if ( + headers is not None + and auth is not None + and hdrs.AUTHORIZATION in headers + ): + raise ValueError( + "Cannot combine AUTHORIZATION header " + "with AUTH argument or credentials " + "encoded in URL" + ) + + all_cookies = self._cookie_jar.filter_cookies(url) + + if cookies is not None: + tmp_cookie_jar = CookieJar() + tmp_cookie_jar.update_cookies(cookies) + req_cookies = tmp_cookie_jar.filter_cookies(url) + if req_cookies: + all_cookies.load(req_cookies) + + if proxy is not None: + proxy = URL(proxy) + elif self._trust_env: + with suppress(LookupError): + proxy, proxy_auth = get_env_proxy_for_url(url) + + req = self._request_class( + method, + url, + params=params, + headers=headers, + skip_auto_headers=skip_headers, + data=data, + cookies=all_cookies, + auth=auth, + version=version, + compress=compress, + chunked=chunked, + expect100=expect100, + loop=self._loop, + response_class=self._response_class, + proxy=proxy, + proxy_auth=proxy_auth, + timer=timer, + session=self, + ssl=ssl if ssl is not None else True, + server_hostname=server_hostname, + proxy_headers=proxy_headers, + traces=traces, + trust_env=self.trust_env, + ) + + # connection timeout + try: + async with ceil_timeout( + real_timeout.connect, + ceil_threshold=real_timeout.ceil_threshold, + ): + conn = await self._connector.connect( + req, traces=traces, timeout=real_timeout + ) + except asyncio.TimeoutError as exc: + raise ConnectionTimeoutError( + f"Connection timeout to host {url}" + ) from exc + + assert conn.transport is not None + + assert conn.protocol is not None + conn.protocol.set_response_params( + timer=timer, + skip_payload=method_must_be_empty_body(method), + read_until_eof=read_until_eof, + auto_decompress=auto_decompress, + read_timeout=real_timeout.sock_read, + read_bufsize=read_bufsize, + timeout_ceil_threshold=self._connector._timeout_ceil_threshold, + max_line_size=max_line_size, + max_field_size=max_field_size, + ) + + try: + try: + resp = await req.send(conn) + try: + await resp.start(conn) + except BaseException: + resp.close() + raise + except BaseException: + conn.close() + raise + except (ClientOSError, ServerDisconnectedError): + if retry_persistent_connection: + retry_persistent_connection = False + continue + raise + except ClientError: + raise + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise ClientOSError(*exc.args) from exc + + self._cookie_jar.update_cookies(resp.cookies, resp.url) + + # redirects + if resp.status in (301, 302, 303, 307, 308) and allow_redirects: + + for trace in traces: + await trace.send_request_redirect( + method, url.update_query(params), headers, resp + ) + + redirects += 1 + history.append(resp) + if max_redirects and redirects >= max_redirects: + resp.close() + raise TooManyRedirects( + history[0].request_info, tuple(history) + ) + + # For 301 and 302, mimic IE, now changed in RFC + # https://github.com/kennethreitz/requests/pull/269 + if (resp.status == 303 and resp.method != hdrs.METH_HEAD) or ( + resp.status in (301, 302) and resp.method == hdrs.METH_POST + ): + method = hdrs.METH_GET + data = None + if headers.get(hdrs.CONTENT_LENGTH): + headers.pop(hdrs.CONTENT_LENGTH) + + r_url = resp.headers.get(hdrs.LOCATION) or resp.headers.get( + hdrs.URI + ) + if r_url is None: + # see github.com/aio-libs/aiohttp/issues/2022 + break + else: + # reading from correct redirection + # response is forbidden + resp.release() + + try: + parsed_redirect_url = URL( + r_url, encoded=not self._requote_redirect_url + ) + except ValueError as e: + raise InvalidUrlRedirectClientError( + r_url, + "Server attempted redirecting to a location that does not look like a URL", + ) from e + + scheme = parsed_redirect_url.scheme + if scheme not in HTTP_AND_EMPTY_SCHEMA_SET: + resp.close() + raise NonHttpUrlRedirectClientError(r_url) + elif not scheme: + parsed_redirect_url = url.join(parsed_redirect_url) + + try: + redirect_origin = parsed_redirect_url.origin() + except ValueError as origin_val_err: + raise InvalidUrlRedirectClientError( + parsed_redirect_url, + "Invalid redirect URL origin", + ) from origin_val_err + + if url.origin() != redirect_origin: + auth = None + headers.pop(hdrs.AUTHORIZATION, None) + + url = parsed_redirect_url + params = {} + resp.release() + continue + + break + + # check response status + if raise_for_status is None: + raise_for_status = self._raise_for_status + + if raise_for_status is None: + pass + elif callable(raise_for_status): + await raise_for_status(resp) + elif raise_for_status: + resp.raise_for_status() + + # register connection + if handle is not None: + if resp.connection is not None: + resp.connection.add_callback(handle.cancel) + else: + handle.cancel() + + resp._history = tuple(history) + + for trace in traces: + await trace.send_request_end( + method, url.update_query(params), headers, resp + ) + return resp + + except BaseException as e: + # cleanup timer + tm.close() + if handle: + handle.cancel() + handle = None + + for trace in traces: + await trace.send_request_exception( + method, url.update_query(params), headers, e + ) + raise + + def ws_connect( + self, + url: StrOrURL, + *, + method: str = hdrs.METH_GET, + protocols: Iterable[str] = (), + timeout: float = 10.0, + receive_timeout: Optional[float] = None, + autoclose: bool = True, + autoping: bool = True, + heartbeat: Optional[float] = None, + auth: Optional[BasicAuth] = None, + origin: Optional[str] = None, + params: Optional[Mapping[str, str]] = None, + headers: Optional[LooseHeaders] = None, + proxy: Optional[StrOrURL] = None, + proxy_auth: Optional[BasicAuth] = None, + ssl: Union[SSLContext, bool, Fingerprint] = True, + verify_ssl: Optional[bool] = None, + fingerprint: Optional[bytes] = None, + ssl_context: Optional[SSLContext] = None, + proxy_headers: Optional[LooseHeaders] = None, + compress: int = 0, + max_msg_size: int = 4 * 1024 * 1024, + ) -> "_WSRequestContextManager": + """Initiate websocket connection.""" + return _WSRequestContextManager( + self._ws_connect( + url, + method=method, + protocols=protocols, + timeout=timeout, + receive_timeout=receive_timeout, + autoclose=autoclose, + autoping=autoping, + heartbeat=heartbeat, + auth=auth, + origin=origin, + params=params, + headers=headers, + proxy=proxy, + proxy_auth=proxy_auth, + ssl=ssl, + verify_ssl=verify_ssl, + fingerprint=fingerprint, + ssl_context=ssl_context, + proxy_headers=proxy_headers, + compress=compress, + max_msg_size=max_msg_size, + ) + ) + + async def _ws_connect( + self, + url: StrOrURL, + *, + method: str = hdrs.METH_GET, + protocols: Iterable[str] = (), + timeout: float = 10.0, + receive_timeout: Optional[float] = None, + autoclose: bool = True, + autoping: bool = True, + heartbeat: Optional[float] = None, + auth: Optional[BasicAuth] = None, + origin: Optional[str] = None, + params: Optional[Mapping[str, str]] = None, + headers: Optional[LooseHeaders] = None, + proxy: Optional[StrOrURL] = None, + proxy_auth: Optional[BasicAuth] = None, + ssl: Union[SSLContext, bool, Fingerprint] = True, + verify_ssl: Optional[bool] = None, + fingerprint: Optional[bytes] = None, + ssl_context: Optional[SSLContext] = None, + proxy_headers: Optional[LooseHeaders] = None, + compress: int = 0, + max_msg_size: int = 4 * 1024 * 1024, + ) -> ClientWebSocketResponse: + + if headers is None: + real_headers: CIMultiDict[str] = CIMultiDict() + else: + real_headers = CIMultiDict(headers) + + default_headers = { + hdrs.UPGRADE: "websocket", + hdrs.CONNECTION: "Upgrade", + hdrs.SEC_WEBSOCKET_VERSION: "13", + } + + for key, value in default_headers.items(): + real_headers.setdefault(key, value) + + sec_key = base64.b64encode(os.urandom(16)) + real_headers[hdrs.SEC_WEBSOCKET_KEY] = sec_key.decode() + + if protocols: + real_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ",".join(protocols) + if origin is not None: + real_headers[hdrs.ORIGIN] = origin + if compress: + extstr = ws_ext_gen(compress=compress) + real_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = extstr + + # For the sake of backward compatibility, if user passes in None, convert it to True + if ssl is None: + warnings.warn( + "ssl=None is deprecated, please use ssl=True", + DeprecationWarning, + stacklevel=2, + ) + ssl = True + ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) + + # send request + resp = await self.request( + method, + url, + params=params, + headers=real_headers, + read_until_eof=False, + auth=auth, + proxy=proxy, + proxy_auth=proxy_auth, + ssl=ssl, + proxy_headers=proxy_headers, + ) + + try: + # check handshake + if resp.status != 101: + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message="Invalid response status", + status=resp.status, + headers=resp.headers, + ) + + if resp.headers.get(hdrs.UPGRADE, "").lower() != "websocket": + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message="Invalid upgrade header", + status=resp.status, + headers=resp.headers, + ) + + if resp.headers.get(hdrs.CONNECTION, "").lower() != "upgrade": + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message="Invalid connection header", + status=resp.status, + headers=resp.headers, + ) + + # key calculation + r_key = resp.headers.get(hdrs.SEC_WEBSOCKET_ACCEPT, "") + match = base64.b64encode(hashlib.sha1(sec_key + WS_KEY).digest()).decode() + if r_key != match: + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message="Invalid challenge response", + status=resp.status, + headers=resp.headers, + ) + + # websocket protocol + protocol = None + if protocols and hdrs.SEC_WEBSOCKET_PROTOCOL in resp.headers: + resp_protocols = [ + proto.strip() + for proto in resp.headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",") + ] + + for proto in resp_protocols: + if proto in protocols: + protocol = proto + break + + # websocket compress + notakeover = False + if compress: + compress_hdrs = resp.headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS) + if compress_hdrs: + try: + compress, notakeover = ws_ext_parse(compress_hdrs) + except WSHandshakeError as exc: + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message=exc.args[0], + status=resp.status, + headers=resp.headers, + ) from exc + else: + compress = 0 + notakeover = False + + conn = resp.connection + assert conn is not None + conn_proto = conn.protocol + assert conn_proto is not None + + # For WS connection the read_timeout must be either receive_timeout or greater + # None == no timeout, i.e. infinite timeout, so None is the max timeout possible + if receive_timeout is None: + # Reset regardless + conn_proto.read_timeout = receive_timeout + elif conn_proto.read_timeout is not None: + # If read_timeout was set check which wins + conn_proto.read_timeout = max(receive_timeout, conn_proto.read_timeout) + + transport = conn.transport + assert transport is not None + reader: FlowControlDataQueue[WSMessage] = FlowControlDataQueue( + conn_proto, 2**16, loop=self._loop + ) + conn_proto.set_parser(WebSocketReader(reader, max_msg_size), reader) + writer = WebSocketWriter( + conn_proto, + transport, + use_mask=True, + compress=compress, + notakeover=notakeover, + ) + except BaseException: + resp.close() + raise + else: + return self._ws_response_class( + reader, + writer, + protocol, + resp, + timeout, + autoclose, + autoping, + self._loop, + receive_timeout=receive_timeout, + heartbeat=heartbeat, + compress=compress, + client_notakeover=notakeover, + ) + + def _prepare_headers(self, headers: Optional[LooseHeaders]) -> "CIMultiDict[str]": + """Add default headers and transform it to CIMultiDict""" + # Convert headers to MultiDict + result = CIMultiDict(self._default_headers) + if headers: + if not isinstance(headers, (MultiDictProxy, MultiDict)): + headers = CIMultiDict(headers) + added_names: Set[str] = set() + for key, value in headers.items(): + if key in added_names: + result.add(key, value) + else: + result[key] = value + added_names.add(key) + return result + + if sys.version_info >= (3, 11) and TYPE_CHECKING: + + def get( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def options( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def head( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def post( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def put( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def patch( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def delete( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + else: + + def get( + self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP GET request.""" + return _RequestContextManager( + self._request( + hdrs.METH_GET, url, allow_redirects=allow_redirects, **kwargs + ) + ) + + def options( + self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP OPTIONS request.""" + return _RequestContextManager( + self._request( + hdrs.METH_OPTIONS, url, allow_redirects=allow_redirects, **kwargs + ) + ) + + def head( + self, url: StrOrURL, *, allow_redirects: bool = False, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP HEAD request.""" + return _RequestContextManager( + self._request( + hdrs.METH_HEAD, url, allow_redirects=allow_redirects, **kwargs + ) + ) + + def post( + self, url: StrOrURL, *, data: Any = None, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP POST request.""" + return _RequestContextManager( + self._request(hdrs.METH_POST, url, data=data, **kwargs) + ) + + def put( + self, url: StrOrURL, *, data: Any = None, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP PUT request.""" + return _RequestContextManager( + self._request(hdrs.METH_PUT, url, data=data, **kwargs) + ) + + def patch( + self, url: StrOrURL, *, data: Any = None, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP PATCH request.""" + return _RequestContextManager( + self._request(hdrs.METH_PATCH, url, data=data, **kwargs) + ) + + def delete(self, url: StrOrURL, **kwargs: Any) -> "_RequestContextManager": + """Perform HTTP DELETE request.""" + return _RequestContextManager( + self._request(hdrs.METH_DELETE, url, **kwargs) + ) + + async def close(self) -> None: + """Close underlying connector. + + Release all acquired resources. + """ + if not self.closed: + if self._connector is not None and self._connector_owner: + await self._connector.close() + self._connector = None + + @property + def closed(self) -> bool: + """Is client session closed. + + A readonly property. + """ + return self._connector is None or self._connector.closed + + @property + def connector(self) -> Optional[BaseConnector]: + """Connector instance used for the session.""" + return self._connector + + @property + def cookie_jar(self) -> AbstractCookieJar: + """The session cookies.""" + return self._cookie_jar + + @property + def version(self) -> Tuple[int, int]: + """The session HTTP protocol version.""" + return self._version + + @property + def requote_redirect_url(self) -> bool: + """Do URL requoting on redirection handling.""" + return self._requote_redirect_url + + @requote_redirect_url.setter + def requote_redirect_url(self, val: bool) -> None: + """Do URL requoting on redirection handling.""" + warnings.warn( + "session.requote_redirect_url modification " "is deprecated #2778", + DeprecationWarning, + stacklevel=2, + ) + self._requote_redirect_url = val + + @property + def loop(self) -> asyncio.AbstractEventLoop: + """Session's loop.""" + warnings.warn( + "client.loop property is deprecated", DeprecationWarning, stacklevel=2 + ) + return self._loop + + @property + def timeout(self) -> ClientTimeout: + """Timeout for the session.""" + return self._timeout + + @property + def headers(self) -> "CIMultiDict[str]": + """The default headers of the client session.""" + return self._default_headers + + @property + def skip_auto_headers(self) -> FrozenSet[istr]: + """Headers for which autogeneration should be skipped""" + return self._skip_auto_headers + + @property + def auth(self) -> Optional[BasicAuth]: + """An object that represents HTTP Basic Authorization""" + return self._default_auth + + @property + def json_serialize(self) -> JSONEncoder: + """Json serializer callable""" + return self._json_serialize + + @property + def connector_owner(self) -> bool: + """Should connector be closed on session closing""" + return self._connector_owner + + @property + def raise_for_status( + self, + ) -> Union[bool, Callable[[ClientResponse], Awaitable[None]]]: + """Should `ClientResponse.raise_for_status()` be called for each response.""" + return self._raise_for_status + + @property + def auto_decompress(self) -> bool: + """Should the body response be automatically decompressed.""" + return self._auto_decompress + + @property + def trust_env(self) -> bool: + """ + Should proxies information from environment or netrc be trusted. + + Information is from HTTP_PROXY / HTTPS_PROXY environment variables + or ~/.netrc file if present. + """ + return self._trust_env + + @property + def trace_configs(self) -> List[TraceConfig]: + """A list of TraceConfig instances used for client tracing""" + return self._trace_configs + + def detach(self) -> None: + """Detach connector from session without closing the former. + + Session is switched to closed state anyway. + """ + self._connector = None + + def __enter__(self) -> None: + raise TypeError("Use async with instead") + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + # __exit__ should exist in pair with __enter__ but never executed + pass # pragma: no cover + + async def __aenter__(self) -> "ClientSession": + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + await self.close() + + +class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]): + + __slots__ = ("_coro", "_resp") + + def __init__(self, coro: Coroutine["asyncio.Future[Any]", None, _RetType]) -> None: + self._coro = coro + + def send(self, arg: None) -> "asyncio.Future[Any]": + return self._coro.send(arg) + + def throw(self, *args: Any, **kwargs: Any) -> "asyncio.Future[Any]": + return self._coro.throw(*args, **kwargs) + + def close(self) -> None: + return self._coro.close() + + def __await__(self) -> Generator[Any, None, _RetType]: + ret = self._coro.__await__() + return ret + + def __iter__(self) -> Generator[Any, None, _RetType]: + return self.__await__() + + async def __aenter__(self) -> _RetType: + self._resp = await self._coro + return self._resp + + +class _RequestContextManager(_BaseRequestContextManager[ClientResponse]): + __slots__ = () + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + # We're basing behavior on the exception as it can be caused by + # user code unrelated to the status of the connection. If you + # would like to close a connection you must do that + # explicitly. Otherwise connection error handling should kick in + # and close/recycle the connection as required. + self._resp.release() + await self._resp.wait_for_close() + + +class _WSRequestContextManager(_BaseRequestContextManager[ClientWebSocketResponse]): + __slots__ = () + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + await self._resp.close() + + +class _SessionRequestContextManager: + + __slots__ = ("_coro", "_resp", "_session") + + def __init__( + self, + coro: Coroutine["asyncio.Future[Any]", None, ClientResponse], + session: ClientSession, + ) -> None: + self._coro = coro + self._resp: Optional[ClientResponse] = None + self._session = session + + async def __aenter__(self) -> ClientResponse: + try: + self._resp = await self._coro + except BaseException: + await self._session.close() + raise + else: + return self._resp + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + assert self._resp is not None + self._resp.close() + await self._session.close() + + +def request( + method: str, + url: StrOrURL, + *, + params: Optional[Mapping[str, str]] = None, + data: Any = None, + json: Any = None, + headers: Optional[LooseHeaders] = None, + skip_auto_headers: Optional[Iterable[str]] = None, + auth: Optional[BasicAuth] = None, + allow_redirects: bool = True, + max_redirects: int = 10, + compress: Optional[str] = None, + chunked: Optional[bool] = None, + expect100: bool = False, + raise_for_status: Optional[bool] = None, + read_until_eof: bool = True, + proxy: Optional[StrOrURL] = None, + proxy_auth: Optional[BasicAuth] = None, + timeout: Union[ClientTimeout, object] = sentinel, + cookies: Optional[LooseCookies] = None, + version: HttpVersion = http.HttpVersion11, + connector: Optional[BaseConnector] = None, + read_bufsize: Optional[int] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + max_line_size: int = 8190, + max_field_size: int = 8190, +) -> _SessionRequestContextManager: + """Constructs and sends a request. + + Returns response object. + method - HTTP method + url - request url + params - (optional) Dictionary or bytes to be sent in the query + string of the new request + data - (optional) Dictionary, bytes, or file-like object to + send in the body of the request + json - (optional) Any json compatible python object + headers - (optional) Dictionary of HTTP Headers to send with + the request + cookies - (optional) Dict object to send with the request + auth - (optional) BasicAuth named tuple represent HTTP Basic Auth + auth - aiohttp.helpers.BasicAuth + allow_redirects - (optional) If set to False, do not follow + redirects + version - Request HTTP version. + compress - Set to True if request has to be compressed + with deflate encoding. + chunked - Set to chunk size for chunked transfer encoding. + expect100 - Expect 100-continue response from server. + connector - BaseConnector sub-class instance to support + connection pooling. + read_until_eof - Read response until eof if response + does not have Content-Length header. + loop - Optional event loop. + timeout - Optional ClientTimeout settings structure, 5min + total timeout by default. + Usage:: + >>> import aiohttp + >>> resp = await aiohttp.request('GET', 'http://python.org/') + >>> resp + + >>> data = await resp.read() + """ + connector_owner = False + if connector is None: + connector_owner = True + connector = TCPConnector(loop=loop, force_close=True) + + session = ClientSession( + loop=loop, + cookies=cookies, + version=version, + timeout=timeout, + connector=connector, + connector_owner=connector_owner, + ) + + return _SessionRequestContextManager( + session._request( + method, + url, + params=params, + data=data, + json=json, + headers=headers, + skip_auto_headers=skip_auto_headers, + auth=auth, + allow_redirects=allow_redirects, + max_redirects=max_redirects, + compress=compress, + chunked=chunked, + expect100=expect100, + raise_for_status=raise_for_status, + read_until_eof=read_until_eof, + proxy=proxy, + proxy_auth=proxy_auth, + read_bufsize=read_bufsize, + max_line_size=max_line_size, + max_field_size=max_field_size, + ), + session, + ) diff --git a/env/Lib/site-packages/aiohttp/client_exceptions.py b/env/Lib/site-packages/aiohttp/client_exceptions.py new file mode 100644 index 0000000..ff29b3d --- /dev/null +++ b/env/Lib/site-packages/aiohttp/client_exceptions.py @@ -0,0 +1,396 @@ +"""HTTP related errors.""" + +import asyncio +import warnings +from typing import TYPE_CHECKING, Optional, Tuple, Union + +from .http_parser import RawResponseMessage +from .typedefs import LooseHeaders, StrOrURL + +try: + import ssl + + SSLContext = ssl.SSLContext +except ImportError: # pragma: no cover + ssl = SSLContext = None # type: ignore[assignment] + + +if TYPE_CHECKING: + from .client_reqrep import ClientResponse, ConnectionKey, Fingerprint, RequestInfo +else: + RequestInfo = ClientResponse = ConnectionKey = None + +__all__ = ( + "ClientError", + "ClientConnectionError", + "ClientOSError", + "ClientConnectorError", + "ClientProxyConnectionError", + "ClientSSLError", + "ClientConnectorSSLError", + "ClientConnectorCertificateError", + "ConnectionTimeoutError", + "SocketTimeoutError", + "ServerConnectionError", + "ServerTimeoutError", + "ServerDisconnectedError", + "ServerFingerprintMismatch", + "ClientResponseError", + "ClientHttpProxyError", + "WSServerHandshakeError", + "ContentTypeError", + "ClientPayloadError", + "InvalidURL", + "InvalidUrlClientError", + "RedirectClientError", + "NonHttpUrlClientError", + "InvalidUrlRedirectClientError", + "NonHttpUrlRedirectClientError", +) + + +class ClientError(Exception): + """Base class for client connection errors.""" + + +class ClientResponseError(ClientError): + """Base class for exceptions that occur after getting a response. + + request_info: An instance of RequestInfo. + history: A sequence of responses, if redirects occurred. + status: HTTP status code. + message: Error message. + headers: Response headers. + """ + + def __init__( + self, + request_info: RequestInfo, + history: Tuple[ClientResponse, ...], + *, + code: Optional[int] = None, + status: Optional[int] = None, + message: str = "", + headers: Optional[LooseHeaders] = None, + ) -> None: + self.request_info = request_info + if code is not None: + if status is not None: + raise ValueError( + "Both code and status arguments are provided; " + "code is deprecated, use status instead" + ) + warnings.warn( + "code argument is deprecated, use status instead", + DeprecationWarning, + stacklevel=2, + ) + if status is not None: + self.status = status + elif code is not None: + self.status = code + else: + self.status = 0 + self.message = message + self.headers = headers + self.history = history + self.args = (request_info, history) + + def __str__(self) -> str: + return "{}, message={!r}, url={!r}".format( + self.status, + self.message, + str(self.request_info.real_url), + ) + + def __repr__(self) -> str: + args = f"{self.request_info!r}, {self.history!r}" + if self.status != 0: + args += f", status={self.status!r}" + if self.message != "": + args += f", message={self.message!r}" + if self.headers is not None: + args += f", headers={self.headers!r}" + return f"{type(self).__name__}({args})" + + @property + def code(self) -> int: + warnings.warn( + "code property is deprecated, use status instead", + DeprecationWarning, + stacklevel=2, + ) + return self.status + + @code.setter + def code(self, value: int) -> None: + warnings.warn( + "code property is deprecated, use status instead", + DeprecationWarning, + stacklevel=2, + ) + self.status = value + + +class ContentTypeError(ClientResponseError): + """ContentType found is not valid.""" + + +class WSServerHandshakeError(ClientResponseError): + """websocket server handshake error.""" + + +class ClientHttpProxyError(ClientResponseError): + """HTTP proxy error. + + Raised in :class:`aiohttp.connector.TCPConnector` if + proxy responds with status other than ``200 OK`` + on ``CONNECT`` request. + """ + + +class TooManyRedirects(ClientResponseError): + """Client was redirected too many times.""" + + +class ClientConnectionError(ClientError): + """Base class for client socket errors.""" + + +class ClientOSError(ClientConnectionError, OSError): + """OSError error.""" + + +class ClientConnectorError(ClientOSError): + """Client connector error. + + Raised in :class:`aiohttp.connector.TCPConnector` if + a connection can not be established. + """ + + def __init__(self, connection_key: ConnectionKey, os_error: OSError) -> None: + self._conn_key = connection_key + self._os_error = os_error + super().__init__(os_error.errno, os_error.strerror) + self.args = (connection_key, os_error) + + @property + def os_error(self) -> OSError: + return self._os_error + + @property + def host(self) -> str: + return self._conn_key.host + + @property + def port(self) -> Optional[int]: + return self._conn_key.port + + @property + def ssl(self) -> Union[SSLContext, bool, "Fingerprint"]: + return self._conn_key.ssl + + def __str__(self) -> str: + return "Cannot connect to host {0.host}:{0.port} ssl:{1} [{2}]".format( + self, "default" if self.ssl is True else self.ssl, self.strerror + ) + + # OSError.__reduce__ does too much black magick + __reduce__ = BaseException.__reduce__ + + +class ClientProxyConnectionError(ClientConnectorError): + """Proxy connection error. + + Raised in :class:`aiohttp.connector.TCPConnector` if + connection to proxy can not be established. + """ + + +class UnixClientConnectorError(ClientConnectorError): + """Unix connector error. + + Raised in :py:class:`aiohttp.connector.UnixConnector` + if connection to unix socket can not be established. + """ + + def __init__( + self, path: str, connection_key: ConnectionKey, os_error: OSError + ) -> None: + self._path = path + super().__init__(connection_key, os_error) + + @property + def path(self) -> str: + return self._path + + def __str__(self) -> str: + return "Cannot connect to unix socket {0.path} ssl:{1} [{2}]".format( + self, "default" if self.ssl is True else self.ssl, self.strerror + ) + + +class ServerConnectionError(ClientConnectionError): + """Server connection errors.""" + + +class ServerDisconnectedError(ServerConnectionError): + """Server disconnected.""" + + def __init__(self, message: Union[RawResponseMessage, str, None] = None) -> None: + if message is None: + message = "Server disconnected" + + self.args = (message,) + self.message = message + + +class ServerTimeoutError(ServerConnectionError, asyncio.TimeoutError): + """Server timeout error.""" + + +class ConnectionTimeoutError(ServerTimeoutError): + """Connection timeout error.""" + + +class SocketTimeoutError(ServerTimeoutError): + """Socket timeout error.""" + + +class ServerFingerprintMismatch(ServerConnectionError): + """SSL certificate does not match expected fingerprint.""" + + def __init__(self, expected: bytes, got: bytes, host: str, port: int) -> None: + self.expected = expected + self.got = got + self.host = host + self.port = port + self.args = (expected, got, host, port) + + def __repr__(self) -> str: + return "<{} expected={!r} got={!r} host={!r} port={!r}>".format( + self.__class__.__name__, self.expected, self.got, self.host, self.port + ) + + +class ClientPayloadError(ClientError): + """Response payload error.""" + + +class InvalidURL(ClientError, ValueError): + """Invalid URL. + + URL used for fetching is malformed, e.g. it doesn't contains host + part. + """ + + # Derive from ValueError for backward compatibility + + def __init__(self, url: StrOrURL, description: Union[str, None] = None) -> None: + # The type of url is not yarl.URL because the exception can be raised + # on URL(url) call + self._url = url + self._description = description + + if description: + super().__init__(url, description) + else: + super().__init__(url) + + @property + def url(self) -> StrOrURL: + return self._url + + @property + def description(self) -> "str | None": + return self._description + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} {self}>" + + def __str__(self) -> str: + if self._description: + return f"{self._url} - {self._description}" + return str(self._url) + + +class InvalidUrlClientError(InvalidURL): + """Invalid URL client error.""" + + +class RedirectClientError(ClientError): + """Client redirect error.""" + + +class NonHttpUrlClientError(ClientError): + """Non http URL client error.""" + + +class InvalidUrlRedirectClientError(InvalidUrlClientError, RedirectClientError): + """Invalid URL redirect client error.""" + + +class NonHttpUrlRedirectClientError(NonHttpUrlClientError, RedirectClientError): + """Non http URL redirect client error.""" + + +class ClientSSLError(ClientConnectorError): + """Base error for ssl.*Errors.""" + + +if ssl is not None: + cert_errors = (ssl.CertificateError,) + cert_errors_bases = ( + ClientSSLError, + ssl.CertificateError, + ) + + ssl_errors = (ssl.SSLError,) + ssl_error_bases = (ClientSSLError, ssl.SSLError) +else: # pragma: no cover + cert_errors = tuple() + cert_errors_bases = ( + ClientSSLError, + ValueError, + ) + + ssl_errors = tuple() + ssl_error_bases = (ClientSSLError,) + + +class ClientConnectorSSLError(*ssl_error_bases): # type: ignore[misc] + """Response ssl error.""" + + +class ClientConnectorCertificateError(*cert_errors_bases): # type: ignore[misc] + """Response certificate error.""" + + def __init__( + self, connection_key: ConnectionKey, certificate_error: Exception + ) -> None: + self._conn_key = connection_key + self._certificate_error = certificate_error + self.args = (connection_key, certificate_error) + + @property + def certificate_error(self) -> Exception: + return self._certificate_error + + @property + def host(self) -> str: + return self._conn_key.host + + @property + def port(self) -> Optional[int]: + return self._conn_key.port + + @property + def ssl(self) -> bool: + return self._conn_key.is_ssl + + def __str__(self) -> str: + return ( + "Cannot connect to host {0.host}:{0.port} ssl:{0.ssl} " + "[{0.certificate_error.__class__.__name__}: " + "{0.certificate_error.args}]".format(self) + ) diff --git a/env/Lib/site-packages/aiohttp/client_proto.py b/env/Lib/site-packages/aiohttp/client_proto.py new file mode 100644 index 0000000..f8c8324 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/client_proto.py @@ -0,0 +1,304 @@ +import asyncio +from contextlib import suppress +from typing import Any, Optional, Tuple + +from .base_protocol import BaseProtocol +from .client_exceptions import ( + ClientOSError, + ClientPayloadError, + ServerDisconnectedError, + SocketTimeoutError, +) +from .helpers import ( + _EXC_SENTINEL, + BaseTimerContext, + set_exception, + status_code_must_be_empty_body, +) +from .http import HttpResponseParser, RawResponseMessage +from .http_exceptions import HttpProcessingError +from .streams import EMPTY_PAYLOAD, DataQueue, StreamReader + + +class ResponseHandler(BaseProtocol, DataQueue[Tuple[RawResponseMessage, StreamReader]]): + """Helper class to adapt between Protocol and StreamReader.""" + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + BaseProtocol.__init__(self, loop=loop) + DataQueue.__init__(self, loop) + + self._should_close = False + + self._payload: Optional[StreamReader] = None + self._skip_payload = False + self._payload_parser = None + + self._timer = None + + self._tail = b"" + self._upgraded = False + self._parser: Optional[HttpResponseParser] = None + + self._read_timeout: Optional[float] = None + self._read_timeout_handle: Optional[asyncio.TimerHandle] = None + + self._timeout_ceil_threshold: Optional[float] = 5 + + @property + def upgraded(self) -> bool: + return self._upgraded + + @property + def should_close(self) -> bool: + if self._payload is not None and not self._payload.is_eof() or self._upgraded: + return True + + return ( + self._should_close + or self._upgraded + or self.exception() is not None + or self._payload_parser is not None + or len(self) > 0 + or bool(self._tail) + ) + + def force_close(self) -> None: + self._should_close = True + + def close(self) -> None: + transport = self.transport + if transport is not None: + transport.close() + self.transport = None + self._payload = None + self._drop_timeout() + + def is_connected(self) -> bool: + return self.transport is not None and not self.transport.is_closing() + + def connection_lost(self, exc: Optional[BaseException]) -> None: + self._drop_timeout() + + original_connection_error = exc + reraised_exc = original_connection_error + + connection_closed_cleanly = original_connection_error is None + + if self._payload_parser is not None: + with suppress(Exception): # FIXME: log this somehow? + self._payload_parser.feed_eof() + + uncompleted = None + if self._parser is not None: + try: + uncompleted = self._parser.feed_eof() + except Exception as underlying_exc: + if self._payload is not None: + client_payload_exc_msg = ( + f"Response payload is not completed: {underlying_exc !r}" + ) + if not connection_closed_cleanly: + client_payload_exc_msg = ( + f"{client_payload_exc_msg !s}. " + f"{original_connection_error !r}" + ) + set_exception( + self._payload, + ClientPayloadError(client_payload_exc_msg), + underlying_exc, + ) + + if not self.is_eof(): + if isinstance(original_connection_error, OSError): + reraised_exc = ClientOSError(*original_connection_error.args) + if connection_closed_cleanly: + reraised_exc = ServerDisconnectedError(uncompleted) + # assigns self._should_close to True as side effect, + # we do it anyway below + underlying_non_eof_exc = ( + _EXC_SENTINEL + if connection_closed_cleanly + else original_connection_error + ) + assert underlying_non_eof_exc is not None + assert reraised_exc is not None + self.set_exception(reraised_exc, underlying_non_eof_exc) + + self._should_close = True + self._parser = None + self._payload = None + self._payload_parser = None + self._reading_paused = False + + super().connection_lost(reraised_exc) + + def eof_received(self) -> None: + # should call parser.feed_eof() most likely + self._drop_timeout() + + def pause_reading(self) -> None: + super().pause_reading() + self._drop_timeout() + + def resume_reading(self) -> None: + super().resume_reading() + self._reschedule_timeout() + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + self._should_close = True + self._drop_timeout() + super().set_exception(exc, exc_cause) + + def set_parser(self, parser: Any, payload: Any) -> None: + # TODO: actual types are: + # parser: WebSocketReader + # payload: FlowControlDataQueue + # but they are not generi enough + # Need an ABC for both types + self._payload = payload + self._payload_parser = parser + + self._drop_timeout() + + if self._tail: + data, self._tail = self._tail, b"" + self.data_received(data) + + def set_response_params( + self, + *, + timer: Optional[BaseTimerContext] = None, + skip_payload: bool = False, + read_until_eof: bool = False, + auto_decompress: bool = True, + read_timeout: Optional[float] = None, + read_bufsize: int = 2**16, + timeout_ceil_threshold: float = 5, + max_line_size: int = 8190, + max_field_size: int = 8190, + ) -> None: + self._skip_payload = skip_payload + + self._read_timeout = read_timeout + + self._timeout_ceil_threshold = timeout_ceil_threshold + + self._parser = HttpResponseParser( + self, + self._loop, + read_bufsize, + timer=timer, + payload_exception=ClientPayloadError, + response_with_body=not skip_payload, + read_until_eof=read_until_eof, + auto_decompress=auto_decompress, + max_line_size=max_line_size, + max_field_size=max_field_size, + ) + + if self._tail: + data, self._tail = self._tail, b"" + self.data_received(data) + + def _drop_timeout(self) -> None: + if self._read_timeout_handle is not None: + self._read_timeout_handle.cancel() + self._read_timeout_handle = None + + def _reschedule_timeout(self) -> None: + timeout = self._read_timeout + if self._read_timeout_handle is not None: + self._read_timeout_handle.cancel() + + if timeout: + self._read_timeout_handle = self._loop.call_later( + timeout, self._on_read_timeout + ) + else: + self._read_timeout_handle = None + + def start_timeout(self) -> None: + self._reschedule_timeout() + + @property + def read_timeout(self) -> Optional[float]: + return self._read_timeout + + @read_timeout.setter + def read_timeout(self, read_timeout: Optional[float]) -> None: + self._read_timeout = read_timeout + + def _on_read_timeout(self) -> None: + exc = SocketTimeoutError("Timeout on reading data from socket") + self.set_exception(exc) + if self._payload is not None: + set_exception(self._payload, exc) + + def data_received(self, data: bytes) -> None: + self._reschedule_timeout() + + if not data: + return + + # custom payload parser + if self._payload_parser is not None: + eof, tail = self._payload_parser.feed_data(data) + if eof: + self._payload = None + self._payload_parser = None + + if tail: + self.data_received(tail) + return + else: + if self._upgraded or self._parser is None: + # i.e. websocket connection, websocket parser is not set yet + self._tail += data + else: + # parse http messages + try: + messages, upgraded, tail = self._parser.feed_data(data) + except BaseException as underlying_exc: + if self.transport is not None: + # connection.release() could be called BEFORE + # data_received(), the transport is already + # closed in this case + self.transport.close() + # should_close is True after the call + self.set_exception(HttpProcessingError(), underlying_exc) + return + + self._upgraded = upgraded + + payload: Optional[StreamReader] = None + for message, payload in messages: + if message.should_close: + self._should_close = True + + self._payload = payload + + if self._skip_payload or status_code_must_be_empty_body( + message.code + ): + self.feed_data((message, EMPTY_PAYLOAD), 0) + else: + self.feed_data((message, payload), 0) + if payload is not None: + # new message(s) was processed + # register timeout handler unsubscribing + # either on end-of-stream or immediately for + # EMPTY_PAYLOAD + if payload is not EMPTY_PAYLOAD: + payload.on_eof(self._drop_timeout) + else: + self._drop_timeout() + + if tail: + if upgraded: + self.data_received(tail) + else: + self._tail = tail diff --git a/env/Lib/site-packages/aiohttp/client_reqrep.py b/env/Lib/site-packages/aiohttp/client_reqrep.py new file mode 100644 index 0000000..bea76d8 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/client_reqrep.py @@ -0,0 +1,1231 @@ +import asyncio +import codecs +import contextlib +import functools +import io +import re +import sys +import traceback +import warnings +from hashlib import md5, sha1, sha256 +from http.cookies import CookieError, Morsel, SimpleCookie +from types import MappingProxyType, TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Mapping, + Optional, + Tuple, + Type, + Union, + cast, +) + +import attr +from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy +from yarl import URL + +from . import hdrs, helpers, http, multipart, payload +from .abc import AbstractStreamWriter +from .client_exceptions import ( + ClientConnectionError, + ClientOSError, + ClientResponseError, + ContentTypeError, + InvalidURL, + ServerFingerprintMismatch, +) +from .compression_utils import HAS_BROTLI +from .formdata import FormData +from .helpers import ( + BaseTimerContext, + BasicAuth, + HeadersMixin, + TimerNoop, + basicauth_from_netrc, + netrc_from_env, + noop, + reify, + set_exception, + set_result, +) +from .http import ( + SERVER_SOFTWARE, + HttpVersion, + HttpVersion10, + HttpVersion11, + StreamWriter, +) +from .log import client_logger +from .streams import StreamReader +from .typedefs import ( + DEFAULT_JSON_DECODER, + JSONDecoder, + LooseCookies, + LooseHeaders, + RawHeaders, +) + +try: + import ssl + from ssl import SSLContext +except ImportError: # pragma: no cover + ssl = None # type: ignore[assignment] + SSLContext = object # type: ignore[misc,assignment] + + +__all__ = ("ClientRequest", "ClientResponse", "RequestInfo", "Fingerprint") + + +if TYPE_CHECKING: + from .client import ClientSession + from .connector import Connection + from .tracing import Trace + + +_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]") +json_re = re.compile(r"^application/(?:[\w.+-]+?\+)?json") + + +def _gen_default_accept_encoding() -> str: + return "gzip, deflate, br" if HAS_BROTLI else "gzip, deflate" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class ContentDisposition: + type: Optional[str] + parameters: "MappingProxyType[str, str]" + filename: Optional[str] + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class RequestInfo: + url: URL + method: str + headers: "CIMultiDictProxy[str]" + real_url: URL = attr.ib() + + @real_url.default + def real_url_default(self) -> URL: + return self.url + + +class Fingerprint: + HASHFUNC_BY_DIGESTLEN = { + 16: md5, + 20: sha1, + 32: sha256, + } + + def __init__(self, fingerprint: bytes) -> None: + digestlen = len(fingerprint) + hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen) + if not hashfunc: + raise ValueError("fingerprint has invalid length") + elif hashfunc is md5 or hashfunc is sha1: + raise ValueError( + "md5 and sha1 are insecure and " "not supported. Use sha256." + ) + self._hashfunc = hashfunc + self._fingerprint = fingerprint + + @property + def fingerprint(self) -> bytes: + return self._fingerprint + + def check(self, transport: asyncio.Transport) -> None: + if not transport.get_extra_info("sslcontext"): + return + sslobj = transport.get_extra_info("ssl_object") + cert = sslobj.getpeercert(binary_form=True) + got = self._hashfunc(cert).digest() + if got != self._fingerprint: + host, port, *_ = transport.get_extra_info("peername") + raise ServerFingerprintMismatch(self._fingerprint, got, host, port) + + +if ssl is not None: + SSL_ALLOWED_TYPES = (ssl.SSLContext, bool, Fingerprint, type(None)) +else: # pragma: no cover + SSL_ALLOWED_TYPES = (bool, type(None)) + + +def _merge_ssl_params( + ssl: Union["SSLContext", bool, Fingerprint], + verify_ssl: Optional[bool], + ssl_context: Optional["SSLContext"], + fingerprint: Optional[bytes], +) -> Union["SSLContext", bool, Fingerprint]: + if ssl is None: + ssl = True # Double check for backwards compatibility + if verify_ssl is not None and not verify_ssl: + warnings.warn( + "verify_ssl is deprecated, use ssl=False instead", + DeprecationWarning, + stacklevel=3, + ) + if ssl is not True: + raise ValueError( + "verify_ssl, ssl_context, fingerprint and ssl " + "parameters are mutually exclusive" + ) + else: + ssl = False + if ssl_context is not None: + warnings.warn( + "ssl_context is deprecated, use ssl=context instead", + DeprecationWarning, + stacklevel=3, + ) + if ssl is not True: + raise ValueError( + "verify_ssl, ssl_context, fingerprint and ssl " + "parameters are mutually exclusive" + ) + else: + ssl = ssl_context + if fingerprint is not None: + warnings.warn( + "fingerprint is deprecated, " "use ssl=Fingerprint(fingerprint) instead", + DeprecationWarning, + stacklevel=3, + ) + if ssl is not True: + raise ValueError( + "verify_ssl, ssl_context, fingerprint and ssl " + "parameters are mutually exclusive" + ) + else: + ssl = Fingerprint(fingerprint) + if not isinstance(ssl, SSL_ALLOWED_TYPES): + raise TypeError( + "ssl should be SSLContext, bool, Fingerprint or None, " + "got {!r} instead.".format(ssl) + ) + return ssl + + +@attr.s(auto_attribs=True, slots=True, frozen=True) +class ConnectionKey: + # the key should contain an information about used proxy / TLS + # to prevent reusing wrong connections from a pool + host: str + port: Optional[int] + is_ssl: bool + ssl: Union[SSLContext, bool, Fingerprint] + proxy: Optional[URL] + proxy_auth: Optional[BasicAuth] + proxy_headers_hash: Optional[int] # hash(CIMultiDict) + + +def _is_expected_content_type( + response_content_type: str, expected_content_type: str +) -> bool: + if expected_content_type == "application/json": + return json_re.match(response_content_type) is not None + return expected_content_type in response_content_type + + +class ClientRequest: + GET_METHODS = { + hdrs.METH_GET, + hdrs.METH_HEAD, + hdrs.METH_OPTIONS, + hdrs.METH_TRACE, + } + POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT} + ALL_METHODS = GET_METHODS.union(POST_METHODS).union({hdrs.METH_DELETE}) + + DEFAULT_HEADERS = { + hdrs.ACCEPT: "*/*", + hdrs.ACCEPT_ENCODING: _gen_default_accept_encoding(), + } + + # Type of body depends on PAYLOAD_REGISTRY, which is dynamic. + body: Any = b"" + auth = None + response = None + + __writer = None # async task for streaming data + _continue = None # waiter future for '100 Continue' response + + # N.B. + # Adding __del__ method with self._writer closing doesn't make sense + # because _writer is instance method, thus it keeps a reference to self. + # Until writer has finished finalizer will not be called. + + def __init__( + self, + method: str, + url: URL, + *, + params: Optional[Mapping[str, str]] = None, + headers: Optional[LooseHeaders] = None, + skip_auto_headers: Iterable[str] = frozenset(), + data: Any = None, + cookies: Optional[LooseCookies] = None, + auth: Optional[BasicAuth] = None, + version: http.HttpVersion = http.HttpVersion11, + compress: Optional[str] = None, + chunked: Optional[bool] = None, + expect100: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, + response_class: Optional[Type["ClientResponse"]] = None, + proxy: Optional[URL] = None, + proxy_auth: Optional[BasicAuth] = None, + timer: Optional[BaseTimerContext] = None, + session: Optional["ClientSession"] = None, + ssl: Union[SSLContext, bool, Fingerprint] = True, + proxy_headers: Optional[LooseHeaders] = None, + traces: Optional[List["Trace"]] = None, + trust_env: bool = False, + server_hostname: Optional[str] = None, + ): + if loop is None: + loop = asyncio.get_event_loop() + + match = _CONTAINS_CONTROL_CHAR_RE.search(method) + if match: + raise ValueError( + f"Method cannot contain non-token characters {method!r} " + "(found at least {match.group()!r})" + ) + + assert isinstance(url, URL), url + assert isinstance(proxy, (URL, type(None))), proxy + # FIXME: session is None in tests only, need to fix tests + # assert session is not None + self._session = cast("ClientSession", session) + if params: + q = MultiDict(url.query) + url2 = url.with_query(params) + q.extend(url2.query) + url = url.with_query(q) + self.original_url = url + self.url = url.with_fragment(None) + self.method = method.upper() + self.chunked = chunked + self.compress = compress + self.loop = loop + self.length = None + if response_class is None: + real_response_class = ClientResponse + else: + real_response_class = response_class + self.response_class: Type[ClientResponse] = real_response_class + self._timer = timer if timer is not None else TimerNoop() + self._ssl = ssl if ssl is not None else True + self.server_hostname = server_hostname + + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + self.update_version(version) + self.update_host(url) + self.update_headers(headers) + self.update_auto_headers(skip_auto_headers) + self.update_cookies(cookies) + self.update_content_encoding(data) + self.update_auth(auth, trust_env) + self.update_proxy(proxy, proxy_auth, proxy_headers) + + self.update_body_from_data(data) + if data is not None or self.method not in self.GET_METHODS: + self.update_transfer_encoding() + self.update_expect_continue(expect100) + if traces is None: + traces = [] + self._traces = traces + + def __reset_writer(self, _: object = None) -> None: + self.__writer = None + + @property + def _writer(self) -> Optional["asyncio.Task[None]"]: + return self.__writer + + @_writer.setter + def _writer(self, writer: Optional["asyncio.Task[None]"]) -> None: + if self.__writer is not None: + self.__writer.remove_done_callback(self.__reset_writer) + self.__writer = writer + if writer is None: + return + if writer.done(): + # The writer is already done, so we can reset it immediately. + self.__reset_writer() + else: + writer.add_done_callback(self.__reset_writer) + + def is_ssl(self) -> bool: + return self.url.scheme in ("https", "wss") + + @property + def ssl(self) -> Union["SSLContext", bool, Fingerprint]: + return self._ssl + + @property + def connection_key(self) -> ConnectionKey: + proxy_headers = self.proxy_headers + if proxy_headers: + h: Optional[int] = hash(tuple((k, v) for k, v in proxy_headers.items())) + else: + h = None + return ConnectionKey( + self.host, + self.port, + self.is_ssl(), + self.ssl, + self.proxy, + self.proxy_auth, + h, + ) + + @property + def host(self) -> str: + ret = self.url.raw_host + assert ret is not None + return ret + + @property + def port(self) -> Optional[int]: + return self.url.port + + @property + def request_info(self) -> RequestInfo: + headers: CIMultiDictProxy[str] = CIMultiDictProxy(self.headers) + return RequestInfo(self.url, self.method, headers, self.original_url) + + def update_host(self, url: URL) -> None: + """Update destination host, port and connection type (ssl).""" + # get host/port + if not url.raw_host: + raise InvalidURL(url) + + # basic auth info + username, password = url.user, url.password + if username: + self.auth = helpers.BasicAuth(username, password or "") + + def update_version(self, version: Union[http.HttpVersion, str]) -> None: + """Convert request version to two elements tuple. + + parser HTTP version '1.1' => (1, 1) + """ + if isinstance(version, str): + v = [part.strip() for part in version.split(".", 1)] + try: + version = http.HttpVersion(int(v[0]), int(v[1])) + except ValueError: + raise ValueError( + f"Can not parse http version number: {version}" + ) from None + self.version = version + + def update_headers(self, headers: Optional[LooseHeaders]) -> None: + """Update request headers.""" + self.headers: CIMultiDict[str] = CIMultiDict() + + # add host + netloc = cast(str, self.url.raw_host) + if helpers.is_ipv6_address(netloc): + netloc = f"[{netloc}]" + # See https://github.com/aio-libs/aiohttp/issues/3636. + netloc = netloc.rstrip(".") + if self.url.port is not None and not self.url.is_default_port(): + netloc += ":" + str(self.url.port) + self.headers[hdrs.HOST] = netloc + + if headers: + if isinstance(headers, (dict, MultiDictProxy, MultiDict)): + headers = headers.items() + + for key, value in headers: # type: ignore[misc] + # A special case for Host header + if key.lower() == "host": + self.headers[key] = value + else: + self.headers.add(key, value) + + def update_auto_headers(self, skip_auto_headers: Iterable[str]) -> None: + self.skip_auto_headers = CIMultiDict( + (hdr, None) for hdr in sorted(skip_auto_headers) + ) + used_headers = self.headers.copy() + used_headers.extend(self.skip_auto_headers) # type: ignore[arg-type] + + for hdr, val in self.DEFAULT_HEADERS.items(): + if hdr not in used_headers: + self.headers.add(hdr, val) + + if hdrs.USER_AGENT not in used_headers: + self.headers[hdrs.USER_AGENT] = SERVER_SOFTWARE + + def update_cookies(self, cookies: Optional[LooseCookies]) -> None: + """Update request cookies header.""" + if not cookies: + return + + c = SimpleCookie() + if hdrs.COOKIE in self.headers: + c.load(self.headers.get(hdrs.COOKIE, "")) + del self.headers[hdrs.COOKIE] + + if isinstance(cookies, Mapping): + iter_cookies = cookies.items() + else: + iter_cookies = cookies # type: ignore[assignment] + for name, value in iter_cookies: + if isinstance(value, Morsel): + # Preserve coded_value + mrsl_val = value.get(value.key, Morsel()) + mrsl_val.set(value.key, value.value, value.coded_value) + c[name] = mrsl_val + else: + c[name] = value # type: ignore[assignment] + + self.headers[hdrs.COOKIE] = c.output(header="", sep=";").strip() + + def update_content_encoding(self, data: Any) -> None: + """Set request content encoding.""" + if data is None: + return + + enc = self.headers.get(hdrs.CONTENT_ENCODING, "").lower() + if enc: + if self.compress: + raise ValueError( + "compress can not be set " "if Content-Encoding header is set" + ) + elif self.compress: + if not isinstance(self.compress, str): + self.compress = "deflate" + self.headers[hdrs.CONTENT_ENCODING] = self.compress + self.chunked = True # enable chunked, no need to deal with length + + def update_transfer_encoding(self) -> None: + """Analyze transfer-encoding header.""" + te = self.headers.get(hdrs.TRANSFER_ENCODING, "").lower() + + if "chunked" in te: + if self.chunked: + raise ValueError( + "chunked can not be set " + 'if "Transfer-Encoding: chunked" header is set' + ) + + elif self.chunked: + if hdrs.CONTENT_LENGTH in self.headers: + raise ValueError( + "chunked can not be set " "if Content-Length header is set" + ) + + self.headers[hdrs.TRANSFER_ENCODING] = "chunked" + else: + if hdrs.CONTENT_LENGTH not in self.headers: + self.headers[hdrs.CONTENT_LENGTH] = str(len(self.body)) + + def update_auth(self, auth: Optional[BasicAuth], trust_env: bool = False) -> None: + """Set basic auth.""" + if auth is None: + auth = self.auth + if auth is None and trust_env and self.url.host is not None: + netrc_obj = netrc_from_env() + with contextlib.suppress(LookupError): + auth = basicauth_from_netrc(netrc_obj, self.url.host) + if auth is None: + return + + if not isinstance(auth, helpers.BasicAuth): + raise TypeError("BasicAuth() tuple is required instead") + + self.headers[hdrs.AUTHORIZATION] = auth.encode() + + def update_body_from_data(self, body: Any) -> None: + if body is None: + return + + # FormData + if isinstance(body, FormData): + body = body() + + try: + body = payload.PAYLOAD_REGISTRY.get(body, disposition=None) + except payload.LookupError: + body = FormData(body)() + + self.body = body + + # enable chunked encoding if needed + if not self.chunked: + if hdrs.CONTENT_LENGTH not in self.headers: + size = body.size + if size is None: + self.chunked = True + else: + if hdrs.CONTENT_LENGTH not in self.headers: + self.headers[hdrs.CONTENT_LENGTH] = str(size) + + # copy payload headers + assert body.headers + for key, value in body.headers.items(): + if key in self.headers: + continue + if key in self.skip_auto_headers: + continue + self.headers[key] = value + + def update_expect_continue(self, expect: bool = False) -> None: + if expect: + self.headers[hdrs.EXPECT] = "100-continue" + elif self.headers.get(hdrs.EXPECT, "").lower() == "100-continue": + expect = True + + if expect: + self._continue = self.loop.create_future() + + def update_proxy( + self, + proxy: Optional[URL], + proxy_auth: Optional[BasicAuth], + proxy_headers: Optional[LooseHeaders], + ) -> None: + if proxy_auth and not isinstance(proxy_auth, helpers.BasicAuth): + raise ValueError("proxy_auth must be None or BasicAuth() tuple") + self.proxy = proxy + self.proxy_auth = proxy_auth + if proxy_headers is not None and not isinstance( + proxy_headers, (MultiDict, MultiDictProxy) + ): + proxy_headers = CIMultiDict(proxy_headers) + self.proxy_headers = proxy_headers + + def keep_alive(self) -> bool: + if self.version < HttpVersion10: + # keep alive not supported at all + return False + if self.version == HttpVersion10: + if self.headers.get(hdrs.CONNECTION) == "keep-alive": + return True + else: # no headers means we close for Http 1.0 + return False + elif self.headers.get(hdrs.CONNECTION) == "close": + return False + + return True + + async def write_bytes( + self, writer: AbstractStreamWriter, conn: "Connection" + ) -> None: + """Support coroutines that yields bytes objects.""" + # 100 response + if self._continue is not None: + try: + await writer.drain() + await self._continue + except asyncio.CancelledError: + return + + protocol = conn.protocol + assert protocol is not None + try: + if isinstance(self.body, payload.Payload): + await self.body.write(writer) + else: + if isinstance(self.body, (bytes, bytearray)): + self.body = (self.body,) + + for chunk in self.body: + await writer.write(chunk) + except OSError as underlying_exc: + reraised_exc = underlying_exc + + exc_is_not_timeout = underlying_exc.errno is not None or not isinstance( + underlying_exc, asyncio.TimeoutError + ) + if exc_is_not_timeout: + reraised_exc = ClientOSError( + underlying_exc.errno, + f"Can not write request body for {self.url !s}", + ) + + set_exception(protocol, reraised_exc, underlying_exc) + except asyncio.CancelledError: + await writer.write_eof() + except Exception as underlying_exc: + set_exception( + protocol, + ClientConnectionError( + f"Failed to send bytes into the underlying connection {conn !s}", + ), + underlying_exc, + ) + else: + await writer.write_eof() + protocol.start_timeout() + + async def send(self, conn: "Connection") -> "ClientResponse": + # Specify request target: + # - CONNECT request must send authority form URI + # - not CONNECT proxy must send absolute form URI + # - most common is origin form URI + if self.method == hdrs.METH_CONNECT: + connect_host = self.url.raw_host + assert connect_host is not None + if helpers.is_ipv6_address(connect_host): + connect_host = f"[{connect_host}]" + path = f"{connect_host}:{self.url.port}" + elif self.proxy and not self.is_ssl(): + path = str(self.url) + else: + path = self.url.raw_path + if self.url.raw_query_string: + path += "?" + self.url.raw_query_string + + protocol = conn.protocol + assert protocol is not None + writer = StreamWriter( + protocol, + self.loop, + on_chunk_sent=functools.partial( + self._on_chunk_request_sent, self.method, self.url + ), + on_headers_sent=functools.partial( + self._on_headers_request_sent, self.method, self.url + ), + ) + + if self.compress: + writer.enable_compression(self.compress) + + if self.chunked is not None: + writer.enable_chunking() + + # set default content-type + if ( + self.method in self.POST_METHODS + and hdrs.CONTENT_TYPE not in self.skip_auto_headers + and hdrs.CONTENT_TYPE not in self.headers + ): + self.headers[hdrs.CONTENT_TYPE] = "application/octet-stream" + + # set the connection header + connection = self.headers.get(hdrs.CONNECTION) + if not connection: + if self.keep_alive(): + if self.version == HttpVersion10: + connection = "keep-alive" + else: + if self.version == HttpVersion11: + connection = "close" + + if connection is not None: + self.headers[hdrs.CONNECTION] = connection + + # status + headers + status_line = "{0} {1} HTTP/{v.major}.{v.minor}".format( + self.method, path, v=self.version + ) + await writer.write_headers(status_line, self.headers) + coro = self.write_bytes(writer, conn) + + if sys.version_info >= (3, 12): + # Optimization for Python 3.12, try to write + # bytes immediately to avoid having to schedule + # the task on the event loop. + task = asyncio.Task(coro, loop=self.loop, eager_start=True) + else: + task = self.loop.create_task(coro) + + self._writer = task + response_class = self.response_class + assert response_class is not None + self.response = response_class( + self.method, + self.original_url, + writer=self._writer, + continue100=self._continue, + timer=self._timer, + request_info=self.request_info, + traces=self._traces, + loop=self.loop, + session=self._session, + ) + return self.response + + async def close(self) -> None: + if self._writer is not None: + with contextlib.suppress(asyncio.CancelledError): + await self._writer + + def terminate(self) -> None: + if self._writer is not None: + if not self.loop.is_closed(): + self._writer.cancel() + self._writer.remove_done_callback(self.__reset_writer) + self._writer = None + + async def _on_chunk_request_sent(self, method: str, url: URL, chunk: bytes) -> None: + for trace in self._traces: + await trace.send_request_chunk_sent(method, url, chunk) + + async def _on_headers_request_sent( + self, method: str, url: URL, headers: "CIMultiDict[str]" + ) -> None: + for trace in self._traces: + await trace.send_request_headers(method, url, headers) + + +class ClientResponse(HeadersMixin): + + # Some of these attributes are None when created, + # but will be set by the start() method. + # As the end user will likely never see the None values, we cheat the types below. + # from the Status-Line of the response + version: Optional[HttpVersion] = None # HTTP-Version + status: int = None # type: ignore[assignment] # Status-Code + reason: Optional[str] = None # Reason-Phrase + + content: StreamReader = None # type: ignore[assignment] # Payload stream + _headers: CIMultiDictProxy[str] = None # type: ignore[assignment] + _raw_headers: RawHeaders = None # type: ignore[assignment] + + _connection = None # current connection + _source_traceback: Optional[traceback.StackSummary] = None + # set up by ClientRequest after ClientResponse object creation + # post-init stage allows to not change ctor signature + _closed = True # to allow __del__ for non-initialized properly response + _released = False + __writer = None + + def __init__( + self, + method: str, + url: URL, + *, + writer: "asyncio.Task[None]", + continue100: Optional["asyncio.Future[bool]"], + timer: BaseTimerContext, + request_info: RequestInfo, + traces: List["Trace"], + loop: asyncio.AbstractEventLoop, + session: "ClientSession", + ) -> None: + assert isinstance(url, URL) + + self.method = method + self.cookies = SimpleCookie() + + self._real_url = url + self._url = url.with_fragment(None) + self._body: Any = None + self._writer: Optional[asyncio.Task[None]] = writer + self._continue = continue100 # None by default + self._closed = True + self._history: Tuple[ClientResponse, ...] = () + self._request_info = request_info + self._timer = timer if timer is not None else TimerNoop() + self._cache: Dict[str, Any] = {} + self._traces = traces + self._loop = loop + # store a reference to session #1985 + self._session: Optional[ClientSession] = session + # Save reference to _resolve_charset, so that get_encoding() will still + # work after the response has finished reading the body. + if session is None: + # TODO: Fix session=None in tests (see ClientRequest.__init__). + self._resolve_charset: Callable[["ClientResponse", bytes], str] = ( + lambda *_: "utf-8" + ) + else: + self._resolve_charset = session._resolve_charset + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + def __reset_writer(self, _: object = None) -> None: + self.__writer = None + + @property + def _writer(self) -> Optional["asyncio.Task[None]"]: + return self.__writer + + @_writer.setter + def _writer(self, writer: Optional["asyncio.Task[None]"]) -> None: + if self.__writer is not None: + self.__writer.remove_done_callback(self.__reset_writer) + self.__writer = writer + if writer is None: + return + if writer.done(): + # The writer is already done, so we can reset it immediately. + self.__reset_writer() + else: + writer.add_done_callback(self.__reset_writer) + + @reify + def url(self) -> URL: + return self._url + + @reify + def url_obj(self) -> URL: + warnings.warn("Deprecated, use .url #1654", DeprecationWarning, stacklevel=2) + return self._url + + @reify + def real_url(self) -> URL: + return self._real_url + + @reify + def host(self) -> str: + assert self._url.host is not None + return self._url.host + + @reify + def headers(self) -> "CIMultiDictProxy[str]": + return self._headers + + @reify + def raw_headers(self) -> RawHeaders: + return self._raw_headers + + @reify + def request_info(self) -> RequestInfo: + return self._request_info + + @reify + def content_disposition(self) -> Optional[ContentDisposition]: + raw = self._headers.get(hdrs.CONTENT_DISPOSITION) + if raw is None: + return None + disposition_type, params_dct = multipart.parse_content_disposition(raw) + params = MappingProxyType(params_dct) + filename = multipart.content_disposition_filename(params) + return ContentDisposition(disposition_type, params, filename) + + def __del__(self, _warnings: Any = warnings) -> None: + if self._closed: + return + + if self._connection is not None: + self._connection.release() + self._cleanup_writer() + + if self._loop.get_debug(): + kwargs = {"source": self} + _warnings.warn(f"Unclosed response {self!r}", ResourceWarning, **kwargs) + context = {"client_response": self, "message": "Unclosed response"} + if self._source_traceback: + context["source_traceback"] = self._source_traceback + self._loop.call_exception_handler(context) + + def __repr__(self) -> str: + out = io.StringIO() + ascii_encodable_url = str(self.url) + if self.reason: + ascii_encodable_reason = self.reason.encode( + "ascii", "backslashreplace" + ).decode("ascii") + else: + ascii_encodable_reason = "None" + print( + "".format( + ascii_encodable_url, self.status, ascii_encodable_reason + ), + file=out, + ) + print(self.headers, file=out) + return out.getvalue() + + @property + def connection(self) -> Optional["Connection"]: + return self._connection + + @reify + def history(self) -> Tuple["ClientResponse", ...]: + """A sequence of of responses, if redirects occurred.""" + return self._history + + @reify + def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]": + links_str = ", ".join(self.headers.getall("link", [])) + + if not links_str: + return MultiDictProxy(MultiDict()) + + links: MultiDict[MultiDictProxy[Union[str, URL]]] = MultiDict() + + for val in re.split(r",(?=\s*<)", links_str): + match = re.match(r"\s*<(.*)>(.*)", val) + if match is None: # pragma: no cover + # the check exists to suppress mypy error + continue + url, params_str = match.groups() + params = params_str.split(";")[1:] + + link: MultiDict[Union[str, URL]] = MultiDict() + + for param in params: + match = re.match(r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$", param, re.M) + if match is None: # pragma: no cover + # the check exists to suppress mypy error + continue + key, _, value, _ = match.groups() + + link.add(key, value) + + key = link.get("rel", url) + + link.add("url", self.url.join(URL(url))) + + links.add(str(key), MultiDictProxy(link)) + + return MultiDictProxy(links) + + async def start(self, connection: "Connection") -> "ClientResponse": + """Start response processing.""" + self._closed = False + self._protocol = connection.protocol + self._connection = connection + + with self._timer: + while True: + # read response + try: + protocol = self._protocol + message, payload = await protocol.read() # type: ignore[union-attr] + except http.HttpProcessingError as exc: + raise ClientResponseError( + self.request_info, + self.history, + status=exc.code, + message=exc.message, + headers=exc.headers, + ) from exc + + if message.code < 100 or message.code > 199 or message.code == 101: + break + + if self._continue is not None: + set_result(self._continue, True) + self._continue = None + + # payload eof handler + payload.on_eof(self._response_eof) + + # response status + self.version = message.version + self.status = message.code + self.reason = message.reason + + # headers + self._headers = message.headers # type is CIMultiDictProxy + self._raw_headers = message.raw_headers # type is Tuple[bytes, bytes] + + # payload + self.content = payload + + # cookies + for hdr in self.headers.getall(hdrs.SET_COOKIE, ()): + try: + self.cookies.load(hdr) + except CookieError as exc: + client_logger.warning("Can not load response cookies: %s", exc) + return self + + def _response_eof(self) -> None: + if self._closed: + return + + # protocol could be None because connection could be detached + protocol = self._connection and self._connection.protocol + if protocol is not None and protocol.upgraded: + return + + self._closed = True + self._cleanup_writer() + self._release_connection() + + @property + def closed(self) -> bool: + return self._closed + + def close(self) -> None: + if not self._released: + self._notify_content() + + self._closed = True + if self._loop is None or self._loop.is_closed(): + return + + self._cleanup_writer() + if self._connection is not None: + self._connection.close() + self._connection = None + + def release(self) -> Any: + if not self._released: + self._notify_content() + + self._closed = True + + self._cleanup_writer() + self._release_connection() + return noop() + + @property + def ok(self) -> bool: + """Returns ``True`` if ``status`` is less than ``400``, ``False`` if not. + + This is **not** a check for ``200 OK`` but a check that the response + status is under 400. + """ + return 400 > self.status + + def raise_for_status(self) -> None: + if not self.ok: + # reason should always be not None for a started response + assert self.reason is not None + self.release() + raise ClientResponseError( + self.request_info, + self.history, + status=self.status, + message=self.reason, + headers=self.headers, + ) + + def _release_connection(self) -> None: + if self._connection is not None: + if self._writer is None: + self._connection.release() + self._connection = None + else: + self._writer.add_done_callback(lambda f: self._release_connection()) + + async def _wait_released(self) -> None: + if self._writer is not None: + await self._writer + self._release_connection() + + def _cleanup_writer(self) -> None: + if self._writer is not None: + self._writer.cancel() + self._session = None + + def _notify_content(self) -> None: + content = self.content + if content and content.exception() is None: + set_exception(content, ClientConnectionError("Connection closed")) + self._released = True + + async def wait_for_close(self) -> None: + if self._writer is not None: + await self._writer + self.release() + + async def read(self) -> bytes: + """Read response payload.""" + if self._body is None: + try: + self._body = await self.content.read() + for trace in self._traces: + await trace.send_response_chunk_received( + self.method, self.url, self._body + ) + except BaseException: + self.close() + raise + elif self._released: # Response explicitly released + raise ClientConnectionError("Connection closed") + + protocol = self._connection and self._connection.protocol + if protocol is None or not protocol.upgraded: + await self._wait_released() # Underlying connection released + return self._body # type: ignore[no-any-return] + + def get_encoding(self) -> str: + ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower() + mimetype = helpers.parse_mimetype(ctype) + + encoding = mimetype.parameters.get("charset") + if encoding: + with contextlib.suppress(LookupError): + return codecs.lookup(encoding).name + + if mimetype.type == "application" and ( + mimetype.subtype == "json" or mimetype.subtype == "rdap" + ): + # RFC 7159 states that the default encoding is UTF-8. + # RFC 7483 defines application/rdap+json + return "utf-8" + + if self._body is None: + raise RuntimeError( + "Cannot compute fallback encoding of a not yet read body" + ) + + return self._resolve_charset(self, self._body) + + async def text(self, encoding: Optional[str] = None, errors: str = "strict") -> str: + """Read response payload and decode.""" + if self._body is None: + await self.read() + + if encoding is None: + encoding = self.get_encoding() + + return self._body.decode( # type: ignore[no-any-return,union-attr] + encoding, errors=errors + ) + + async def json( + self, + *, + encoding: Optional[str] = None, + loads: JSONDecoder = DEFAULT_JSON_DECODER, + content_type: Optional[str] = "application/json", + ) -> Any: + """Read and decodes JSON response.""" + if self._body is None: + await self.read() + + if content_type: + ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower() + if not _is_expected_content_type(ctype, content_type): + raise ContentTypeError( + self.request_info, + self.history, + status=self.status, + message=( + "Attempt to decode JSON with " "unexpected mimetype: %s" % ctype + ), + headers=self.headers, + ) + + stripped = self._body.strip() # type: ignore[union-attr] + if not stripped: + return None + + if encoding is None: + encoding = self.get_encoding() + + return loads(stripped.decode(encoding)) + + async def __aenter__(self) -> "ClientResponse": + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + # similar to _RequestContextManager, we do not need to check + # for exceptions, response object can close connection + # if state is broken + self.release() + await self.wait_for_close() diff --git a/env/Lib/site-packages/aiohttp/client_ws.py b/env/Lib/site-packages/aiohttp/client_ws.py new file mode 100644 index 0000000..7b3a5bf --- /dev/null +++ b/env/Lib/site-packages/aiohttp/client_ws.py @@ -0,0 +1,386 @@ +"""WebSocket client for asyncio.""" + +import asyncio +import sys +from typing import Any, Optional, cast + +from .client_exceptions import ClientError, ServerTimeoutError +from .client_reqrep import ClientResponse +from .helpers import calculate_timeout_when, set_result +from .http import ( + WS_CLOSED_MESSAGE, + WS_CLOSING_MESSAGE, + WebSocketError, + WSCloseCode, + WSMessage, + WSMsgType, +) +from .http_websocket import WebSocketWriter # WSMessage +from .streams import EofStream, FlowControlDataQueue +from .typedefs import ( + DEFAULT_JSON_DECODER, + DEFAULT_JSON_ENCODER, + JSONDecoder, + JSONEncoder, +) + +if sys.version_info >= (3, 11): + import asyncio as async_timeout +else: + import async_timeout + + +class ClientWebSocketResponse: + def __init__( + self, + reader: "FlowControlDataQueue[WSMessage]", + writer: WebSocketWriter, + protocol: Optional[str], + response: ClientResponse, + timeout: float, + autoclose: bool, + autoping: bool, + loop: asyncio.AbstractEventLoop, + *, + receive_timeout: Optional[float] = None, + heartbeat: Optional[float] = None, + compress: int = 0, + client_notakeover: bool = False, + ) -> None: + self._response = response + self._conn = response.connection + + self._writer = writer + self._reader = reader + self._protocol = protocol + self._closed = False + self._closing = False + self._close_code: Optional[int] = None + self._timeout = timeout + self._receive_timeout = receive_timeout + self._autoclose = autoclose + self._autoping = autoping + self._heartbeat = heartbeat + self._heartbeat_cb: Optional[asyncio.TimerHandle] = None + self._heartbeat_when: float = 0.0 + if heartbeat is not None: + self._pong_heartbeat = heartbeat / 2.0 + self._pong_response_cb: Optional[asyncio.TimerHandle] = None + self._loop = loop + self._waiting: bool = False + self._close_wait: Optional[asyncio.Future[None]] = None + self._exception: Optional[BaseException] = None + self._compress = compress + self._client_notakeover = client_notakeover + self._ping_task: Optional[asyncio.Task[None]] = None + + self._reset_heartbeat() + + def _cancel_heartbeat(self) -> None: + self._cancel_pong_response_cb() + if self._heartbeat_cb is not None: + self._heartbeat_cb.cancel() + self._heartbeat_cb = None + if self._ping_task is not None: + self._ping_task.cancel() + self._ping_task = None + + def _cancel_pong_response_cb(self) -> None: + if self._pong_response_cb is not None: + self._pong_response_cb.cancel() + self._pong_response_cb = None + + def _reset_heartbeat(self) -> None: + if self._heartbeat is None: + return + self._cancel_pong_response_cb() + loop = self._loop + assert loop is not None + conn = self._conn + timeout_ceil_threshold = ( + conn._connector._timeout_ceil_threshold if conn is not None else 5 + ) + now = loop.time() + when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold) + self._heartbeat_when = when + if self._heartbeat_cb is None: + # We do not cancel the previous heartbeat_cb here because + # it generates a significant amount of TimerHandle churn + # which causes asyncio to rebuild the heap frequently. + # Instead _send_heartbeat() will reschedule the next + # heartbeat if it fires too early. + self._heartbeat_cb = loop.call_at(when, self._send_heartbeat) + + def _send_heartbeat(self) -> None: + self._heartbeat_cb = None + loop = self._loop + now = loop.time() + if now < self._heartbeat_when: + # Heartbeat fired too early, reschedule + self._heartbeat_cb = loop.call_at( + self._heartbeat_when, self._send_heartbeat + ) + return + + conn = self._conn + timeout_ceil_threshold = ( + conn._connector._timeout_ceil_threshold if conn is not None else 5 + ) + when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold) + self._cancel_pong_response_cb() + self._pong_response_cb = loop.call_at(when, self._pong_not_received) + + if sys.version_info >= (3, 12): + # Optimization for Python 3.12, try to send the ping + # immediately to avoid having to schedule + # the task on the event loop. + ping_task = asyncio.Task(self._writer.ping(), loop=loop, eager_start=True) + else: + ping_task = loop.create_task(self._writer.ping()) + + if not ping_task.done(): + self._ping_task = ping_task + ping_task.add_done_callback(self._ping_task_done) + else: + self._ping_task_done(ping_task) + + def _ping_task_done(self, task: "asyncio.Task[None]") -> None: + """Callback for when the ping task completes.""" + if not task.cancelled() and (exc := task.exception()): + self._handle_ping_pong_exception(exc) + self._ping_task = None + + def _pong_not_received(self) -> None: + self._handle_ping_pong_exception(ServerTimeoutError()) + + def _handle_ping_pong_exception(self, exc: BaseException) -> None: + """Handle exceptions raised during ping/pong processing.""" + if self._closed: + return + self._set_closed() + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._exception = exc + self._response.close() + if self._waiting and not self._closing: + self._reader.feed_data(WSMessage(WSMsgType.ERROR, exc, None)) + + def _set_closed(self) -> None: + """Set the connection to closed. + + Cancel any heartbeat timers and set the closed flag. + """ + self._closed = True + self._cancel_heartbeat() + + def _set_closing(self) -> None: + """Set the connection to closing. + + Cancel any heartbeat timers and set the closing flag. + """ + self._closing = True + self._cancel_heartbeat() + + @property + def closed(self) -> bool: + return self._closed + + @property + def close_code(self) -> Optional[int]: + return self._close_code + + @property + def protocol(self) -> Optional[str]: + return self._protocol + + @property + def compress(self) -> int: + return self._compress + + @property + def client_notakeover(self) -> bool: + return self._client_notakeover + + def get_extra_info(self, name: str, default: Any = None) -> Any: + """extra info from connection transport""" + conn = self._response.connection + if conn is None: + return default + transport = conn.transport + if transport is None: + return default + return transport.get_extra_info(name, default) + + def exception(self) -> Optional[BaseException]: + return self._exception + + async def ping(self, message: bytes = b"") -> None: + await self._writer.ping(message) + + async def pong(self, message: bytes = b"") -> None: + await self._writer.pong(message) + + async def send_str(self, data: str, compress: Optional[int] = None) -> None: + if not isinstance(data, str): + raise TypeError("data argument must be str (%r)" % type(data)) + await self._writer.send(data, binary=False, compress=compress) + + async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None: + if not isinstance(data, (bytes, bytearray, memoryview)): + raise TypeError("data argument must be byte-ish (%r)" % type(data)) + await self._writer.send(data, binary=True, compress=compress) + + async def send_json( + self, + data: Any, + compress: Optional[int] = None, + *, + dumps: JSONEncoder = DEFAULT_JSON_ENCODER, + ) -> None: + await self.send_str(dumps(data), compress=compress) + + async def close(self, *, code: int = WSCloseCode.OK, message: bytes = b"") -> bool: + # we need to break `receive()` cycle first, + # `close()` may be called from different task + if self._waiting and not self._closing: + assert self._loop is not None + self._close_wait = self._loop.create_future() + self._set_closing() + self._reader.feed_data(WS_CLOSING_MESSAGE, 0) + await self._close_wait + + if not self._closed: + self._set_closed() + try: + await self._writer.close(code, message) + except asyncio.CancelledError: + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._response.close() + raise + except Exception as exc: + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._exception = exc + self._response.close() + return True + + if self._close_code: + self._response.close() + return True + + while True: + try: + async with async_timeout.timeout(self._timeout): + msg = await self._reader.read() + except asyncio.CancelledError: + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._response.close() + raise + except Exception as exc: + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._exception = exc + self._response.close() + return True + + if msg.type is WSMsgType.CLOSE: + self._close_code = msg.data + self._response.close() + return True + else: + return False + + async def receive(self, timeout: Optional[float] = None) -> WSMessage: + receive_timeout = timeout or self._receive_timeout + + while True: + if self._waiting: + raise RuntimeError("Concurrent call to receive() is not allowed") + + if self._closed: + return WS_CLOSED_MESSAGE + elif self._closing: + await self.close() + return WS_CLOSED_MESSAGE + + try: + self._waiting = True + try: + if receive_timeout: + # Entering the context manager and creating + # Timeout() object can take almost 50% of the + # run time in this loop so we avoid it if + # there is no read timeout. + async with async_timeout.timeout(receive_timeout): + msg = await self._reader.read() + else: + msg = await self._reader.read() + self._reset_heartbeat() + finally: + self._waiting = False + if self._close_wait: + set_result(self._close_wait, None) + except (asyncio.CancelledError, asyncio.TimeoutError): + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + raise + except EofStream: + self._close_code = WSCloseCode.OK + await self.close() + return WSMessage(WSMsgType.CLOSED, None, None) + except ClientError: + # Likely ServerDisconnectedError when connection is lost + self._set_closed() + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + return WS_CLOSED_MESSAGE + except WebSocketError as exc: + self._close_code = exc.code + await self.close(code=exc.code) + return WSMessage(WSMsgType.ERROR, exc, None) + except Exception as exc: + self._exception = exc + self._set_closing() + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + await self.close() + return WSMessage(WSMsgType.ERROR, exc, None) + + if msg.type is WSMsgType.CLOSE: + self._set_closing() + self._close_code = msg.data + if not self._closed and self._autoclose: + await self.close() + elif msg.type is WSMsgType.CLOSING: + self._set_closing() + elif msg.type is WSMsgType.PING and self._autoping: + await self.pong(msg.data) + continue + elif msg.type is WSMsgType.PONG and self._autoping: + continue + + return msg + + async def receive_str(self, *, timeout: Optional[float] = None) -> str: + msg = await self.receive(timeout) + if msg.type is not WSMsgType.TEXT: + raise TypeError(f"Received message {msg.type}:{msg.data!r} is not str") + return cast(str, msg.data) + + async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes: + msg = await self.receive(timeout) + if msg.type is not WSMsgType.BINARY: + raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes") + return cast(bytes, msg.data) + + async def receive_json( + self, + *, + loads: JSONDecoder = DEFAULT_JSON_DECODER, + timeout: Optional[float] = None, + ) -> Any: + data = await self.receive_str(timeout=timeout) + return loads(data) + + def __aiter__(self) -> "ClientWebSocketResponse": + return self + + async def __anext__(self) -> WSMessage: + msg = await self.receive() + if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED): + raise StopAsyncIteration + return msg diff --git a/env/Lib/site-packages/aiohttp/compression_utils.py b/env/Lib/site-packages/aiohttp/compression_utils.py new file mode 100644 index 0000000..ab4a2f1 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/compression_utils.py @@ -0,0 +1,159 @@ +import asyncio +import zlib +from concurrent.futures import Executor +from typing import Optional, cast + +try: + try: + import brotlicffi as brotli + except ImportError: + import brotli + + HAS_BROTLI = True +except ImportError: # pragma: no cover + HAS_BROTLI = False + +MAX_SYNC_CHUNK_SIZE = 1024 + + +def encoding_to_mode( + encoding: Optional[str] = None, + suppress_deflate_header: bool = False, +) -> int: + if encoding == "gzip": + return 16 + zlib.MAX_WBITS + + return -zlib.MAX_WBITS if suppress_deflate_header else zlib.MAX_WBITS + + +class ZlibBaseHandler: + def __init__( + self, + mode: int, + executor: Optional[Executor] = None, + max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE, + ): + self._mode = mode + self._executor = executor + self._max_sync_chunk_size = max_sync_chunk_size + + +class ZLibCompressor(ZlibBaseHandler): + def __init__( + self, + encoding: Optional[str] = None, + suppress_deflate_header: bool = False, + level: Optional[int] = None, + wbits: Optional[int] = None, + strategy: int = zlib.Z_DEFAULT_STRATEGY, + executor: Optional[Executor] = None, + max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE, + ): + super().__init__( + mode=( + encoding_to_mode(encoding, suppress_deflate_header) + if wbits is None + else wbits + ), + executor=executor, + max_sync_chunk_size=max_sync_chunk_size, + ) + if level is None: + self._compressor = zlib.compressobj(wbits=self._mode, strategy=strategy) + else: + self._compressor = zlib.compressobj( + wbits=self._mode, strategy=strategy, level=level + ) + self._compress_lock = asyncio.Lock() + + def compress_sync(self, data: bytes) -> bytes: + return self._compressor.compress(data) + + async def compress(self, data: bytes) -> bytes: + async with self._compress_lock: + # To ensure the stream is consistent in the event + # there are multiple writers, we need to lock + # the compressor so that only one writer can + # compress at a time. + if ( + self._max_sync_chunk_size is not None + and len(data) > self._max_sync_chunk_size + ): + return await asyncio.get_event_loop().run_in_executor( + self._executor, self.compress_sync, data + ) + return self.compress_sync(data) + + def flush(self, mode: int = zlib.Z_FINISH) -> bytes: + return self._compressor.flush(mode) + + +class ZLibDecompressor(ZlibBaseHandler): + def __init__( + self, + encoding: Optional[str] = None, + suppress_deflate_header: bool = False, + executor: Optional[Executor] = None, + max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE, + ): + super().__init__( + mode=encoding_to_mode(encoding, suppress_deflate_header), + executor=executor, + max_sync_chunk_size=max_sync_chunk_size, + ) + self._decompressor = zlib.decompressobj(wbits=self._mode) + + def decompress_sync(self, data: bytes, max_length: int = 0) -> bytes: + return self._decompressor.decompress(data, max_length) + + async def decompress(self, data: bytes, max_length: int = 0) -> bytes: + if ( + self._max_sync_chunk_size is not None + and len(data) > self._max_sync_chunk_size + ): + return await asyncio.get_event_loop().run_in_executor( + self._executor, self.decompress_sync, data, max_length + ) + return self.decompress_sync(data, max_length) + + def flush(self, length: int = 0) -> bytes: + return ( + self._decompressor.flush(length) + if length > 0 + else self._decompressor.flush() + ) + + @property + def eof(self) -> bool: + return self._decompressor.eof + + @property + def unconsumed_tail(self) -> bytes: + return self._decompressor.unconsumed_tail + + @property + def unused_data(self) -> bytes: + return self._decompressor.unused_data + + +class BrotliDecompressor: + # Supports both 'brotlipy' and 'Brotli' packages + # since they share an import name. The top branches + # are for 'brotlipy' and bottom branches for 'Brotli' + def __init__(self) -> None: + if not HAS_BROTLI: + raise RuntimeError( + "The brotli decompression is not available. " + "Please install `Brotli` module" + ) + self._obj = brotli.Decompressor() + + def decompress_sync(self, data: bytes) -> bytes: + if hasattr(self._obj, "decompress"): + return cast(bytes, self._obj.decompress(data)) + return cast(bytes, self._obj.process(data)) + + def flush(self) -> bytes: + if hasattr(self._obj, "flush"): + return cast(bytes, self._obj.flush()) + return b"" diff --git a/env/Lib/site-packages/aiohttp/connector.py b/env/Lib/site-packages/aiohttp/connector.py new file mode 100644 index 0000000..04115c3 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/connector.py @@ -0,0 +1,1608 @@ +import asyncio +import functools +import random +import socket +import sys +import traceback +import warnings +from collections import defaultdict, deque +from contextlib import suppress +from http import HTTPStatus +from http.cookies import SimpleCookie +from itertools import cycle, islice +from time import monotonic +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + DefaultDict, + Dict, + Iterator, + List, + Literal, + Optional, + Sequence, + Set, + Tuple, + Type, + Union, + cast, +) + +import aiohappyeyeballs +import attr + +from . import hdrs, helpers +from .abc import AbstractResolver, ResolveResult +from .client_exceptions import ( + ClientConnectionError, + ClientConnectorCertificateError, + ClientConnectorError, + ClientConnectorSSLError, + ClientHttpProxyError, + ClientProxyConnectionError, + ServerFingerprintMismatch, + UnixClientConnectorError, + cert_errors, + ssl_errors, +) +from .client_proto import ResponseHandler +from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params +from .helpers import ( + ceil_timeout, + is_ip_address, + noop, + sentinel, + set_exception, + set_result, +) +from .locks import EventResultOrError +from .resolver import DefaultResolver + +try: + import ssl + + SSLContext = ssl.SSLContext +except ImportError: # pragma: no cover + ssl = None # type: ignore[assignment] + SSLContext = object # type: ignore[misc,assignment] + + +EMPTY_SCHEMA_SET = frozenset({""}) +HTTP_SCHEMA_SET = frozenset({"http", "https"}) +WS_SCHEMA_SET = frozenset({"ws", "wss"}) + +HTTP_AND_EMPTY_SCHEMA_SET = HTTP_SCHEMA_SET | EMPTY_SCHEMA_SET +HIGH_LEVEL_SCHEMA_SET = HTTP_AND_EMPTY_SCHEMA_SET | WS_SCHEMA_SET + + +__all__ = ("BaseConnector", "TCPConnector", "UnixConnector", "NamedPipeConnector") + + +if TYPE_CHECKING: + from .client import ClientTimeout + from .client_reqrep import ConnectionKey + from .tracing import Trace + + +class _DeprecationWaiter: + __slots__ = ("_awaitable", "_awaited") + + def __init__(self, awaitable: Awaitable[Any]) -> None: + self._awaitable = awaitable + self._awaited = False + + def __await__(self) -> Any: + self._awaited = True + return self._awaitable.__await__() + + def __del__(self) -> None: + if not self._awaited: + warnings.warn( + "Connector.close() is a coroutine, " + "please use await connector.close()", + DeprecationWarning, + ) + + +class Connection: + + _source_traceback = None + _transport = None + + def __init__( + self, + connector: "BaseConnector", + key: "ConnectionKey", + protocol: ResponseHandler, + loop: asyncio.AbstractEventLoop, + ) -> None: + self._key = key + self._connector = connector + self._loop = loop + self._protocol: Optional[ResponseHandler] = protocol + self._callbacks: List[Callable[[], None]] = [] + + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + def __repr__(self) -> str: + return f"Connection<{self._key}>" + + def __del__(self, _warnings: Any = warnings) -> None: + if self._protocol is not None: + kwargs = {"source": self} + _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs) + if self._loop.is_closed(): + return + + self._connector._release(self._key, self._protocol, should_close=True) + + context = {"client_connection": self, "message": "Unclosed connection"} + if self._source_traceback is not None: + context["source_traceback"] = self._source_traceback + self._loop.call_exception_handler(context) + + def __bool__(self) -> Literal[True]: + """Force subclasses to not be falsy, to make checks simpler.""" + return True + + @property + def loop(self) -> asyncio.AbstractEventLoop: + warnings.warn( + "connector.loop property is deprecated", DeprecationWarning, stacklevel=2 + ) + return self._loop + + @property + def transport(self) -> Optional[asyncio.Transport]: + if self._protocol is None: + return None + return self._protocol.transport + + @property + def protocol(self) -> Optional[ResponseHandler]: + return self._protocol + + def add_callback(self, callback: Callable[[], None]) -> None: + if callback is not None: + self._callbacks.append(callback) + + def _notify_release(self) -> None: + callbacks, self._callbacks = self._callbacks[:], [] + + for cb in callbacks: + with suppress(Exception): + cb() + + def close(self) -> None: + self._notify_release() + + if self._protocol is not None: + self._connector._release(self._key, self._protocol, should_close=True) + self._protocol = None + + def release(self) -> None: + self._notify_release() + + if self._protocol is not None: + self._connector._release( + self._key, self._protocol, should_close=self._protocol.should_close + ) + self._protocol = None + + @property + def closed(self) -> bool: + return self._protocol is None or not self._protocol.is_connected() + + +class _TransportPlaceholder: + """placeholder for BaseConnector.connect function""" + + def close(self) -> None: + pass + + +class BaseConnector: + """Base connector class. + + keepalive_timeout - (optional) Keep-alive timeout. + force_close - Set to True to force close and do reconnect + after each request (and between redirects). + limit - The total number of simultaneous connections. + limit_per_host - Number of simultaneous connections to one host. + enable_cleanup_closed - Enables clean-up closed ssl transports. + Disabled by default. + timeout_ceil_threshold - Trigger ceiling of timeout values when + it's above timeout_ceil_threshold. + loop - Optional event loop. + """ + + _closed = True # prevent AttributeError in __del__ if ctor was failed + _source_traceback = None + + # abort transport after 2 seconds (cleanup broken connections) + _cleanup_closed_period = 2.0 + + allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET + + def __init__( + self, + *, + keepalive_timeout: Union[object, None, float] = sentinel, + force_close: bool = False, + limit: int = 100, + limit_per_host: int = 0, + enable_cleanup_closed: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, + timeout_ceil_threshold: float = 5, + ) -> None: + + if force_close: + if keepalive_timeout is not None and keepalive_timeout is not sentinel: + raise ValueError( + "keepalive_timeout cannot " "be set if force_close is True" + ) + else: + if keepalive_timeout is sentinel: + keepalive_timeout = 15.0 + + loop = loop or asyncio.get_running_loop() + self._timeout_ceil_threshold = timeout_ceil_threshold + + self._closed = False + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + self._conns: Dict[ConnectionKey, List[Tuple[ResponseHandler, float]]] = {} + self._limit = limit + self._limit_per_host = limit_per_host + self._acquired: Set[ResponseHandler] = set() + self._acquired_per_host: DefaultDict[ConnectionKey, Set[ResponseHandler]] = ( + defaultdict(set) + ) + self._keepalive_timeout = cast(float, keepalive_timeout) + self._force_close = force_close + + # {host_key: FIFO list of waiters} + self._waiters = defaultdict(deque) # type: ignore[var-annotated] + + self._loop = loop + self._factory = functools.partial(ResponseHandler, loop=loop) + + self.cookies = SimpleCookie() + + # start keep-alive connection cleanup task + self._cleanup_handle: Optional[asyncio.TimerHandle] = None + + # start cleanup closed transports task + self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None + self._cleanup_closed_disabled = not enable_cleanup_closed + self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = [] + self._cleanup_closed() + + def __del__(self, _warnings: Any = warnings) -> None: + if self._closed: + return + if not self._conns: + return + + conns = [repr(c) for c in self._conns.values()] + + self._close() + + kwargs = {"source": self} + _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs) + context = { + "connector": self, + "connections": conns, + "message": "Unclosed connector", + } + if self._source_traceback is not None: + context["source_traceback"] = self._source_traceback + self._loop.call_exception_handler(context) + + def __enter__(self) -> "BaseConnector": + warnings.warn( + '"with Connector():" is deprecated, ' + 'use "async with Connector():" instead', + DeprecationWarning, + ) + return self + + def __exit__(self, *exc: Any) -> None: + self._close() + + async def __aenter__(self) -> "BaseConnector": + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + exc_traceback: Optional[TracebackType] = None, + ) -> None: + await self.close() + + @property + def force_close(self) -> bool: + """Ultimately close connection on releasing if True.""" + return self._force_close + + @property + def limit(self) -> int: + """The total number for simultaneous connections. + + If limit is 0 the connector has no limit. + The default limit size is 100. + """ + return self._limit + + @property + def limit_per_host(self) -> int: + """The limit for simultaneous connections to the same endpoint. + + Endpoints are the same if they are have equal + (host, port, is_ssl) triple. + """ + return self._limit_per_host + + def _cleanup(self) -> None: + """Cleanup unused transports.""" + if self._cleanup_handle: + self._cleanup_handle.cancel() + # _cleanup_handle should be unset, otherwise _release() will not + # recreate it ever! + self._cleanup_handle = None + + now = self._loop.time() + timeout = self._keepalive_timeout + + if self._conns: + connections = {} + deadline = now - timeout + for key, conns in self._conns.items(): + alive = [] + for proto, use_time in conns: + if proto.is_connected(): + if use_time - deadline < 0: + transport = proto.transport + proto.close() + if key.is_ssl and not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(transport) + else: + alive.append((proto, use_time)) + else: + transport = proto.transport + proto.close() + if key.is_ssl and not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(transport) + + if alive: + connections[key] = alive + + self._conns = connections + + if self._conns: + self._cleanup_handle = helpers.weakref_handle( + self, + "_cleanup", + timeout, + self._loop, + timeout_ceil_threshold=self._timeout_ceil_threshold, + ) + + def _drop_acquired_per_host( + self, key: "ConnectionKey", val: ResponseHandler + ) -> None: + acquired_per_host = self._acquired_per_host + if key not in acquired_per_host: + return + conns = acquired_per_host[key] + conns.remove(val) + if not conns: + del self._acquired_per_host[key] + + def _cleanup_closed(self) -> None: + """Double confirmation for transport close. + + Some broken ssl servers may leave socket open without proper close. + """ + if self._cleanup_closed_handle: + self._cleanup_closed_handle.cancel() + + for transport in self._cleanup_closed_transports: + if transport is not None: + transport.abort() + + self._cleanup_closed_transports = [] + + if not self._cleanup_closed_disabled: + self._cleanup_closed_handle = helpers.weakref_handle( + self, + "_cleanup_closed", + self._cleanup_closed_period, + self._loop, + timeout_ceil_threshold=self._timeout_ceil_threshold, + ) + + def close(self) -> Awaitable[None]: + """Close all opened transports.""" + self._close() + return _DeprecationWaiter(noop()) + + def _close(self) -> None: + if self._closed: + return + + self._closed = True + + try: + if self._loop.is_closed(): + return + + # cancel cleanup task + if self._cleanup_handle: + self._cleanup_handle.cancel() + + # cancel cleanup close task + if self._cleanup_closed_handle: + self._cleanup_closed_handle.cancel() + + for data in self._conns.values(): + for proto, t0 in data: + proto.close() + + for proto in self._acquired: + proto.close() + + for transport in self._cleanup_closed_transports: + if transport is not None: + transport.abort() + + finally: + self._conns.clear() + self._acquired.clear() + self._waiters.clear() + self._cleanup_handle = None + self._cleanup_closed_transports.clear() + self._cleanup_closed_handle = None + + @property + def closed(self) -> bool: + """Is connector closed. + + A readonly property. + """ + return self._closed + + def _available_connections(self, key: "ConnectionKey") -> int: + """ + Return number of available connections. + + The limit, limit_per_host and the connection key are taken into account. + + If it returns less than 1 means that there are no connections + available. + """ + if self._limit: + # total calc available connections + available = self._limit - len(self._acquired) + + # check limit per host + if ( + self._limit_per_host + and available > 0 + and key in self._acquired_per_host + ): + acquired = self._acquired_per_host.get(key) + assert acquired is not None + available = self._limit_per_host - len(acquired) + + elif self._limit_per_host and key in self._acquired_per_host: + # check limit per host + acquired = self._acquired_per_host.get(key) + assert acquired is not None + available = self._limit_per_host - len(acquired) + else: + available = 1 + + return available + + async def connect( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> Connection: + """Get from pool or create new connection.""" + key = req.connection_key + available = self._available_connections(key) + + # Wait if there are no available connections or if there are/were + # waiters (i.e. don't steal connection from a waiter about to wake up) + if available <= 0 or key in self._waiters: + fut = self._loop.create_future() + + # This connection will now count towards the limit. + self._waiters[key].append(fut) + + if traces: + for trace in traces: + await trace.send_connection_queued_start() + + try: + await fut + except BaseException as e: + if key in self._waiters: + # remove a waiter even if it was cancelled, normally it's + # removed when it's notified + try: + self._waiters[key].remove(fut) + except ValueError: # fut may no longer be in list + pass + + raise e + finally: + if key in self._waiters and not self._waiters[key]: + del self._waiters[key] + + if traces: + for trace in traces: + await trace.send_connection_queued_end() + + proto = self._get(key) + if proto is None: + placeholder = cast(ResponseHandler, _TransportPlaceholder()) + self._acquired.add(placeholder) + self._acquired_per_host[key].add(placeholder) + + if traces: + for trace in traces: + await trace.send_connection_create_start() + + try: + proto = await self._create_connection(req, traces, timeout) + if self._closed: + proto.close() + raise ClientConnectionError("Connector is closed.") + except BaseException: + if not self._closed: + self._acquired.remove(placeholder) + self._drop_acquired_per_host(key, placeholder) + self._release_waiter() + raise + else: + if not self._closed: + self._acquired.remove(placeholder) + self._drop_acquired_per_host(key, placeholder) + + if traces: + for trace in traces: + await trace.send_connection_create_end() + else: + if traces: + # Acquire the connection to prevent race conditions with limits + placeholder = cast(ResponseHandler, _TransportPlaceholder()) + self._acquired.add(placeholder) + self._acquired_per_host[key].add(placeholder) + for trace in traces: + await trace.send_connection_reuseconn() + self._acquired.remove(placeholder) + self._drop_acquired_per_host(key, placeholder) + + self._acquired.add(proto) + self._acquired_per_host[key].add(proto) + return Connection(self, key, proto, self._loop) + + def _get(self, key: "ConnectionKey") -> Optional[ResponseHandler]: + try: + conns = self._conns[key] + except KeyError: + return None + + t1 = self._loop.time() + while conns: + proto, t0 = conns.pop() + if proto.is_connected(): + if t1 - t0 > self._keepalive_timeout: + transport = proto.transport + proto.close() + # only for SSL transports + if key.is_ssl and not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(transport) + else: + if not conns: + # The very last connection was reclaimed: drop the key + del self._conns[key] + return proto + else: + transport = proto.transport + proto.close() + if key.is_ssl and not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(transport) + + # No more connections: drop the key + del self._conns[key] + return None + + def _release_waiter(self) -> None: + """ + Iterates over all waiters until one to be released is found. + + The one to be released is not finished and + belongs to a host that has available connections. + """ + if not self._waiters: + return + + # Having the dict keys ordered this avoids to iterate + # at the same order at each call. + queues = list(self._waiters.keys()) + random.shuffle(queues) + + for key in queues: + if self._available_connections(key) < 1: + continue + + waiters = self._waiters[key] + while waiters: + waiter = waiters.popleft() + if not waiter.done(): + waiter.set_result(None) + return + + def _release_acquired(self, key: "ConnectionKey", proto: ResponseHandler) -> None: + if self._closed: + # acquired connection is already released on connector closing + return + + try: + self._acquired.remove(proto) + self._drop_acquired_per_host(key, proto) + except KeyError: # pragma: no cover + # this may be result of undetermenistic order of objects + # finalization due garbage collection. + pass + else: + self._release_waiter() + + def _release( + self, + key: "ConnectionKey", + protocol: ResponseHandler, + *, + should_close: bool = False, + ) -> None: + if self._closed: + # acquired connection is already released on connector closing + return + + self._release_acquired(key, protocol) + + if self._force_close: + should_close = True + + if should_close or protocol.should_close: + transport = protocol.transport + protocol.close() + + if key.is_ssl and not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(transport) + else: + conns = self._conns.get(key) + if conns is None: + conns = self._conns[key] = [] + conns.append((protocol, self._loop.time())) + + if self._cleanup_handle is None: + self._cleanup_handle = helpers.weakref_handle( + self, + "_cleanup", + self._keepalive_timeout, + self._loop, + timeout_ceil_threshold=self._timeout_ceil_threshold, + ) + + async def _create_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> ResponseHandler: + raise NotImplementedError() + + +class _DNSCacheTable: + def __init__(self, ttl: Optional[float] = None) -> None: + self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[ResolveResult], int]] = {} + self._timestamps: Dict[Tuple[str, int], float] = {} + self._ttl = ttl + + def __contains__(self, host: object) -> bool: + return host in self._addrs_rr + + def add(self, key: Tuple[str, int], addrs: List[ResolveResult]) -> None: + self._addrs_rr[key] = (cycle(addrs), len(addrs)) + + if self._ttl is not None: + self._timestamps[key] = monotonic() + + def remove(self, key: Tuple[str, int]) -> None: + self._addrs_rr.pop(key, None) + + if self._ttl is not None: + self._timestamps.pop(key, None) + + def clear(self) -> None: + self._addrs_rr.clear() + self._timestamps.clear() + + def next_addrs(self, key: Tuple[str, int]) -> List[ResolveResult]: + loop, length = self._addrs_rr[key] + addrs = list(islice(loop, length)) + # Consume one more element to shift internal state of `cycle` + next(loop) + return addrs + + def expired(self, key: Tuple[str, int]) -> bool: + if self._ttl is None: + return False + + return self._timestamps[key] + self._ttl < monotonic() + + +class TCPConnector(BaseConnector): + """TCP connector. + + verify_ssl - Set to True to check ssl certifications. + fingerprint - Pass the binary sha256 + digest of the expected certificate in DER format to verify + that the certificate the server presents matches. See also + https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning + resolver - Enable DNS lookups and use this + resolver + use_dns_cache - Use memory cache for DNS lookups. + ttl_dns_cache - Max seconds having cached a DNS entry, None forever. + family - socket address family + local_addr - local tuple of (host, port) to bind socket to + + keepalive_timeout - (optional) Keep-alive timeout. + force_close - Set to True to force close and do reconnect + after each request (and between redirects). + limit - The total number of simultaneous connections. + limit_per_host - Number of simultaneous connections to one host. + enable_cleanup_closed - Enables clean-up closed ssl transports. + Disabled by default. + happy_eyeballs_delay - This is the “Connection Attempt Delay” + as defined in RFC 8305. To disable + the happy eyeballs algorithm, set to None. + interleave - “First Address Family Count” as defined in RFC 8305 + loop - Optional event loop. + """ + + allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"tcp"}) + _made_ssl_context: Dict[bool, "asyncio.Future[SSLContext]"] = {} + + def __init__( + self, + *, + verify_ssl: bool = True, + fingerprint: Optional[bytes] = None, + use_dns_cache: bool = True, + ttl_dns_cache: Optional[int] = 10, + family: socket.AddressFamily = socket.AddressFamily.AF_UNSPEC, + ssl_context: Optional[SSLContext] = None, + ssl: Union[bool, Fingerprint, SSLContext] = True, + local_addr: Optional[Tuple[str, int]] = None, + resolver: Optional[AbstractResolver] = None, + keepalive_timeout: Union[None, float, object] = sentinel, + force_close: bool = False, + limit: int = 100, + limit_per_host: int = 0, + enable_cleanup_closed: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, + timeout_ceil_threshold: float = 5, + happy_eyeballs_delay: Optional[float] = 0.25, + interleave: Optional[int] = None, + ): + super().__init__( + keepalive_timeout=keepalive_timeout, + force_close=force_close, + limit=limit, + limit_per_host=limit_per_host, + enable_cleanup_closed=enable_cleanup_closed, + loop=loop, + timeout_ceil_threshold=timeout_ceil_threshold, + ) + + self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) + if resolver is None: + resolver = DefaultResolver(loop=self._loop) + self._resolver = resolver + + self._use_dns_cache = use_dns_cache + self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache) + self._throttle_dns_events: Dict[Tuple[str, int], EventResultOrError] = {} + self._family = family + self._local_addr_infos = aiohappyeyeballs.addr_to_addr_infos(local_addr) + self._happy_eyeballs_delay = happy_eyeballs_delay + self._interleave = interleave + + def close(self) -> Awaitable[None]: + """Close all ongoing DNS calls.""" + for ev in self._throttle_dns_events.values(): + ev.cancel() + + return super().close() + + @property + def family(self) -> int: + """Socket family like AF_INET.""" + return self._family + + @property + def use_dns_cache(self) -> bool: + """True if local DNS caching is enabled.""" + return self._use_dns_cache + + def clear_dns_cache( + self, host: Optional[str] = None, port: Optional[int] = None + ) -> None: + """Remove specified host/port or clear all dns local cache.""" + if host is not None and port is not None: + self._cached_hosts.remove((host, port)) + elif host is not None or port is not None: + raise ValueError("either both host and port " "or none of them are allowed") + else: + self._cached_hosts.clear() + + async def _resolve_host( + self, host: str, port: int, traces: Optional[Sequence["Trace"]] = None + ) -> List[ResolveResult]: + """Resolve host and return list of addresses.""" + if is_ip_address(host): + return [ + { + "hostname": host, + "host": host, + "port": port, + "family": self._family, + "proto": 0, + "flags": 0, + } + ] + + if not self._use_dns_cache: + + if traces: + for trace in traces: + await trace.send_dns_resolvehost_start(host) + + res = await self._resolver.resolve(host, port, family=self._family) + + if traces: + for trace in traces: + await trace.send_dns_resolvehost_end(host) + + return res + + key = (host, port) + if key in self._cached_hosts and not self._cached_hosts.expired(key): + # get result early, before any await (#4014) + result = self._cached_hosts.next_addrs(key) + + if traces: + for trace in traces: + await trace.send_dns_cache_hit(host) + return result + + # + # If multiple connectors are resolving the same host, we wait + # for the first one to resolve and then use the result for all of them. + # We use a throttle event to ensure that we only resolve the host once + # and then use the result for all the waiters. + # + # In this case we need to create a task to ensure that we can shield + # the task from cancellation as cancelling this lookup should not cancel + # the underlying lookup or else the cancel event will get broadcast to + # all the waiters across all connections. + # + resolved_host_task = asyncio.create_task( + self._resolve_host_with_throttle(key, host, port, traces) + ) + try: + return await asyncio.shield(resolved_host_task) + except asyncio.CancelledError: + + def drop_exception(fut: "asyncio.Future[List[ResolveResult]]") -> None: + with suppress(Exception, asyncio.CancelledError): + fut.result() + + resolved_host_task.add_done_callback(drop_exception) + raise + + async def _resolve_host_with_throttle( + self, + key: Tuple[str, int], + host: str, + port: int, + traces: Optional[Sequence["Trace"]], + ) -> List[ResolveResult]: + """Resolve host with a dns events throttle.""" + if key in self._throttle_dns_events: + # get event early, before any await (#4014) + event = self._throttle_dns_events[key] + if traces: + for trace in traces: + await trace.send_dns_cache_hit(host) + await event.wait() + else: + # update dict early, before any await (#4014) + self._throttle_dns_events[key] = EventResultOrError(self._loop) + if traces: + for trace in traces: + await trace.send_dns_cache_miss(host) + try: + + if traces: + for trace in traces: + await trace.send_dns_resolvehost_start(host) + + addrs = await self._resolver.resolve(host, port, family=self._family) + if traces: + for trace in traces: + await trace.send_dns_resolvehost_end(host) + + self._cached_hosts.add(key, addrs) + self._throttle_dns_events[key].set() + except BaseException as e: + # any DNS exception, independently of the implementation + # is set for the waiters to raise the same exception. + self._throttle_dns_events[key].set(exc=e) + raise + finally: + self._throttle_dns_events.pop(key) + + return self._cached_hosts.next_addrs(key) + + async def _create_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> ResponseHandler: + """Create connection. + + Has same keyword arguments as BaseEventLoop.create_connection. + """ + if req.proxy: + _, proto = await self._create_proxy_connection(req, traces, timeout) + else: + _, proto = await self._create_direct_connection(req, traces, timeout) + + return proto + + @staticmethod + def _make_ssl_context(verified: bool) -> SSLContext: + """Create SSL context. + + This method is not async-friendly and should be called from a thread + because it will load certificates from disk and do other blocking I/O. + """ + if verified: + return ssl.create_default_context() + sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + sslcontext.options |= ssl.OP_NO_SSLv2 + sslcontext.options |= ssl.OP_NO_SSLv3 + sslcontext.check_hostname = False + sslcontext.verify_mode = ssl.CERT_NONE + sslcontext.options |= ssl.OP_NO_COMPRESSION + sslcontext.set_default_verify_paths() + return sslcontext + + async def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]: + """Logic to get the correct SSL context + + 0. if req.ssl is false, return None + + 1. if ssl_context is specified in req, use it + 2. if _ssl_context is specified in self, use it + 3. otherwise: + 1. if verify_ssl is not specified in req, use self.ssl_context + (will generate a default context according to self.verify_ssl) + 2. if verify_ssl is True in req, generate a default SSL context + 3. if verify_ssl is False in req, generate a SSL context that + won't verify + """ + if not req.is_ssl(): + return None + + if ssl is None: # pragma: no cover + raise RuntimeError("SSL is not supported.") + sslcontext = req.ssl + if isinstance(sslcontext, ssl.SSLContext): + return sslcontext + if sslcontext is not True: + # not verified or fingerprinted + return await self._make_or_get_ssl_context(False) + sslcontext = self._ssl + if isinstance(sslcontext, ssl.SSLContext): + return sslcontext + if sslcontext is not True: + # not verified or fingerprinted + return await self._make_or_get_ssl_context(False) + return await self._make_or_get_ssl_context(True) + + async def _make_or_get_ssl_context(self, verified: bool) -> SSLContext: + """Create or get cached SSL context.""" + try: + return await self._made_ssl_context[verified] + except KeyError: + loop = self._loop + future = loop.create_future() + self._made_ssl_context[verified] = future + try: + result = await loop.run_in_executor( + None, self._make_ssl_context, verified + ) + # BaseException is used since we might get CancelledError + except BaseException as ex: + del self._made_ssl_context[verified] + set_exception(future, ex) + raise + else: + set_result(future, result) + return result + + def _get_fingerprint(self, req: ClientRequest) -> Optional["Fingerprint"]: + ret = req.ssl + if isinstance(ret, Fingerprint): + return ret + ret = self._ssl + if isinstance(ret, Fingerprint): + return ret + return None + + async def _wrap_create_connection( + self, + *args: Any, + addr_infos: List[aiohappyeyeballs.AddrInfoType], + req: ClientRequest, + timeout: "ClientTimeout", + client_error: Type[Exception] = ClientConnectorError, + **kwargs: Any, + ) -> Tuple[asyncio.Transport, ResponseHandler]: + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + sock = await aiohappyeyeballs.start_connection( + addr_infos=addr_infos, + local_addr_infos=self._local_addr_infos, + happy_eyeballs_delay=self._happy_eyeballs_delay, + interleave=self._interleave, + loop=self._loop, + ) + return await self._loop.create_connection(*args, **kwargs, sock=sock) + except cert_errors as exc: + raise ClientConnectorCertificateError(req.connection_key, exc) from exc + except ssl_errors as exc: + raise ClientConnectorSSLError(req.connection_key, exc) from exc + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise client_error(req.connection_key, exc) from exc + + async def _wrap_existing_connection( + self, + *args: Any, + req: ClientRequest, + timeout: "ClientTimeout", + client_error: Type[Exception] = ClientConnectorError, + **kwargs: Any, + ) -> Tuple[asyncio.Transport, ResponseHandler]: + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + return await self._loop.create_connection(*args, **kwargs) + except cert_errors as exc: + raise ClientConnectorCertificateError(req.connection_key, exc) from exc + except ssl_errors as exc: + raise ClientConnectorSSLError(req.connection_key, exc) from exc + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise client_error(req.connection_key, exc) from exc + + def _fail_on_no_start_tls(self, req: "ClientRequest") -> None: + """Raise a :py:exc:`RuntimeError` on missing ``start_tls()``. + + It is necessary for TLS-in-TLS so that it is possible to + send HTTPS queries through HTTPS proxies. + + This doesn't affect regular HTTP requests, though. + """ + if not req.is_ssl(): + return + + proxy_url = req.proxy + assert proxy_url is not None + if proxy_url.scheme != "https": + return + + self._check_loop_for_start_tls() + + def _check_loop_for_start_tls(self) -> None: + try: + self._loop.start_tls + except AttributeError as attr_exc: + raise RuntimeError( + "An HTTPS request is being sent through an HTTPS proxy. " + "This needs support for TLS in TLS but it is not implemented " + "in your runtime for the stdlib asyncio.\n\n" + "Please upgrade to Python 3.11 or higher. For more details, " + "please see:\n" + "* https://bugs.python.org/issue37179\n" + "* https://github.com/python/cpython/pull/28073\n" + "* https://docs.aiohttp.org/en/stable/" + "client_advanced.html#proxy-support\n" + "* https://github.com/aio-libs/aiohttp/discussions/6044\n", + ) from attr_exc + + def _loop_supports_start_tls(self) -> bool: + try: + self._check_loop_for_start_tls() + except RuntimeError: + return False + else: + return True + + def _warn_about_tls_in_tls( + self, + underlying_transport: asyncio.Transport, + req: ClientRequest, + ) -> None: + """Issue a warning if the requested URL has HTTPS scheme.""" + if req.request_info.url.scheme != "https": + return + + asyncio_supports_tls_in_tls = getattr( + underlying_transport, + "_start_tls_compatible", + False, + ) + + if asyncio_supports_tls_in_tls: + return + + warnings.warn( + "An HTTPS request is being sent through an HTTPS proxy. " + "This support for TLS in TLS is known to be disabled " + "in the stdlib asyncio (Python <3.11). This is why you'll probably see " + "an error in the log below.\n\n" + "It is possible to enable it via monkeypatching. " + "For more details, see:\n" + "* https://bugs.python.org/issue37179\n" + "* https://github.com/python/cpython/pull/28073\n\n" + "You can temporarily patch this as follows:\n" + "* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\n" + "* https://github.com/aio-libs/aiohttp/discussions/6044\n", + RuntimeWarning, + source=self, + # Why `4`? At least 3 of the calls in the stack originate + # from the methods in this class. + stacklevel=3, + ) + + async def _start_tls_connection( + self, + underlying_transport: asyncio.Transport, + req: ClientRequest, + timeout: "ClientTimeout", + client_error: Type[Exception] = ClientConnectorError, + ) -> Tuple[asyncio.BaseTransport, ResponseHandler]: + """Wrap the raw TCP transport with TLS.""" + tls_proto = self._factory() # Create a brand new proto for TLS + + # Safety of the `cast()` call here is based on the fact that + # internally `_get_ssl_context()` only returns `None` when + # `req.is_ssl()` evaluates to `False` which is never gonna happen + # in this code path. Of course, it's rather fragile + # maintainability-wise but this is to be solved separately. + sslcontext = cast(ssl.SSLContext, await self._get_ssl_context(req)) + + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + try: + tls_transport = await self._loop.start_tls( + underlying_transport, + tls_proto, + sslcontext, + server_hostname=req.server_hostname or req.host, + ssl_handshake_timeout=timeout.total, + ) + except BaseException: + # We need to close the underlying transport since + # `start_tls()` probably failed before it had a + # chance to do this: + underlying_transport.close() + raise + except cert_errors as exc: + raise ClientConnectorCertificateError(req.connection_key, exc) from exc + except ssl_errors as exc: + raise ClientConnectorSSLError(req.connection_key, exc) from exc + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise client_error(req.connection_key, exc) from exc + except TypeError as type_err: + # Example cause looks like this: + # TypeError: transport is not supported by start_tls() + + raise ClientConnectionError( + "Cannot initialize a TLS-in-TLS connection to host " + f"{req.host!s}:{req.port:d} through an underlying connection " + f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} " + f"[{type_err!s}]" + ) from type_err + else: + if tls_transport is None: + msg = "Failed to start TLS (possibly caused by closing transport)" + raise client_error(req.connection_key, OSError(msg)) + tls_proto.connection_made( + tls_transport + ) # Kick the state machine of the new TLS protocol + + return tls_transport, tls_proto + + def _convert_hosts_to_addr_infos( + self, hosts: List[ResolveResult] + ) -> List[aiohappyeyeballs.AddrInfoType]: + """Converts the list of hosts to a list of addr_infos. + + The list of hosts is the result of a DNS lookup. The list of + addr_infos is the result of a call to `socket.getaddrinfo()`. + """ + addr_infos: List[aiohappyeyeballs.AddrInfoType] = [] + for hinfo in hosts: + host = hinfo["host"] + is_ipv6 = ":" in host + family = socket.AF_INET6 if is_ipv6 else socket.AF_INET + if self._family and self._family != family: + continue + addr = (host, hinfo["port"], 0, 0) if is_ipv6 else (host, hinfo["port"]) + addr_infos.append( + (family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr) + ) + return addr_infos + + async def _create_direct_connection( + self, + req: ClientRequest, + traces: List["Trace"], + timeout: "ClientTimeout", + *, + client_error: Type[Exception] = ClientConnectorError, + ) -> Tuple[asyncio.Transport, ResponseHandler]: + sslcontext = await self._get_ssl_context(req) + fingerprint = self._get_fingerprint(req) + + host = req.url.raw_host + assert host is not None + # Replace multiple trailing dots with a single one. + # A trailing dot is only present for fully-qualified domain names. + # See https://github.com/aio-libs/aiohttp/pull/7364. + if host.endswith(".."): + host = host.rstrip(".") + "." + port = req.port + assert port is not None + try: + # Cancelling this lookup should not cancel the underlying lookup + # or else the cancel event will get broadcast to all the waiters + # across all connections. + hosts = await self._resolve_host(host, port, traces=traces) + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + # in case of proxy it is not ClientProxyConnectionError + # it is problem of resolving proxy ip itself + raise ClientConnectorError(req.connection_key, exc) from exc + + last_exc: Optional[Exception] = None + addr_infos = self._convert_hosts_to_addr_infos(hosts) + while addr_infos: + # Strip trailing dots, certificates contain FQDN without dots. + # See https://github.com/aio-libs/aiohttp/issues/3636 + server_hostname = ( + (req.server_hostname or host).rstrip(".") if sslcontext else None + ) + + try: + transp, proto = await self._wrap_create_connection( + self._factory, + timeout=timeout, + ssl=sslcontext, + addr_infos=addr_infos, + server_hostname=server_hostname, + req=req, + client_error=client_error, + ) + except ClientConnectorError as exc: + last_exc = exc + aiohappyeyeballs.pop_addr_infos_interleave(addr_infos, self._interleave) + continue + + if req.is_ssl() and fingerprint: + try: + fingerprint.check(transp) + except ServerFingerprintMismatch as exc: + transp.close() + if not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(transp) + last_exc = exc + # Remove the bad peer from the list of addr_infos + sock: socket.socket = transp.get_extra_info("socket") + bad_peer = sock.getpeername() + aiohappyeyeballs.remove_addr_infos(addr_infos, bad_peer) + continue + + return transp, proto + else: + assert last_exc is not None + raise last_exc + + async def _create_proxy_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> Tuple[asyncio.BaseTransport, ResponseHandler]: + self._fail_on_no_start_tls(req) + runtime_has_start_tls = self._loop_supports_start_tls() + + headers: Dict[str, str] = {} + if req.proxy_headers is not None: + headers = req.proxy_headers # type: ignore[assignment] + headers[hdrs.HOST] = req.headers[hdrs.HOST] + + url = req.proxy + assert url is not None + proxy_req = ClientRequest( + hdrs.METH_GET, + url, + headers=headers, + auth=req.proxy_auth, + loop=self._loop, + ssl=req.ssl, + ) + + # create connection to proxy server + transport, proto = await self._create_direct_connection( + proxy_req, [], timeout, client_error=ClientProxyConnectionError + ) + + # Many HTTP proxies has buggy keepalive support. Let's not + # reuse connection but close it after processing every + # response. + proto.force_close() + + auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None) + if auth is not None: + if not req.is_ssl(): + req.headers[hdrs.PROXY_AUTHORIZATION] = auth + else: + proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth + + if req.is_ssl(): + if runtime_has_start_tls: + self._warn_about_tls_in_tls(transport, req) + + # For HTTPS requests over HTTP proxy + # we must notify proxy to tunnel connection + # so we send CONNECT command: + # CONNECT www.python.org:443 HTTP/1.1 + # Host: www.python.org + # + # next we must do TLS handshake and so on + # to do this we must wrap raw socket into secure one + # asyncio handles this perfectly + proxy_req.method = hdrs.METH_CONNECT + proxy_req.url = req.url + key = attr.evolve( + req.connection_key, proxy=None, proxy_auth=None, proxy_headers_hash=None + ) + conn = Connection(self, key, proto, self._loop) + proxy_resp = await proxy_req.send(conn) + try: + protocol = conn._protocol + assert protocol is not None + + # read_until_eof=True will ensure the connection isn't closed + # once the response is received and processed allowing + # START_TLS to work on the connection below. + protocol.set_response_params( + read_until_eof=runtime_has_start_tls, + timeout_ceil_threshold=self._timeout_ceil_threshold, + ) + resp = await proxy_resp.start(conn) + except BaseException: + proxy_resp.close() + conn.close() + raise + else: + conn._protocol = None + conn._transport = None + try: + if resp.status != 200: + message = resp.reason + if message is None: + message = HTTPStatus(resp.status).phrase + raise ClientHttpProxyError( + proxy_resp.request_info, + resp.history, + status=resp.status, + message=message, + headers=resp.headers, + ) + if not runtime_has_start_tls: + rawsock = transport.get_extra_info("socket", default=None) + if rawsock is None: + raise RuntimeError( + "Transport does not expose socket instance" + ) + # Duplicate the socket, so now we can close proxy transport + rawsock = rawsock.dup() + except BaseException: + # It shouldn't be closed in `finally` because it's fed to + # `loop.start_tls()` and the docs say not to touch it after + # passing there. + transport.close() + raise + finally: + if not runtime_has_start_tls: + transport.close() + + if not runtime_has_start_tls: + # HTTP proxy with support for upgrade to HTTPS + sslcontext = self._get_ssl_context(req) + return await self._wrap_existing_connection( + self._factory, + timeout=timeout, + ssl=sslcontext, + sock=rawsock, + server_hostname=req.host, + req=req, + ) + + return await self._start_tls_connection( + # Access the old transport for the last time before it's + # closed and forgotten forever: + transport, + req=req, + timeout=timeout, + ) + finally: + proxy_resp.close() + + return transport, proto + + +class UnixConnector(BaseConnector): + """Unix socket connector. + + path - Unix socket path. + keepalive_timeout - (optional) Keep-alive timeout. + force_close - Set to True to force close and do reconnect + after each request (and between redirects). + limit - The total number of simultaneous connections. + limit_per_host - Number of simultaneous connections to one host. + loop - Optional event loop. + """ + + allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"unix"}) + + def __init__( + self, + path: str, + force_close: bool = False, + keepalive_timeout: Union[object, float, None] = sentinel, + limit: int = 100, + limit_per_host: int = 0, + loop: Optional[asyncio.AbstractEventLoop] = None, + ) -> None: + super().__init__( + force_close=force_close, + keepalive_timeout=keepalive_timeout, + limit=limit, + limit_per_host=limit_per_host, + loop=loop, + ) + self._path = path + + @property + def path(self) -> str: + """Path to unix socket.""" + return self._path + + async def _create_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> ResponseHandler: + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + _, proto = await self._loop.create_unix_connection( + self._factory, self._path + ) + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc + + return proto + + +class NamedPipeConnector(BaseConnector): + """Named pipe connector. + + Only supported by the proactor event loop. + See also: https://docs.python.org/3/library/asyncio-eventloop.html + + path - Windows named pipe path. + keepalive_timeout - (optional) Keep-alive timeout. + force_close - Set to True to force close and do reconnect + after each request (and between redirects). + limit - The total number of simultaneous connections. + limit_per_host - Number of simultaneous connections to one host. + loop - Optional event loop. + """ + + allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"npipe"}) + + def __init__( + self, + path: str, + force_close: bool = False, + keepalive_timeout: Union[object, float, None] = sentinel, + limit: int = 100, + limit_per_host: int = 0, + loop: Optional[asyncio.AbstractEventLoop] = None, + ) -> None: + super().__init__( + force_close=force_close, + keepalive_timeout=keepalive_timeout, + limit=limit, + limit_per_host=limit_per_host, + loop=loop, + ) + if not isinstance( + self._loop, asyncio.ProactorEventLoop # type: ignore[attr-defined] + ): + raise RuntimeError( + "Named Pipes only available in proactor " "loop under windows" + ) + self._path = path + + @property + def path(self) -> str: + """Path to the named pipe.""" + return self._path + + async def _create_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> ResponseHandler: + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + _, proto = await self._loop.create_pipe_connection( # type: ignore[attr-defined] + self._factory, self._path + ) + # the drain is required so that the connection_made is called + # and transport is set otherwise it is not set before the + # `assert conn.transport is not None` + # in client.py's _request method + await asyncio.sleep(0) + # other option is to manually set transport like + # `proto.transport = trans` + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise ClientConnectorError(req.connection_key, exc) from exc + + return cast(ResponseHandler, proto) diff --git a/env/Lib/site-packages/aiohttp/cookiejar.py b/env/Lib/site-packages/aiohttp/cookiejar.py new file mode 100644 index 0000000..e9997ce --- /dev/null +++ b/env/Lib/site-packages/aiohttp/cookiejar.py @@ -0,0 +1,425 @@ +import asyncio +import calendar +import contextlib +import datetime +import itertools +import os # noqa +import pathlib +import pickle +import re +import time +from collections import defaultdict +from http.cookies import BaseCookie, Morsel, SimpleCookie +from math import ceil +from typing import ( + DefaultDict, + Dict, + Iterable, + Iterator, + List, + Mapping, + Optional, + Set, + Tuple, + Union, + cast, +) + +from yarl import URL + +from .abc import AbstractCookieJar, ClearCookiePredicate +from .helpers import is_ip_address +from .typedefs import LooseCookies, PathLike, StrOrURL + +__all__ = ("CookieJar", "DummyCookieJar") + + +CookieItem = Union[str, "Morsel[str]"] + +# We cache these string methods here as their use is in performance critical code. +_FORMAT_PATH = "{}/{}".format +_FORMAT_DOMAIN_REVERSED = "{1}.{0}".format + + +class CookieJar(AbstractCookieJar): + """Implements cookie storage adhering to RFC 6265.""" + + DATE_TOKENS_RE = re.compile( + r"[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]*" + r"(?P[\x00-\x08\x0A-\x1F\d:a-zA-Z\x7F-\xFF]+)" + ) + + DATE_HMS_TIME_RE = re.compile(r"(\d{1,2}):(\d{1,2}):(\d{1,2})") + + DATE_DAY_OF_MONTH_RE = re.compile(r"(\d{1,2})") + + DATE_MONTH_RE = re.compile( + "(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|" "(aug)|(sep)|(oct)|(nov)|(dec)", + re.I, + ) + + DATE_YEAR_RE = re.compile(r"(\d{2,4})") + + # calendar.timegm() fails for timestamps after datetime.datetime.max + # Minus one as a loss of precision occurs when timestamp() is called. + MAX_TIME = ( + int(datetime.datetime.max.replace(tzinfo=datetime.timezone.utc).timestamp()) - 1 + ) + try: + calendar.timegm(time.gmtime(MAX_TIME)) + except (OSError, ValueError): + # Hit the maximum representable time on Windows + # https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-localtime32-localtime64 + # Throws ValueError on PyPy 3.8 and 3.9, OSError elsewhere + MAX_TIME = calendar.timegm((3000, 12, 31, 23, 59, 59, -1, -1, -1)) + except OverflowError: + # #4515: datetime.max may not be representable on 32-bit platforms + MAX_TIME = 2**31 - 1 + # Avoid minuses in the future, 3x faster + SUB_MAX_TIME = MAX_TIME - 1 + + def __init__( + self, + *, + unsafe: bool = False, + quote_cookie: bool = True, + treat_as_secure_origin: Union[StrOrURL, List[StrOrURL], None] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + ) -> None: + super().__init__(loop=loop) + self._cookies: DefaultDict[Tuple[str, str], SimpleCookie] = defaultdict( + SimpleCookie + ) + self._host_only_cookies: Set[Tuple[str, str]] = set() + self._unsafe = unsafe + self._quote_cookie = quote_cookie + if treat_as_secure_origin is None: + treat_as_secure_origin = [] + elif isinstance(treat_as_secure_origin, URL): + treat_as_secure_origin = [treat_as_secure_origin.origin()] + elif isinstance(treat_as_secure_origin, str): + treat_as_secure_origin = [URL(treat_as_secure_origin).origin()] + else: + treat_as_secure_origin = [ + URL(url).origin() if isinstance(url, str) else url.origin() + for url in treat_as_secure_origin + ] + self._treat_as_secure_origin = treat_as_secure_origin + self._next_expiration: float = ceil(time.time()) + self._expirations: Dict[Tuple[str, str, str], float] = {} + + def save(self, file_path: PathLike) -> None: + file_path = pathlib.Path(file_path) + with file_path.open(mode="wb") as f: + pickle.dump(self._cookies, f, pickle.HIGHEST_PROTOCOL) + + def load(self, file_path: PathLike) -> None: + file_path = pathlib.Path(file_path) + with file_path.open(mode="rb") as f: + self._cookies = pickle.load(f) + + def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: + if predicate is None: + self._next_expiration = ceil(time.time()) + self._cookies.clear() + self._host_only_cookies.clear() + self._expirations.clear() + return + + to_del = [] + now = time.time() + for (domain, path), cookie in self._cookies.items(): + for name, morsel in cookie.items(): + key = (domain, path, name) + if ( + key in self._expirations and self._expirations[key] <= now + ) or predicate(morsel): + to_del.append(key) + + for domain, path, name in to_del: + self._host_only_cookies.discard((domain, name)) + key = (domain, path, name) + if key in self._expirations: + del self._expirations[(domain, path, name)] + self._cookies[(domain, path)].pop(name, None) + + self._next_expiration = ( + min(*self._expirations.values(), self.SUB_MAX_TIME) + 1 + if self._expirations + else self.MAX_TIME + ) + + def clear_domain(self, domain: str) -> None: + self.clear(lambda x: self._is_domain_match(domain, x["domain"])) + + def __iter__(self) -> "Iterator[Morsel[str]]": + self._do_expiration() + for val in self._cookies.values(): + yield from val.values() + + def __len__(self) -> int: + """Return number of cookies. + + This function does not iterate self to avoid unnecessary expiration + checks. + """ + return sum(len(cookie.values()) for cookie in self._cookies.values()) + + def _do_expiration(self) -> None: + self.clear(lambda x: False) + + def _expire_cookie(self, when: float, domain: str, path: str, name: str) -> None: + self._next_expiration = min(self._next_expiration, when) + self._expirations[(domain, path, name)] = when + + def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: + """Update cookies.""" + hostname = response_url.raw_host + + if not self._unsafe and is_ip_address(hostname): + # Don't accept cookies from IPs + return + + if isinstance(cookies, Mapping): + cookies = cookies.items() + + for name, cookie in cookies: + if not isinstance(cookie, Morsel): + tmp = SimpleCookie() + tmp[name] = cookie # type: ignore[assignment] + cookie = tmp[name] + + domain = cookie["domain"] + + # ignore domains with trailing dots + if domain.endswith("."): + domain = "" + del cookie["domain"] + + if not domain and hostname is not None: + # Set the cookie's domain to the response hostname + # and set its host-only-flag + self._host_only_cookies.add((hostname, name)) + domain = cookie["domain"] = hostname + + if domain.startswith("."): + # Remove leading dot + domain = domain[1:] + cookie["domain"] = domain + + if hostname and not self._is_domain_match(domain, hostname): + # Setting cookies for different domains is not allowed + continue + + path = cookie["path"] + if not path or not path.startswith("/"): + # Set the cookie's path to the response path + path = response_url.path + if not path.startswith("/"): + path = "/" + else: + # Cut everything from the last slash to the end + path = "/" + path[1 : path.rfind("/")] + cookie["path"] = path + path = path.rstrip("/") + + max_age = cookie["max-age"] + if max_age: + try: + delta_seconds = int(max_age) + max_age_expiration = min(time.time() + delta_seconds, self.MAX_TIME) + self._expire_cookie(max_age_expiration, domain, path, name) + except ValueError: + cookie["max-age"] = "" + + else: + expires = cookie["expires"] + if expires: + expire_time = self._parse_date(expires) + if expire_time: + self._expire_cookie(expire_time, domain, path, name) + else: + cookie["expires"] = "" + + self._cookies[(domain, path)][name] = cookie + + self._do_expiration() + + def filter_cookies(self, request_url: URL = URL()) -> "BaseCookie[str]": + """Returns this jar's cookies filtered by their attributes.""" + filtered: Union[SimpleCookie, "BaseCookie[str]"] = ( + SimpleCookie() if self._quote_cookie else BaseCookie() + ) + if not self._cookies: + # Skip do_expiration() if there are no cookies. + return filtered + self._do_expiration() + if not self._cookies: + # Skip rest of function if no non-expired cookies. + return filtered + request_url = URL(request_url) + hostname = request_url.raw_host or "" + + is_not_secure = request_url.scheme not in ("https", "wss") + if is_not_secure and self._treat_as_secure_origin: + request_origin = URL() + with contextlib.suppress(ValueError): + request_origin = request_url.origin() + is_not_secure = request_origin not in self._treat_as_secure_origin + + # Send shared cookie + for c in self._cookies[("", "")].values(): + filtered[c.key] = c.value + + if is_ip_address(hostname): + if not self._unsafe: + return filtered + domains: Iterable[str] = (hostname,) + else: + # Get all the subdomains that might match a cookie (e.g. "foo.bar.com", "bar.com", "com") + domains = itertools.accumulate( + reversed(hostname.split(".")), _FORMAT_DOMAIN_REVERSED + ) + + # Get all the path prefixes that might match a cookie (e.g. "", "/foo", "/foo/bar") + paths = itertools.accumulate(request_url.path.split("/"), _FORMAT_PATH) + # Create every combination of (domain, path) pairs. + pairs = itertools.product(domains, paths) + + # Point 2: https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 + cookies = itertools.chain.from_iterable( + self._cookies[p].values() for p in pairs + ) + path_len = len(request_url.path) + for cookie in cookies: + name = cookie.key + domain = cookie["domain"] + + if (domain, name) in self._host_only_cookies: + if domain != hostname: + continue + + # Skip edge case when the cookie has a trailing slash but request doesn't. + if len(cookie["path"]) > path_len: + continue + + if is_not_secure and cookie["secure"]: + continue + + # It's critical we use the Morsel so the coded_value + # (based on cookie version) is preserved + mrsl_val = cast("Morsel[str]", cookie.get(cookie.key, Morsel())) + mrsl_val.set(cookie.key, cookie.value, cookie.coded_value) + filtered[name] = mrsl_val + + return filtered + + @staticmethod + def _is_domain_match(domain: str, hostname: str) -> bool: + """Implements domain matching adhering to RFC 6265.""" + if hostname == domain: + return True + + if not hostname.endswith(domain): + return False + + non_matching = hostname[: -len(domain)] + + if not non_matching.endswith("."): + return False + + return not is_ip_address(hostname) + + @classmethod + def _parse_date(cls, date_str: str) -> Optional[int]: + """Implements date string parsing adhering to RFC 6265.""" + if not date_str: + return None + + found_time = False + found_day = False + found_month = False + found_year = False + + hour = minute = second = 0 + day = 0 + month = 0 + year = 0 + + for token_match in cls.DATE_TOKENS_RE.finditer(date_str): + + token = token_match.group("token") + + if not found_time: + time_match = cls.DATE_HMS_TIME_RE.match(token) + if time_match: + found_time = True + hour, minute, second = (int(s) for s in time_match.groups()) + continue + + if not found_day: + day_match = cls.DATE_DAY_OF_MONTH_RE.match(token) + if day_match: + found_day = True + day = int(day_match.group()) + continue + + if not found_month: + month_match = cls.DATE_MONTH_RE.match(token) + if month_match: + found_month = True + assert month_match.lastindex is not None + month = month_match.lastindex + continue + + if not found_year: + year_match = cls.DATE_YEAR_RE.match(token) + if year_match: + found_year = True + year = int(year_match.group()) + + if 70 <= year <= 99: + year += 1900 + elif 0 <= year <= 69: + year += 2000 + + if False in (found_day, found_month, found_year, found_time): + return None + + if not 1 <= day <= 31: + return None + + if year < 1601 or hour > 23 or minute > 59 or second > 59: + return None + + return calendar.timegm((year, month, day, hour, minute, second, -1, -1, -1)) + + +class DummyCookieJar(AbstractCookieJar): + """Implements a dummy cookie storage. + + It can be used with the ClientSession when no cookie processing is needed. + + """ + + def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: + super().__init__(loop=loop) + + def __iter__(self) -> "Iterator[Morsel[str]]": + while False: + yield None + + def __len__(self) -> int: + return 0 + + def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: + pass + + def clear_domain(self, domain: str) -> None: + pass + + def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: + pass + + def filter_cookies(self, request_url: URL) -> "BaseCookie[str]": + return SimpleCookie() diff --git a/env/Lib/site-packages/aiohttp/formdata.py b/env/Lib/site-packages/aiohttp/formdata.py new file mode 100644 index 0000000..2b75b3d --- /dev/null +++ b/env/Lib/site-packages/aiohttp/formdata.py @@ -0,0 +1,182 @@ +import io +import warnings +from typing import Any, Iterable, List, Optional +from urllib.parse import urlencode + +from multidict import MultiDict, MultiDictProxy + +from . import hdrs, multipart, payload +from .helpers import guess_filename +from .payload import Payload + +__all__ = ("FormData",) + + +class FormData: + """Helper class for form body generation. + + Supports multipart/form-data and application/x-www-form-urlencoded. + """ + + def __init__( + self, + fields: Iterable[Any] = (), + quote_fields: bool = True, + charset: Optional[str] = None, + ) -> None: + self._writer = multipart.MultipartWriter("form-data") + self._fields: List[Any] = [] + self._is_multipart = False + self._is_processed = False + self._quote_fields = quote_fields + self._charset = charset + + if isinstance(fields, dict): + fields = list(fields.items()) + elif not isinstance(fields, (list, tuple)): + fields = (fields,) + self.add_fields(*fields) + + @property + def is_multipart(self) -> bool: + return self._is_multipart + + def add_field( + self, + name: str, + value: Any, + *, + content_type: Optional[str] = None, + filename: Optional[str] = None, + content_transfer_encoding: Optional[str] = None, + ) -> None: + + if isinstance(value, io.IOBase): + self._is_multipart = True + elif isinstance(value, (bytes, bytearray, memoryview)): + msg = ( + "In v4, passing bytes will no longer create a file field. " + "Please explicitly use the filename parameter or pass a BytesIO object." + ) + if filename is None and content_transfer_encoding is None: + warnings.warn(msg, DeprecationWarning) + filename = name + + type_options: MultiDict[str] = MultiDict({"name": name}) + if filename is not None and not isinstance(filename, str): + raise TypeError( + "filename must be an instance of str. " "Got: %s" % filename + ) + if filename is None and isinstance(value, io.IOBase): + filename = guess_filename(value, name) + if filename is not None: + type_options["filename"] = filename + self._is_multipart = True + + headers = {} + if content_type is not None: + if not isinstance(content_type, str): + raise TypeError( + "content_type must be an instance of str. " "Got: %s" % content_type + ) + headers[hdrs.CONTENT_TYPE] = content_type + self._is_multipart = True + if content_transfer_encoding is not None: + if not isinstance(content_transfer_encoding, str): + raise TypeError( + "content_transfer_encoding must be an instance" + " of str. Got: %s" % content_transfer_encoding + ) + msg = ( + "content_transfer_encoding is deprecated. " + "To maintain compatibility with v4 please pass a BytesPayload." + ) + warnings.warn(msg, DeprecationWarning) + self._is_multipart = True + + self._fields.append((type_options, headers, value)) + + def add_fields(self, *fields: Any) -> None: + to_add = list(fields) + + while to_add: + rec = to_add.pop(0) + + if isinstance(rec, io.IOBase): + k = guess_filename(rec, "unknown") + self.add_field(k, rec) # type: ignore[arg-type] + + elif isinstance(rec, (MultiDictProxy, MultiDict)): + to_add.extend(rec.items()) + + elif isinstance(rec, (list, tuple)) and len(rec) == 2: + k, fp = rec + self.add_field(k, fp) # type: ignore[arg-type] + + else: + raise TypeError( + "Only io.IOBase, multidict and (name, file) " + "pairs allowed, use .add_field() for passing " + "more complex parameters, got {!r}".format(rec) + ) + + def _gen_form_urlencoded(self) -> payload.BytesPayload: + # form data (x-www-form-urlencoded) + data = [] + for type_options, _, value in self._fields: + data.append((type_options["name"], value)) + + charset = self._charset if self._charset is not None else "utf-8" + + if charset == "utf-8": + content_type = "application/x-www-form-urlencoded" + else: + content_type = "application/x-www-form-urlencoded; " "charset=%s" % charset + + return payload.BytesPayload( + urlencode(data, doseq=True, encoding=charset).encode(), + content_type=content_type, + ) + + def _gen_form_data(self) -> multipart.MultipartWriter: + """Encode a list of fields using the multipart/form-data MIME format""" + if self._is_processed: + raise RuntimeError("Form data has been processed already") + for dispparams, headers, value in self._fields: + try: + if hdrs.CONTENT_TYPE in headers: + part = payload.get_payload( + value, + content_type=headers[hdrs.CONTENT_TYPE], + headers=headers, + encoding=self._charset, + ) + else: + part = payload.get_payload( + value, headers=headers, encoding=self._charset + ) + except Exception as exc: + raise TypeError( + "Can not serialize value type: %r\n " + "headers: %r\n value: %r" % (type(value), headers, value) + ) from exc + + if dispparams: + part.set_content_disposition( + "form-data", quote_fields=self._quote_fields, **dispparams + ) + # FIXME cgi.FieldStorage doesn't likes body parts with + # Content-Length which were sent via chunked transfer encoding + assert part.headers is not None + part.headers.popall(hdrs.CONTENT_LENGTH, None) + + self._writer.append_payload(part) + + self._is_processed = True + return self._writer + + def __call__(self) -> Payload: + if self._is_multipart: + return self._gen_form_data() + else: + return self._gen_form_urlencoded() diff --git a/env/Lib/site-packages/aiohttp/hdrs.py b/env/Lib/site-packages/aiohttp/hdrs.py new file mode 100644 index 0000000..2f1f5e0 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/hdrs.py @@ -0,0 +1,108 @@ +"""HTTP Headers constants.""" + +# After changing the file content call ./tools/gen.py +# to regenerate the headers parser +from typing import Final, Set + +from multidict import istr + +METH_ANY: Final[str] = "*" +METH_CONNECT: Final[str] = "CONNECT" +METH_HEAD: Final[str] = "HEAD" +METH_GET: Final[str] = "GET" +METH_DELETE: Final[str] = "DELETE" +METH_OPTIONS: Final[str] = "OPTIONS" +METH_PATCH: Final[str] = "PATCH" +METH_POST: Final[str] = "POST" +METH_PUT: Final[str] = "PUT" +METH_TRACE: Final[str] = "TRACE" + +METH_ALL: Final[Set[str]] = { + METH_CONNECT, + METH_HEAD, + METH_GET, + METH_DELETE, + METH_OPTIONS, + METH_PATCH, + METH_POST, + METH_PUT, + METH_TRACE, +} + +ACCEPT: Final[istr] = istr("Accept") +ACCEPT_CHARSET: Final[istr] = istr("Accept-Charset") +ACCEPT_ENCODING: Final[istr] = istr("Accept-Encoding") +ACCEPT_LANGUAGE: Final[istr] = istr("Accept-Language") +ACCEPT_RANGES: Final[istr] = istr("Accept-Ranges") +ACCESS_CONTROL_MAX_AGE: Final[istr] = istr("Access-Control-Max-Age") +ACCESS_CONTROL_ALLOW_CREDENTIALS: Final[istr] = istr("Access-Control-Allow-Credentials") +ACCESS_CONTROL_ALLOW_HEADERS: Final[istr] = istr("Access-Control-Allow-Headers") +ACCESS_CONTROL_ALLOW_METHODS: Final[istr] = istr("Access-Control-Allow-Methods") +ACCESS_CONTROL_ALLOW_ORIGIN: Final[istr] = istr("Access-Control-Allow-Origin") +ACCESS_CONTROL_EXPOSE_HEADERS: Final[istr] = istr("Access-Control-Expose-Headers") +ACCESS_CONTROL_REQUEST_HEADERS: Final[istr] = istr("Access-Control-Request-Headers") +ACCESS_CONTROL_REQUEST_METHOD: Final[istr] = istr("Access-Control-Request-Method") +AGE: Final[istr] = istr("Age") +ALLOW: Final[istr] = istr("Allow") +AUTHORIZATION: Final[istr] = istr("Authorization") +CACHE_CONTROL: Final[istr] = istr("Cache-Control") +CONNECTION: Final[istr] = istr("Connection") +CONTENT_DISPOSITION: Final[istr] = istr("Content-Disposition") +CONTENT_ENCODING: Final[istr] = istr("Content-Encoding") +CONTENT_LANGUAGE: Final[istr] = istr("Content-Language") +CONTENT_LENGTH: Final[istr] = istr("Content-Length") +CONTENT_LOCATION: Final[istr] = istr("Content-Location") +CONTENT_MD5: Final[istr] = istr("Content-MD5") +CONTENT_RANGE: Final[istr] = istr("Content-Range") +CONTENT_TRANSFER_ENCODING: Final[istr] = istr("Content-Transfer-Encoding") +CONTENT_TYPE: Final[istr] = istr("Content-Type") +COOKIE: Final[istr] = istr("Cookie") +DATE: Final[istr] = istr("Date") +DESTINATION: Final[istr] = istr("Destination") +DIGEST: Final[istr] = istr("Digest") +ETAG: Final[istr] = istr("Etag") +EXPECT: Final[istr] = istr("Expect") +EXPIRES: Final[istr] = istr("Expires") +FORWARDED: Final[istr] = istr("Forwarded") +FROM: Final[istr] = istr("From") +HOST: Final[istr] = istr("Host") +IF_MATCH: Final[istr] = istr("If-Match") +IF_MODIFIED_SINCE: Final[istr] = istr("If-Modified-Since") +IF_NONE_MATCH: Final[istr] = istr("If-None-Match") +IF_RANGE: Final[istr] = istr("If-Range") +IF_UNMODIFIED_SINCE: Final[istr] = istr("If-Unmodified-Since") +KEEP_ALIVE: Final[istr] = istr("Keep-Alive") +LAST_EVENT_ID: Final[istr] = istr("Last-Event-ID") +LAST_MODIFIED: Final[istr] = istr("Last-Modified") +LINK: Final[istr] = istr("Link") +LOCATION: Final[istr] = istr("Location") +MAX_FORWARDS: Final[istr] = istr("Max-Forwards") +ORIGIN: Final[istr] = istr("Origin") +PRAGMA: Final[istr] = istr("Pragma") +PROXY_AUTHENTICATE: Final[istr] = istr("Proxy-Authenticate") +PROXY_AUTHORIZATION: Final[istr] = istr("Proxy-Authorization") +RANGE: Final[istr] = istr("Range") +REFERER: Final[istr] = istr("Referer") +RETRY_AFTER: Final[istr] = istr("Retry-After") +SEC_WEBSOCKET_ACCEPT: Final[istr] = istr("Sec-WebSocket-Accept") +SEC_WEBSOCKET_VERSION: Final[istr] = istr("Sec-WebSocket-Version") +SEC_WEBSOCKET_PROTOCOL: Final[istr] = istr("Sec-WebSocket-Protocol") +SEC_WEBSOCKET_EXTENSIONS: Final[istr] = istr("Sec-WebSocket-Extensions") +SEC_WEBSOCKET_KEY: Final[istr] = istr("Sec-WebSocket-Key") +SEC_WEBSOCKET_KEY1: Final[istr] = istr("Sec-WebSocket-Key1") +SERVER: Final[istr] = istr("Server") +SET_COOKIE: Final[istr] = istr("Set-Cookie") +TE: Final[istr] = istr("TE") +TRAILER: Final[istr] = istr("Trailer") +TRANSFER_ENCODING: Final[istr] = istr("Transfer-Encoding") +UPGRADE: Final[istr] = istr("Upgrade") +URI: Final[istr] = istr("URI") +USER_AGENT: Final[istr] = istr("User-Agent") +VARY: Final[istr] = istr("Vary") +VIA: Final[istr] = istr("Via") +WANT_DIGEST: Final[istr] = istr("Want-Digest") +WARNING: Final[istr] = istr("Warning") +WWW_AUTHENTICATE: Final[istr] = istr("WWW-Authenticate") +X_FORWARDED_FOR: Final[istr] = istr("X-Forwarded-For") +X_FORWARDED_HOST: Final[istr] = istr("X-Forwarded-Host") +X_FORWARDED_PROTO: Final[istr] = istr("X-Forwarded-Proto") diff --git a/env/Lib/site-packages/aiohttp/helpers.py b/env/Lib/site-packages/aiohttp/helpers.py new file mode 100644 index 0000000..ccfa9d5 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/helpers.py @@ -0,0 +1,1001 @@ +"""Various helper functions""" + +import asyncio +import base64 +import binascii +import contextlib +import datetime +import enum +import functools +import inspect +import netrc +import os +import platform +import re +import sys +import time +import weakref +from collections import namedtuple +from contextlib import suppress +from email.parser import HeaderParser +from email.utils import parsedate +from math import ceil +from pathlib import Path +from types import TracebackType +from typing import ( + Any, + Callable, + ContextManager, + Dict, + Generator, + Generic, + Iterable, + Iterator, + List, + Mapping, + Optional, + Pattern, + Protocol, + Tuple, + Type, + TypeVar, + Union, + get_args, + overload, +) +from urllib.parse import quote +from urllib.request import getproxies, proxy_bypass + +import attr +from multidict import MultiDict, MultiDictProxy, MultiMapping +from yarl import URL + +from . import hdrs +from .log import client_logger + +if sys.version_info >= (3, 11): + import asyncio as async_timeout +else: + import async_timeout + +__all__ = ("BasicAuth", "ChainMapProxy", "ETag") + +IS_MACOS = platform.system() == "Darwin" +IS_WINDOWS = platform.system() == "Windows" + +PY_310 = sys.version_info >= (3, 10) +PY_311 = sys.version_info >= (3, 11) + + +_T = TypeVar("_T") +_S = TypeVar("_S") + +_SENTINEL = enum.Enum("_SENTINEL", "sentinel") +sentinel = _SENTINEL.sentinel + +NO_EXTENSIONS = bool(os.environ.get("AIOHTTP_NO_EXTENSIONS")) + +DEBUG = sys.flags.dev_mode or ( + not sys.flags.ignore_environment and bool(os.environ.get("PYTHONASYNCIODEBUG")) +) + + +CHAR = {chr(i) for i in range(0, 128)} +CTL = {chr(i) for i in range(0, 32)} | { + chr(127), +} +SEPARATORS = { + "(", + ")", + "<", + ">", + "@", + ",", + ";", + ":", + "\\", + '"', + "/", + "[", + "]", + "?", + "=", + "{", + "}", + " ", + chr(9), +} +TOKEN = CHAR ^ CTL ^ SEPARATORS + + +class noop: + def __await__(self) -> Generator[None, None, None]: + yield + + +class BasicAuth(namedtuple("BasicAuth", ["login", "password", "encoding"])): + """Http basic authentication helper.""" + + def __new__( + cls, login: str, password: str = "", encoding: str = "latin1" + ) -> "BasicAuth": + if login is None: + raise ValueError("None is not allowed as login value") + + if password is None: + raise ValueError("None is not allowed as password value") + + if ":" in login: + raise ValueError('A ":" is not allowed in login (RFC 1945#section-11.1)') + + return super().__new__(cls, login, password, encoding) + + @classmethod + def decode(cls, auth_header: str, encoding: str = "latin1") -> "BasicAuth": + """Create a BasicAuth object from an Authorization HTTP header.""" + try: + auth_type, encoded_credentials = auth_header.split(" ", 1) + except ValueError: + raise ValueError("Could not parse authorization header.") + + if auth_type.lower() != "basic": + raise ValueError("Unknown authorization method %s" % auth_type) + + try: + decoded = base64.b64decode( + encoded_credentials.encode("ascii"), validate=True + ).decode(encoding) + except binascii.Error: + raise ValueError("Invalid base64 encoding.") + + try: + # RFC 2617 HTTP Authentication + # https://www.ietf.org/rfc/rfc2617.txt + # the colon must be present, but the username and password may be + # otherwise blank. + username, password = decoded.split(":", 1) + except ValueError: + raise ValueError("Invalid credentials.") + + return cls(username, password, encoding=encoding) + + @classmethod + def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"]: + """Create BasicAuth from url.""" + if not isinstance(url, URL): + raise TypeError("url should be yarl.URL instance") + if url.user is None: + return None + return cls(url.user, url.password or "", encoding=encoding) + + def encode(self) -> str: + """Encode credentials.""" + creds = (f"{self.login}:{self.password}").encode(self.encoding) + return "Basic %s" % base64.b64encode(creds).decode(self.encoding) + + +def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: + auth = BasicAuth.from_url(url) + if auth is None: + return url, None + else: + return url.with_user(None), auth + + +def netrc_from_env() -> Optional[netrc.netrc]: + """Load netrc from file. + + Attempt to load it from the path specified by the env-var + NETRC or in the default location in the user's home directory. + + Returns None if it couldn't be found or fails to parse. + """ + netrc_env = os.environ.get("NETRC") + + if netrc_env is not None: + netrc_path = Path(netrc_env) + else: + try: + home_dir = Path.home() + except RuntimeError as e: # pragma: no cover + # if pathlib can't resolve home, it may raise a RuntimeError + client_logger.debug( + "Could not resolve home directory when " + "trying to look for .netrc file: %s", + e, + ) + return None + + netrc_path = home_dir / ("_netrc" if IS_WINDOWS else ".netrc") + + try: + return netrc.netrc(str(netrc_path)) + except netrc.NetrcParseError as e: + client_logger.warning("Could not parse .netrc file: %s", e) + except OSError as e: + netrc_exists = False + with contextlib.suppress(OSError): + netrc_exists = netrc_path.is_file() + # we couldn't read the file (doesn't exist, permissions, etc.) + if netrc_env or netrc_exists: + # only warn if the environment wanted us to load it, + # or it appears like the default file does actually exist + client_logger.warning("Could not read .netrc file: %s", e) + + return None + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class ProxyInfo: + proxy: URL + proxy_auth: Optional[BasicAuth] + + +def basicauth_from_netrc(netrc_obj: Optional[netrc.netrc], host: str) -> BasicAuth: + """ + Return :py:class:`~aiohttp.BasicAuth` credentials for ``host`` from ``netrc_obj``. + + :raises LookupError: if ``netrc_obj`` is :py:data:`None` or if no + entry is found for the ``host``. + """ + if netrc_obj is None: + raise LookupError("No .netrc file found") + auth_from_netrc = netrc_obj.authenticators(host) + + if auth_from_netrc is None: + raise LookupError(f"No entry for {host!s} found in the `.netrc` file.") + login, account, password = auth_from_netrc + + # TODO(PY311): username = login or account + # Up to python 3.10, account could be None if not specified, + # and login will be empty string if not specified. From 3.11, + # login and account will be empty string if not specified. + username = login if (login or account is None) else account + + # TODO(PY311): Remove this, as password will be empty string + # if not specified + if password is None: + password = "" + + return BasicAuth(username, password) + + +def proxies_from_env() -> Dict[str, ProxyInfo]: + proxy_urls = { + k: URL(v) + for k, v in getproxies().items() + if k in ("http", "https", "ws", "wss") + } + netrc_obj = netrc_from_env() + stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()} + ret = {} + for proto, val in stripped.items(): + proxy, auth = val + if proxy.scheme in ("https", "wss"): + client_logger.warning( + "%s proxies %s are not supported, ignoring", proxy.scheme.upper(), proxy + ) + continue + if netrc_obj and auth is None: + if proxy.host is not None: + try: + auth = basicauth_from_netrc(netrc_obj, proxy.host) + except LookupError: + auth = None + ret[proto] = ProxyInfo(proxy, auth) + return ret + + +def get_env_proxy_for_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: + """Get a permitted proxy for the given URL from the env.""" + if url.host is not None and proxy_bypass(url.host): + raise LookupError(f"Proxying is disallowed for `{url.host!r}`") + + proxies_in_env = proxies_from_env() + try: + proxy_info = proxies_in_env[url.scheme] + except KeyError: + raise LookupError(f"No proxies found for `{url!s}` in the env") + else: + return proxy_info.proxy, proxy_info.proxy_auth + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class MimeType: + type: str + subtype: str + suffix: str + parameters: "MultiDictProxy[str]" + + +@functools.lru_cache(maxsize=56) +def parse_mimetype(mimetype: str) -> MimeType: + """Parses a MIME type into its components. + + mimetype is a MIME type string. + + Returns a MimeType object. + + Example: + + >>> parse_mimetype('text/html; charset=utf-8') + MimeType(type='text', subtype='html', suffix='', + parameters={'charset': 'utf-8'}) + + """ + if not mimetype: + return MimeType( + type="", subtype="", suffix="", parameters=MultiDictProxy(MultiDict()) + ) + + parts = mimetype.split(";") + params: MultiDict[str] = MultiDict() + for item in parts[1:]: + if not item: + continue + key, _, value = item.partition("=") + params.add(key.lower().strip(), value.strip(' "')) + + fulltype = parts[0].strip().lower() + if fulltype == "*": + fulltype = "*/*" + + mtype, _, stype = fulltype.partition("/") + stype, _, suffix = stype.partition("+") + + return MimeType( + type=mtype, subtype=stype, suffix=suffix, parameters=MultiDictProxy(params) + ) + + +def guess_filename(obj: Any, default: Optional[str] = None) -> Optional[str]: + name = getattr(obj, "name", None) + if name and isinstance(name, str) and name[0] != "<" and name[-1] != ">": + return Path(name).name + return default + + +not_qtext_re = re.compile(r"[^\041\043-\133\135-\176]") +QCONTENT = {chr(i) for i in range(0x20, 0x7F)} | {"\t"} + + +def quoted_string(content: str) -> str: + """Return 7-bit content as quoted-string. + + Format content into a quoted-string as defined in RFC5322 for + Internet Message Format. Notice that this is not the 8-bit HTTP + format, but the 7-bit email format. Content must be in usascii or + a ValueError is raised. + """ + if not (QCONTENT > set(content)): + raise ValueError(f"bad content for quoted-string {content!r}") + return not_qtext_re.sub(lambda x: "\\" + x.group(0), content) + + +def content_disposition_header( + disptype: str, quote_fields: bool = True, _charset: str = "utf-8", **params: str +) -> str: + """Sets ``Content-Disposition`` header for MIME. + + This is the MIME payload Content-Disposition header from RFC 2183 + and RFC 7579 section 4.2, not the HTTP Content-Disposition from + RFC 6266. + + disptype is a disposition type: inline, attachment, form-data. + Should be valid extension token (see RFC 2183) + + quote_fields performs value quoting to 7-bit MIME headers + according to RFC 7578. Set to quote_fields to False if recipient + can take 8-bit file names and field values. + + _charset specifies the charset to use when quote_fields is True. + + params is a dict with disposition params. + """ + if not disptype or not (TOKEN > set(disptype)): + raise ValueError("bad content disposition type {!r}" "".format(disptype)) + + value = disptype + if params: + lparams = [] + for key, val in params.items(): + if not key or not (TOKEN > set(key)): + raise ValueError( + "bad content disposition parameter" " {!r}={!r}".format(key, val) + ) + if quote_fields: + if key.lower() == "filename": + qval = quote(val, "", encoding=_charset) + lparams.append((key, '"%s"' % qval)) + else: + try: + qval = quoted_string(val) + except ValueError: + qval = "".join( + (_charset, "''", quote(val, "", encoding=_charset)) + ) + lparams.append((key + "*", qval)) + else: + lparams.append((key, '"%s"' % qval)) + else: + qval = val.replace("\\", "\\\\").replace('"', '\\"') + lparams.append((key, '"%s"' % qval)) + sparams = "; ".join("=".join(pair) for pair in lparams) + value = "; ".join((value, sparams)) + return value + + +class _TSelf(Protocol, Generic[_T]): + _cache: Dict[str, _T] + + +class reify(Generic[_T]): + """Use as a class method decorator. + + It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + """ + + def __init__(self, wrapped: Callable[..., _T]) -> None: + self.wrapped = wrapped + self.__doc__ = wrapped.__doc__ + self.name = wrapped.__name__ + + def __get__(self, inst: _TSelf[_T], owner: Optional[Type[Any]] = None) -> _T: + try: + try: + return inst._cache[self.name] + except KeyError: + val = self.wrapped(inst) + inst._cache[self.name] = val + return val + except AttributeError: + if inst is None: + return self + raise + + def __set__(self, inst: _TSelf[_T], value: _T) -> None: + raise AttributeError("reified property is read-only") + + +reify_py = reify + +try: + from ._helpers import reify as reify_c + + if not NO_EXTENSIONS: + reify = reify_c # type: ignore[misc,assignment] +except ImportError: + pass + +_ipv4_pattern = ( + r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}" + r"(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$" +) +_ipv6_pattern = ( + r"^(?:(?:(?:[A-F0-9]{1,4}:){6}|(?=(?:[A-F0-9]{0,4}:){0,6}" + r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}$)(([0-9A-F]{1,4}:){0,5}|:)" + r"((:[0-9A-F]{1,4}){1,5}:|:)|::(?:[A-F0-9]{1,4}:){5})" + r"(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}" + r"(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[A-F0-9]{1,4}:){7}" + r"[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}[A-F0-9]{0,4}$)" + r"(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:)|(?:[A-F0-9]{1,4}:){7}" + r":|:(:[A-F0-9]{1,4}){7})$" +) +_ipv4_regex = re.compile(_ipv4_pattern) +_ipv6_regex = re.compile(_ipv6_pattern, flags=re.IGNORECASE) +_ipv4_regexb = re.compile(_ipv4_pattern.encode("ascii")) +_ipv6_regexb = re.compile(_ipv6_pattern.encode("ascii"), flags=re.IGNORECASE) + + +def _is_ip_address( + regex: Pattern[str], regexb: Pattern[bytes], host: Optional[Union[str, bytes]] +) -> bool: + if host is None: + return False + if isinstance(host, str): + return bool(regex.match(host)) + elif isinstance(host, (bytes, bytearray, memoryview)): + return bool(regexb.match(host)) + else: + raise TypeError(f"{host} [{type(host)}] is not a str or bytes") + + +is_ipv4_address = functools.partial(_is_ip_address, _ipv4_regex, _ipv4_regexb) +is_ipv6_address = functools.partial(_is_ip_address, _ipv6_regex, _ipv6_regexb) + + +def is_ip_address(host: Optional[Union[str, bytes, bytearray, memoryview]]) -> bool: + return is_ipv4_address(host) or is_ipv6_address(host) + + +_cached_current_datetime: Optional[int] = None +_cached_formatted_datetime = "" + + +def rfc822_formatted_time() -> str: + global _cached_current_datetime + global _cached_formatted_datetime + + now = int(time.time()) + if now != _cached_current_datetime: + # Weekday and month names for HTTP date/time formatting; + # always English! + # Tuples are constants stored in codeobject! + _weekdayname = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") + _monthname = ( + "", # Dummy so we can use 1-based month numbers + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ) + + year, month, day, hh, mm, ss, wd, *tail = time.gmtime(now) + _cached_formatted_datetime = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( + _weekdayname[wd], + day, + _monthname[month], + year, + hh, + mm, + ss, + ) + _cached_current_datetime = now + return _cached_formatted_datetime + + +def _weakref_handle(info: "Tuple[weakref.ref[object], str]") -> None: + ref, name = info + ob = ref() + if ob is not None: + with suppress(Exception): + getattr(ob, name)() + + +def weakref_handle( + ob: object, + name: str, + timeout: float, + loop: asyncio.AbstractEventLoop, + timeout_ceil_threshold: float = 5, +) -> Optional[asyncio.TimerHandle]: + if timeout is not None and timeout > 0: + when = loop.time() + timeout + if timeout >= timeout_ceil_threshold: + when = ceil(when) + + return loop.call_at(when, _weakref_handle, (weakref.ref(ob), name)) + return None + + +def call_later( + cb: Callable[[], Any], + timeout: float, + loop: asyncio.AbstractEventLoop, + timeout_ceil_threshold: float = 5, +) -> Optional[asyncio.TimerHandle]: + if timeout is None or timeout <= 0: + return None + now = loop.time() + when = calculate_timeout_when(now, timeout, timeout_ceil_threshold) + return loop.call_at(when, cb) + + +def calculate_timeout_when( + loop_time: float, + timeout: float, + timeout_ceiling_threshold: float, +) -> float: + """Calculate when to execute a timeout.""" + when = loop_time + timeout + if timeout > timeout_ceiling_threshold: + return ceil(when) + return when + + +class TimeoutHandle: + """Timeout handle""" + + def __init__( + self, + loop: asyncio.AbstractEventLoop, + timeout: Optional[float], + ceil_threshold: float = 5, + ) -> None: + self._timeout = timeout + self._loop = loop + self._ceil_threshold = ceil_threshold + self._callbacks: List[ + Tuple[Callable[..., None], Tuple[Any, ...], Dict[str, Any]] + ] = [] + + def register( + self, callback: Callable[..., None], *args: Any, **kwargs: Any + ) -> None: + self._callbacks.append((callback, args, kwargs)) + + def close(self) -> None: + self._callbacks.clear() + + def start(self) -> Optional[asyncio.TimerHandle]: + timeout = self._timeout + if timeout is not None and timeout > 0: + when = self._loop.time() + timeout + if timeout >= self._ceil_threshold: + when = ceil(when) + return self._loop.call_at(when, self.__call__) + else: + return None + + def timer(self) -> "BaseTimerContext": + if self._timeout is not None and self._timeout > 0: + timer = TimerContext(self._loop) + self.register(timer.timeout) + return timer + else: + return TimerNoop() + + def __call__(self) -> None: + for cb, args, kwargs in self._callbacks: + with suppress(Exception): + cb(*args, **kwargs) + + self._callbacks.clear() + + +class BaseTimerContext(ContextManager["BaseTimerContext"]): + def assert_timeout(self) -> None: + """Raise TimeoutError if timeout has been exceeded.""" + + +class TimerNoop(BaseTimerContext): + def __enter__(self) -> BaseTimerContext: + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + return + + +class TimerContext(BaseTimerContext): + """Low resolution timeout context manager""" + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop = loop + self._tasks: List[asyncio.Task[Any]] = [] + self._cancelled = False + + def assert_timeout(self) -> None: + """Raise TimeoutError if timer has already been cancelled.""" + if self._cancelled: + raise asyncio.TimeoutError from None + + def __enter__(self) -> BaseTimerContext: + task = asyncio.current_task(loop=self._loop) + + if task is None: + raise RuntimeError( + "Timeout context manager should be used " "inside a task" + ) + + if self._cancelled: + raise asyncio.TimeoutError from None + + self._tasks.append(task) + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + if self._tasks: + self._tasks.pop() + + if exc_type is asyncio.CancelledError and self._cancelled: + raise asyncio.TimeoutError from None + return None + + def timeout(self) -> None: + if not self._cancelled: + for task in set(self._tasks): + task.cancel() + + self._cancelled = True + + +def ceil_timeout( + delay: Optional[float], ceil_threshold: float = 5 +) -> async_timeout.Timeout: + if delay is None or delay <= 0: + return async_timeout.timeout(None) + + loop = asyncio.get_running_loop() + now = loop.time() + when = now + delay + if delay > ceil_threshold: + when = ceil(when) + return async_timeout.timeout_at(when) + + +class HeadersMixin: + ATTRS = frozenset(["_content_type", "_content_dict", "_stored_content_type"]) + + _headers: MultiMapping[str] + + _content_type: Optional[str] = None + _content_dict: Optional[Dict[str, str]] = None + _stored_content_type: Union[str, None, _SENTINEL] = sentinel + + def _parse_content_type(self, raw: Optional[str]) -> None: + self._stored_content_type = raw + if raw is None: + # default value according to RFC 2616 + self._content_type = "application/octet-stream" + self._content_dict = {} + else: + msg = HeaderParser().parsestr("Content-Type: " + raw) + self._content_type = msg.get_content_type() + params = msg.get_params(()) + self._content_dict = dict(params[1:]) # First element is content type again + + @property + def content_type(self) -> str: + """The value of content part for Content-Type HTTP header.""" + raw = self._headers.get(hdrs.CONTENT_TYPE) + if self._stored_content_type != raw: + self._parse_content_type(raw) + return self._content_type # type: ignore[return-value] + + @property + def charset(self) -> Optional[str]: + """The value of charset part for Content-Type HTTP header.""" + raw = self._headers.get(hdrs.CONTENT_TYPE) + if self._stored_content_type != raw: + self._parse_content_type(raw) + return self._content_dict.get("charset") # type: ignore[union-attr] + + @property + def content_length(self) -> Optional[int]: + """The value of Content-Length HTTP header.""" + content_length = self._headers.get(hdrs.CONTENT_LENGTH) + + if content_length is not None: + return int(content_length) + else: + return None + + +def set_result(fut: "asyncio.Future[_T]", result: _T) -> None: + if not fut.done(): + fut.set_result(result) + + +_EXC_SENTINEL = BaseException() + + +class ErrorableProtocol(Protocol): + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = ..., + ) -> None: ... # pragma: no cover + + +def set_exception( + fut: "asyncio.Future[_T] | ErrorableProtocol", + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, +) -> None: + """Set future exception. + + If the future is marked as complete, this function is a no-op. + + :param exc_cause: An exception that is a direct cause of ``exc``. + Only set if provided. + """ + if asyncio.isfuture(fut) and fut.done(): + return + + exc_is_sentinel = exc_cause is _EXC_SENTINEL + exc_causes_itself = exc is exc_cause + if not exc_is_sentinel and not exc_causes_itself: + exc.__cause__ = exc_cause + + fut.set_exception(exc) + + +@functools.total_ordering +class AppKey(Generic[_T]): + """Keys for static typing support in Application.""" + + __slots__ = ("_name", "_t", "__orig_class__") + + # This may be set by Python when instantiating with a generic type. We need to + # support this, in order to support types that are not concrete classes, + # like Iterable, which can't be passed as the second parameter to __init__. + __orig_class__: Type[object] + + def __init__(self, name: str, t: Optional[Type[_T]] = None): + # Prefix with module name to help deduplicate key names. + frame = inspect.currentframe() + while frame: + if frame.f_code.co_name == "": + module: str = frame.f_globals["__name__"] + break + frame = frame.f_back + + self._name = module + "." + name + self._t = t + + def __lt__(self, other: object) -> bool: + if isinstance(other, AppKey): + return self._name < other._name + return True # Order AppKey above other types. + + def __repr__(self) -> str: + t = self._t + if t is None: + with suppress(AttributeError): + # Set to type arg. + t = get_args(self.__orig_class__)[0] + + if t is None: + t_repr = "<>" + elif isinstance(t, type): + if t.__module__ == "builtins": + t_repr = t.__qualname__ + else: + t_repr = f"{t.__module__}.{t.__qualname__}" + else: + t_repr = repr(t) + return f"" + + +class ChainMapProxy(Mapping[Union[str, AppKey[Any]], Any]): + __slots__ = ("_maps",) + + def __init__(self, maps: Iterable[Mapping[Union[str, AppKey[Any]], Any]]) -> None: + self._maps = tuple(maps) + + def __init_subclass__(cls) -> None: + raise TypeError( + "Inheritance class {} from ChainMapProxy " + "is forbidden".format(cls.__name__) + ) + + @overload # type: ignore[override] + def __getitem__(self, key: AppKey[_T]) -> _T: ... + + @overload + def __getitem__(self, key: str) -> Any: ... + + def __getitem__(self, key: Union[str, AppKey[_T]]) -> Any: + for mapping in self._maps: + try: + return mapping[key] + except KeyError: + pass + raise KeyError(key) + + @overload # type: ignore[override] + def get(self, key: AppKey[_T], default: _S) -> Union[_T, _S]: ... + + @overload + def get(self, key: AppKey[_T], default: None = ...) -> Optional[_T]: ... + + @overload + def get(self, key: str, default: Any = ...) -> Any: ... + + def get(self, key: Union[str, AppKey[_T]], default: Any = None) -> Any: + try: + return self[key] + except KeyError: + return default + + def __len__(self) -> int: + # reuses stored hash values if possible + return len(set().union(*self._maps)) + + def __iter__(self) -> Iterator[Union[str, AppKey[Any]]]: + d: Dict[Union[str, AppKey[Any]], Any] = {} + for mapping in reversed(self._maps): + # reuses stored hash values if possible + d.update(mapping) + return iter(d) + + def __contains__(self, key: object) -> bool: + return any(key in m for m in self._maps) + + def __bool__(self) -> bool: + return any(self._maps) + + def __repr__(self) -> str: + content = ", ".join(map(repr, self._maps)) + return f"ChainMapProxy({content})" + + +# https://tools.ietf.org/html/rfc7232#section-2.3 +_ETAGC = r"[!\x23-\x7E\x80-\xff]+" +_ETAGC_RE = re.compile(_ETAGC) +_QUOTED_ETAG = rf'(W/)?"({_ETAGC})"' +QUOTED_ETAG_RE = re.compile(_QUOTED_ETAG) +LIST_QUOTED_ETAG_RE = re.compile(rf"({_QUOTED_ETAG})(?:\s*,\s*|$)|(.)") + +ETAG_ANY = "*" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class ETag: + value: str + is_weak: bool = False + + +def validate_etag_value(value: str) -> None: + if value != ETAG_ANY and not _ETAGC_RE.fullmatch(value): + raise ValueError( + f"Value {value!r} is not a valid etag. Maybe it contains '\"'?" + ) + + +def parse_http_date(date_str: Optional[str]) -> Optional[datetime.datetime]: + """Process a date string, return a datetime object""" + if date_str is not None: + timetuple = parsedate(date_str) + if timetuple is not None: + with suppress(ValueError): + return datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc) + return None + + +def must_be_empty_body(method: str, code: int) -> bool: + """Check if a request must return an empty body.""" + return ( + status_code_must_be_empty_body(code) + or method_must_be_empty_body(method) + or (200 <= code < 300 and method.upper() == hdrs.METH_CONNECT) + ) + + +def method_must_be_empty_body(method: str) -> bool: + """Check if a method must return an empty body.""" + # https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.1 + # https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.2 + return method.upper() == hdrs.METH_HEAD + + +def status_code_must_be_empty_body(code: int) -> bool: + """Check if a status code must return an empty body.""" + # https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.1 + return code in {204, 304} or 100 <= code < 200 + + +def should_remove_content_length(method: str, code: int) -> bool: + """Check if a Content-Length header should be removed. + + This should always be a subset of must_be_empty_body + """ + # https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6-8 + # https://www.rfc-editor.org/rfc/rfc9110.html#section-15.4.5-4 + return ( + code in {204, 304} + or 100 <= code < 200 + or (200 <= code < 300 and method.upper() == hdrs.METH_CONNECT) + ) diff --git a/env/Lib/site-packages/aiohttp/http.py b/env/Lib/site-packages/aiohttp/http.py new file mode 100644 index 0000000..a1feae2 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/http.py @@ -0,0 +1,72 @@ +import sys +from http import HTTPStatus +from typing import Mapping, Tuple + +from . import __version__ +from .http_exceptions import HttpProcessingError as HttpProcessingError +from .http_parser import ( + HeadersParser as HeadersParser, + HttpParser as HttpParser, + HttpRequestParser as HttpRequestParser, + HttpResponseParser as HttpResponseParser, + RawRequestMessage as RawRequestMessage, + RawResponseMessage as RawResponseMessage, +) +from .http_websocket import ( + WS_CLOSED_MESSAGE as WS_CLOSED_MESSAGE, + WS_CLOSING_MESSAGE as WS_CLOSING_MESSAGE, + WS_KEY as WS_KEY, + WebSocketError as WebSocketError, + WebSocketReader as WebSocketReader, + WebSocketWriter as WebSocketWriter, + WSCloseCode as WSCloseCode, + WSMessage as WSMessage, + WSMsgType as WSMsgType, + ws_ext_gen as ws_ext_gen, + ws_ext_parse as ws_ext_parse, +) +from .http_writer import ( + HttpVersion as HttpVersion, + HttpVersion10 as HttpVersion10, + HttpVersion11 as HttpVersion11, + StreamWriter as StreamWriter, +) + +__all__ = ( + "HttpProcessingError", + "RESPONSES", + "SERVER_SOFTWARE", + # .http_writer + "StreamWriter", + "HttpVersion", + "HttpVersion10", + "HttpVersion11", + # .http_parser + "HeadersParser", + "HttpParser", + "HttpRequestParser", + "HttpResponseParser", + "RawRequestMessage", + "RawResponseMessage", + # .http_websocket + "WS_CLOSED_MESSAGE", + "WS_CLOSING_MESSAGE", + "WS_KEY", + "WebSocketReader", + "WebSocketWriter", + "ws_ext_gen", + "ws_ext_parse", + "WSMessage", + "WebSocketError", + "WSMsgType", + "WSCloseCode", +) + + +SERVER_SOFTWARE: str = "Python/{0[0]}.{0[1]} aiohttp/{1}".format( + sys.version_info, __version__ +) + +RESPONSES: Mapping[int, Tuple[str, str]] = { + v: (v.phrase, v.description) for v in HTTPStatus.__members__.values() +} diff --git a/env/Lib/site-packages/aiohttp/http_exceptions.py b/env/Lib/site-packages/aiohttp/http_exceptions.py new file mode 100644 index 0000000..c43ee0d --- /dev/null +++ b/env/Lib/site-packages/aiohttp/http_exceptions.py @@ -0,0 +1,105 @@ +"""Low-level http related exceptions.""" + +from textwrap import indent +from typing import Optional, Union + +from .typedefs import _CIMultiDict + +__all__ = ("HttpProcessingError",) + + +class HttpProcessingError(Exception): + """HTTP error. + + Shortcut for raising HTTP errors with custom code, message and headers. + + code: HTTP Error code. + message: (optional) Error message. + headers: (optional) Headers to be sent in response, a list of pairs + """ + + code = 0 + message = "" + headers = None + + def __init__( + self, + *, + code: Optional[int] = None, + message: str = "", + headers: Optional[_CIMultiDict] = None, + ) -> None: + if code is not None: + self.code = code + self.headers = headers + self.message = message + + def __str__(self) -> str: + msg = indent(self.message, " ") + return f"{self.code}, message:\n{msg}" + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}: {self.code}, message={self.message!r}>" + + +class BadHttpMessage(HttpProcessingError): + + code = 400 + message = "Bad Request" + + def __init__(self, message: str, *, headers: Optional[_CIMultiDict] = None) -> None: + super().__init__(message=message, headers=headers) + self.args = (message,) + + +class HttpBadRequest(BadHttpMessage): + + code = 400 + message = "Bad Request" + + +class PayloadEncodingError(BadHttpMessage): + """Base class for payload errors""" + + +class ContentEncodingError(PayloadEncodingError): + """Content encoding error.""" + + +class TransferEncodingError(PayloadEncodingError): + """transfer encoding error.""" + + +class ContentLengthError(PayloadEncodingError): + """Not enough data for satisfy content length header.""" + + +class LineTooLong(BadHttpMessage): + def __init__( + self, line: str, limit: str = "Unknown", actual_size: str = "Unknown" + ) -> None: + super().__init__( + f"Got more than {limit} bytes ({actual_size}) when reading {line}." + ) + self.args = (line, limit, actual_size) + + +class InvalidHeader(BadHttpMessage): + def __init__(self, hdr: Union[bytes, str]) -> None: + hdr_s = hdr.decode(errors="backslashreplace") if isinstance(hdr, bytes) else hdr + super().__init__(f"Invalid HTTP header: {hdr!r}") + self.hdr = hdr_s + self.args = (hdr,) + + +class BadStatusLine(BadHttpMessage): + def __init__(self, line: str = "", error: Optional[str] = None) -> None: + if not isinstance(line, str): + line = repr(line) + super().__init__(error or f"Bad status line {line!r}") + self.args = (line,) + self.line = line + + +class InvalidURLError(BadHttpMessage): + pass diff --git a/env/Lib/site-packages/aiohttp/http_parser.py b/env/Lib/site-packages/aiohttp/http_parser.py new file mode 100644 index 0000000..b992955 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/http_parser.py @@ -0,0 +1,1023 @@ +import abc +import asyncio +import re +import string +from contextlib import suppress +from enum import IntEnum +from typing import ( + Any, + ClassVar, + Final, + Generic, + List, + Literal, + NamedTuple, + Optional, + Pattern, + Set, + Tuple, + Type, + TypeVar, + Union, +) + +from multidict import CIMultiDict, CIMultiDictProxy, istr +from yarl import URL + +from . import hdrs +from .base_protocol import BaseProtocol +from .compression_utils import HAS_BROTLI, BrotliDecompressor, ZLibDecompressor +from .helpers import ( + _EXC_SENTINEL, + DEBUG, + NO_EXTENSIONS, + BaseTimerContext, + method_must_be_empty_body, + set_exception, + status_code_must_be_empty_body, +) +from .http_exceptions import ( + BadHttpMessage, + BadStatusLine, + ContentEncodingError, + ContentLengthError, + InvalidHeader, + InvalidURLError, + LineTooLong, + TransferEncodingError, +) +from .http_writer import HttpVersion, HttpVersion10 +from .streams import EMPTY_PAYLOAD, StreamReader +from .typedefs import RawHeaders + +__all__ = ( + "HeadersParser", + "HttpParser", + "HttpRequestParser", + "HttpResponseParser", + "RawRequestMessage", + "RawResponseMessage", +) + +_SEP = Literal[b"\r\n", b"\n"] + +ASCIISET: Final[Set[str]] = set(string.printable) + +# See https://www.rfc-editor.org/rfc/rfc9110.html#name-overview +# and https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens +# +# method = token +# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / +# "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +# token = 1*tchar +_TCHAR_SPECIALS: Final[str] = re.escape("!#$%&'*+-.^_`|~") +TOKENRE: Final[Pattern[str]] = re.compile(f"[0-9A-Za-z{_TCHAR_SPECIALS}]+") +VERSRE: Final[Pattern[str]] = re.compile(r"HTTP/(\d)\.(\d)", re.ASCII) +DIGITS: Final[Pattern[str]] = re.compile(r"\d+", re.ASCII) +HEXDIGITS: Final[Pattern[bytes]] = re.compile(rb"[0-9a-fA-F]+") + + +class RawRequestMessage(NamedTuple): + method: str + path: str + version: HttpVersion + headers: "CIMultiDictProxy[str]" + raw_headers: RawHeaders + should_close: bool + compression: Optional[str] + upgrade: bool + chunked: bool + url: URL + + +class RawResponseMessage(NamedTuple): + version: HttpVersion + code: int + reason: str + headers: CIMultiDictProxy[str] + raw_headers: RawHeaders + should_close: bool + compression: Optional[str] + upgrade: bool + chunked: bool + + +_MsgT = TypeVar("_MsgT", RawRequestMessage, RawResponseMessage) + + +class ParseState(IntEnum): + + PARSE_NONE = 0 + PARSE_LENGTH = 1 + PARSE_CHUNKED = 2 + PARSE_UNTIL_EOF = 3 + + +class ChunkState(IntEnum): + PARSE_CHUNKED_SIZE = 0 + PARSE_CHUNKED_CHUNK = 1 + PARSE_CHUNKED_CHUNK_EOF = 2 + PARSE_MAYBE_TRAILERS = 3 + PARSE_TRAILERS = 4 + + +class HeadersParser: + def __init__( + self, + max_line_size: int = 8190, + max_headers: int = 32768, + max_field_size: int = 8190, + lax: bool = False, + ) -> None: + self.max_line_size = max_line_size + self.max_headers = max_headers + self.max_field_size = max_field_size + self._lax = lax + + def parse_headers( + self, lines: List[bytes] + ) -> Tuple["CIMultiDictProxy[str]", RawHeaders]: + headers: CIMultiDict[str] = CIMultiDict() + # note: "raw" does not mean inclusion of OWS before/after the field value + raw_headers = [] + + lines_idx = 1 + line = lines[1] + line_count = len(lines) + + while line: + # Parse initial header name : value pair. + try: + bname, bvalue = line.split(b":", 1) + except ValueError: + raise InvalidHeader(line) from None + + if len(bname) == 0: + raise InvalidHeader(bname) + + # https://www.rfc-editor.org/rfc/rfc9112.html#section-5.1-2 + if {bname[0], bname[-1]} & {32, 9}: # {" ", "\t"} + raise InvalidHeader(line) + + bvalue = bvalue.lstrip(b" \t") + if len(bname) > self.max_field_size: + raise LineTooLong( + "request header name {}".format( + bname.decode("utf8", "backslashreplace") + ), + str(self.max_field_size), + str(len(bname)), + ) + name = bname.decode("utf-8", "surrogateescape") + if not TOKENRE.fullmatch(name): + raise InvalidHeader(bname) + + header_length = len(bvalue) + + # next line + lines_idx += 1 + line = lines[lines_idx] + + # consume continuation lines + continuation = self._lax and line and line[0] in (32, 9) # (' ', '\t') + + # Deprecated: https://www.rfc-editor.org/rfc/rfc9112.html#name-obsolete-line-folding + if continuation: + bvalue_lst = [bvalue] + while continuation: + header_length += len(line) + if header_length > self.max_field_size: + raise LineTooLong( + "request header field {}".format( + bname.decode("utf8", "backslashreplace") + ), + str(self.max_field_size), + str(header_length), + ) + bvalue_lst.append(line) + + # next line + lines_idx += 1 + if lines_idx < line_count: + line = lines[lines_idx] + if line: + continuation = line[0] in (32, 9) # (' ', '\t') + else: + line = b"" + break + bvalue = b"".join(bvalue_lst) + else: + if header_length > self.max_field_size: + raise LineTooLong( + "request header field {}".format( + bname.decode("utf8", "backslashreplace") + ), + str(self.max_field_size), + str(header_length), + ) + + bvalue = bvalue.strip(b" \t") + value = bvalue.decode("utf-8", "surrogateescape") + + # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-5 + if "\n" in value or "\r" in value or "\x00" in value: + raise InvalidHeader(bvalue) + + headers.add(name, value) + raw_headers.append((bname, bvalue)) + + return (CIMultiDictProxy(headers), tuple(raw_headers)) + + +def _is_supported_upgrade(headers: CIMultiDictProxy[str]) -> bool: + """Check if the upgrade header is supported.""" + return headers.get(hdrs.UPGRADE, "").lower() in {"tcp", "websocket"} + + +class HttpParser(abc.ABC, Generic[_MsgT]): + lax: ClassVar[bool] = False + + def __init__( + self, + protocol: Optional[BaseProtocol] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + limit: int = 2**16, + max_line_size: int = 8190, + max_headers: int = 32768, + max_field_size: int = 8190, + timer: Optional[BaseTimerContext] = None, + code: Optional[int] = None, + method: Optional[str] = None, + payload_exception: Optional[Type[BaseException]] = None, + response_with_body: bool = True, + read_until_eof: bool = False, + auto_decompress: bool = True, + ) -> None: + self.protocol = protocol + self.loop = loop + self.max_line_size = max_line_size + self.max_headers = max_headers + self.max_field_size = max_field_size + self.timer = timer + self.code = code + self.method = method + self.payload_exception = payload_exception + self.response_with_body = response_with_body + self.read_until_eof = read_until_eof + + self._lines: List[bytes] = [] + self._tail = b"" + self._upgraded = False + self._payload = None + self._payload_parser: Optional[HttpPayloadParser] = None + self._auto_decompress = auto_decompress + self._limit = limit + self._headers_parser = HeadersParser( + max_line_size, max_headers, max_field_size, self.lax + ) + + @abc.abstractmethod + def parse_message(self, lines: List[bytes]) -> _MsgT: + pass + + def feed_eof(self) -> Optional[_MsgT]: + if self._payload_parser is not None: + self._payload_parser.feed_eof() + self._payload_parser = None + else: + # try to extract partial message + if self._tail: + self._lines.append(self._tail) + + if self._lines: + if self._lines[-1] != "\r\n": + self._lines.append(b"") + with suppress(Exception): + return self.parse_message(self._lines) + return None + + def feed_data( + self, + data: bytes, + SEP: _SEP = b"\r\n", + EMPTY: bytes = b"", + CONTENT_LENGTH: istr = hdrs.CONTENT_LENGTH, + METH_CONNECT: str = hdrs.METH_CONNECT, + SEC_WEBSOCKET_KEY1: istr = hdrs.SEC_WEBSOCKET_KEY1, + ) -> Tuple[List[Tuple[_MsgT, StreamReader]], bool, bytes]: + + messages = [] + + if self._tail: + data, self._tail = self._tail + data, b"" + + data_len = len(data) + start_pos = 0 + loop = self.loop + + while start_pos < data_len: + + # read HTTP message (request/response line + headers), \r\n\r\n + # and split by lines + if self._payload_parser is None and not self._upgraded: + pos = data.find(SEP, start_pos) + # consume \r\n + if pos == start_pos and not self._lines: + start_pos = pos + len(SEP) + continue + + if pos >= start_pos: + # line found + line = data[start_pos:pos] + if SEP == b"\n": # For lax response parsing + line = line.rstrip(b"\r") + self._lines.append(line) + start_pos = pos + len(SEP) + + # \r\n\r\n found + if self._lines[-1] == EMPTY: + try: + msg: _MsgT = self.parse_message(self._lines) + finally: + self._lines.clear() + + def get_content_length() -> Optional[int]: + # payload length + length_hdr = msg.headers.get(CONTENT_LENGTH) + if length_hdr is None: + return None + + # Shouldn't allow +/- or other number formats. + # https://www.rfc-editor.org/rfc/rfc9110#section-8.6-2 + # msg.headers is already stripped of leading/trailing wsp + if not DIGITS.fullmatch(length_hdr): + raise InvalidHeader(CONTENT_LENGTH) + + return int(length_hdr) + + length = get_content_length() + # do not support old websocket spec + if SEC_WEBSOCKET_KEY1 in msg.headers: + raise InvalidHeader(SEC_WEBSOCKET_KEY1) + + self._upgraded = msg.upgrade and _is_supported_upgrade( + msg.headers + ) + + method = getattr(msg, "method", self.method) + # code is only present on responses + code = getattr(msg, "code", 0) + + assert self.protocol is not None + # calculate payload + empty_body = status_code_must_be_empty_body(code) or bool( + method and method_must_be_empty_body(method) + ) + if not empty_body and ( + ((length is not None and length > 0) or msg.chunked) + and not self._upgraded + ): + payload = StreamReader( + self.protocol, + timer=self.timer, + loop=loop, + limit=self._limit, + ) + payload_parser = HttpPayloadParser( + payload, + length=length, + chunked=msg.chunked, + method=method, + compression=msg.compression, + code=self.code, + response_with_body=self.response_with_body, + auto_decompress=self._auto_decompress, + lax=self.lax, + ) + if not payload_parser.done: + self._payload_parser = payload_parser + elif method == METH_CONNECT: + assert isinstance(msg, RawRequestMessage) + payload = StreamReader( + self.protocol, + timer=self.timer, + loop=loop, + limit=self._limit, + ) + self._upgraded = True + self._payload_parser = HttpPayloadParser( + payload, + method=msg.method, + compression=msg.compression, + auto_decompress=self._auto_decompress, + lax=self.lax, + ) + elif not empty_body and length is None and self.read_until_eof: + payload = StreamReader( + self.protocol, + timer=self.timer, + loop=loop, + limit=self._limit, + ) + payload_parser = HttpPayloadParser( + payload, + length=length, + chunked=msg.chunked, + method=method, + compression=msg.compression, + code=self.code, + response_with_body=self.response_with_body, + auto_decompress=self._auto_decompress, + lax=self.lax, + ) + if not payload_parser.done: + self._payload_parser = payload_parser + else: + payload = EMPTY_PAYLOAD + + messages.append((msg, payload)) + else: + self._tail = data[start_pos:] + data = EMPTY + break + + # no parser, just store + elif self._payload_parser is None and self._upgraded: + assert not self._lines + break + + # feed payload + elif data and start_pos < data_len: + assert not self._lines + assert self._payload_parser is not None + try: + eof, data = self._payload_parser.feed_data(data[start_pos:], SEP) + except BaseException as underlying_exc: + reraised_exc = underlying_exc + if self.payload_exception is not None: + reraised_exc = self.payload_exception(str(underlying_exc)) + + set_exception( + self._payload_parser.payload, + reraised_exc, + underlying_exc, + ) + + eof = True + data = b"" + + if eof: + start_pos = 0 + data_len = len(data) + self._payload_parser = None + continue + else: + break + + if data and start_pos < data_len: + data = data[start_pos:] + else: + data = EMPTY + + return messages, self._upgraded, data + + def parse_headers( + self, lines: List[bytes] + ) -> Tuple[ + "CIMultiDictProxy[str]", RawHeaders, Optional[bool], Optional[str], bool, bool + ]: + """Parses RFC 5322 headers from a stream. + + Line continuations are supported. Returns list of header name + and value pairs. Header name is in upper case. + """ + headers, raw_headers = self._headers_parser.parse_headers(lines) + close_conn = None + encoding = None + upgrade = False + chunked = False + + # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-6 + # https://www.rfc-editor.org/rfc/rfc9110.html#name-collected-abnf + singletons = ( + hdrs.CONTENT_LENGTH, + hdrs.CONTENT_LOCATION, + hdrs.CONTENT_RANGE, + hdrs.CONTENT_TYPE, + hdrs.ETAG, + hdrs.HOST, + hdrs.MAX_FORWARDS, + hdrs.SERVER, + hdrs.TRANSFER_ENCODING, + hdrs.USER_AGENT, + ) + bad_hdr = next((h for h in singletons if len(headers.getall(h, ())) > 1), None) + if bad_hdr is not None: + raise BadHttpMessage(f"Duplicate '{bad_hdr}' header found.") + + # keep-alive + conn = headers.get(hdrs.CONNECTION) + if conn: + v = conn.lower() + if v == "close": + close_conn = True + elif v == "keep-alive": + close_conn = False + # https://www.rfc-editor.org/rfc/rfc9110.html#name-101-switching-protocols + elif v == "upgrade" and headers.get(hdrs.UPGRADE): + upgrade = True + + # encoding + enc = headers.get(hdrs.CONTENT_ENCODING) + if enc: + enc = enc.lower() + if enc in ("gzip", "deflate", "br"): + encoding = enc + + # chunking + te = headers.get(hdrs.TRANSFER_ENCODING) + if te is not None: + if "chunked" == te.lower(): + chunked = True + else: + raise BadHttpMessage("Request has invalid `Transfer-Encoding`") + + if hdrs.CONTENT_LENGTH in headers: + raise BadHttpMessage( + "Transfer-Encoding can't be present with Content-Length", + ) + + return (headers, raw_headers, close_conn, encoding, upgrade, chunked) + + def set_upgraded(self, val: bool) -> None: + """Set connection upgraded (to websocket) mode. + + :param bool val: new state. + """ + self._upgraded = val + + +class HttpRequestParser(HttpParser[RawRequestMessage]): + """Read request status line. + + Exception .http_exceptions.BadStatusLine + could be raised in case of any errors in status line. + Returns RawRequestMessage. + """ + + def parse_message(self, lines: List[bytes]) -> RawRequestMessage: + # request line + line = lines[0].decode("utf-8", "surrogateescape") + try: + method, path, version = line.split(" ", maxsplit=2) + except ValueError: + raise BadStatusLine(line) from None + + if len(path) > self.max_line_size: + raise LineTooLong( + "Status line is too long", str(self.max_line_size), str(len(path)) + ) + + # method + if not TOKENRE.fullmatch(method): + raise BadStatusLine(method) + + # version + match = VERSRE.fullmatch(version) + if match is None: + raise BadStatusLine(line) + version_o = HttpVersion(int(match.group(1)), int(match.group(2))) + + if method == "CONNECT": + # authority-form, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3 + url = URL.build(authority=path, encoded=True) + elif path.startswith("/"): + # origin-form, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1 + path_part, _hash_separator, url_fragment = path.partition("#") + path_part, _question_mark_separator, qs_part = path_part.partition("?") + + # NOTE: `yarl.URL.build()` is used to mimic what the Cython-based + # NOTE: parser does, otherwise it results into the same + # NOTE: HTTP Request-Line input producing different + # NOTE: `yarl.URL()` objects + url = URL.build( + path=path_part, + query_string=qs_part, + fragment=url_fragment, + encoded=True, + ) + elif path == "*" and method == "OPTIONS": + # asterisk-form, + url = URL(path, encoded=True) + else: + # absolute-form for proxy maybe, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2 + url = URL(path, encoded=True) + if url.scheme == "": + # not absolute-form + raise InvalidURLError( + path.encode(errors="surrogateescape").decode("latin1") + ) + + # read headers + ( + headers, + raw_headers, + close, + compression, + upgrade, + chunked, + ) = self.parse_headers(lines) + + if close is None: # then the headers weren't set in the request + if version_o <= HttpVersion10: # HTTP 1.0 must asks to not close + close = True + else: # HTTP 1.1 must ask to close. + close = False + + return RawRequestMessage( + method, + path, + version_o, + headers, + raw_headers, + close, + compression, + upgrade, + chunked, + url, + ) + + +class HttpResponseParser(HttpParser[RawResponseMessage]): + """Read response status line and headers. + + BadStatusLine could be raised in case of any errors in status line. + Returns RawResponseMessage. + """ + + # Lax mode should only be enabled on response parser. + lax = not DEBUG + + def feed_data( + self, + data: bytes, + SEP: Optional[_SEP] = None, + *args: Any, + **kwargs: Any, + ) -> Tuple[List[Tuple[RawResponseMessage, StreamReader]], bool, bytes]: + if SEP is None: + SEP = b"\r\n" if DEBUG else b"\n" + return super().feed_data(data, SEP, *args, **kwargs) + + def parse_message(self, lines: List[bytes]) -> RawResponseMessage: + line = lines[0].decode("utf-8", "surrogateescape") + try: + version, status = line.split(maxsplit=1) + except ValueError: + raise BadStatusLine(line) from None + + try: + status, reason = status.split(maxsplit=1) + except ValueError: + status = status.strip() + reason = "" + + if len(reason) > self.max_line_size: + raise LineTooLong( + "Status line is too long", str(self.max_line_size), str(len(reason)) + ) + + # version + match = VERSRE.fullmatch(version) + if match is None: + raise BadStatusLine(line) + version_o = HttpVersion(int(match.group(1)), int(match.group(2))) + + # The status code is a three-digit ASCII number, no padding + if len(status) != 3 or not DIGITS.fullmatch(status): + raise BadStatusLine(line) + status_i = int(status) + + # read headers + ( + headers, + raw_headers, + close, + compression, + upgrade, + chunked, + ) = self.parse_headers(lines) + + if close is None: + if version_o <= HttpVersion10: + close = True + # https://www.rfc-editor.org/rfc/rfc9112.html#name-message-body-length + elif 100 <= status_i < 200 or status_i in {204, 304}: + close = False + elif hdrs.CONTENT_LENGTH in headers or hdrs.TRANSFER_ENCODING in headers: + close = False + else: + # https://www.rfc-editor.org/rfc/rfc9112.html#section-6.3-2.8 + close = True + + return RawResponseMessage( + version_o, + status_i, + reason.strip(), + headers, + raw_headers, + close, + compression, + upgrade, + chunked, + ) + + +class HttpPayloadParser: + def __init__( + self, + payload: StreamReader, + length: Optional[int] = None, + chunked: bool = False, + compression: Optional[str] = None, + code: Optional[int] = None, + method: Optional[str] = None, + response_with_body: bool = True, + auto_decompress: bool = True, + lax: bool = False, + ) -> None: + self._length = 0 + self._type = ParseState.PARSE_UNTIL_EOF + self._chunk = ChunkState.PARSE_CHUNKED_SIZE + self._chunk_size = 0 + self._chunk_tail = b"" + self._auto_decompress = auto_decompress + self._lax = lax + self.done = False + + # payload decompression wrapper + if response_with_body and compression and self._auto_decompress: + real_payload: Union[StreamReader, DeflateBuffer] = DeflateBuffer( + payload, compression + ) + else: + real_payload = payload + + # payload parser + if not response_with_body: + # don't parse payload if it's not expected to be received + self._type = ParseState.PARSE_NONE + real_payload.feed_eof() + self.done = True + elif chunked: + self._type = ParseState.PARSE_CHUNKED + elif length is not None: + self._type = ParseState.PARSE_LENGTH + self._length = length + if self._length == 0: + real_payload.feed_eof() + self.done = True + + self.payload = real_payload + + def feed_eof(self) -> None: + if self._type == ParseState.PARSE_UNTIL_EOF: + self.payload.feed_eof() + elif self._type == ParseState.PARSE_LENGTH: + raise ContentLengthError( + "Not enough data for satisfy content length header." + ) + elif self._type == ParseState.PARSE_CHUNKED: + raise TransferEncodingError( + "Not enough data for satisfy transfer length header." + ) + + def feed_data( + self, chunk: bytes, SEP: _SEP = b"\r\n", CHUNK_EXT: bytes = b";" + ) -> Tuple[bool, bytes]: + # Read specified amount of bytes + if self._type == ParseState.PARSE_LENGTH: + required = self._length + chunk_len = len(chunk) + + if required >= chunk_len: + self._length = required - chunk_len + self.payload.feed_data(chunk, chunk_len) + if self._length == 0: + self.payload.feed_eof() + return True, b"" + else: + self._length = 0 + self.payload.feed_data(chunk[:required], required) + self.payload.feed_eof() + return True, chunk[required:] + + # Chunked transfer encoding parser + elif self._type == ParseState.PARSE_CHUNKED: + if self._chunk_tail: + chunk = self._chunk_tail + chunk + self._chunk_tail = b"" + + while chunk: + + # read next chunk size + if self._chunk == ChunkState.PARSE_CHUNKED_SIZE: + pos = chunk.find(SEP) + if pos >= 0: + i = chunk.find(CHUNK_EXT, 0, pos) + if i >= 0: + size_b = chunk[:i] # strip chunk-extensions + else: + size_b = chunk[:pos] + + if self._lax: # Allow whitespace in lax mode. + size_b = size_b.strip() + + if not re.fullmatch(HEXDIGITS, size_b): + exc = TransferEncodingError( + chunk[:pos].decode("ascii", "surrogateescape") + ) + set_exception(self.payload, exc) + raise exc + size = int(bytes(size_b), 16) + + chunk = chunk[pos + len(SEP) :] + if size == 0: # eof marker + self._chunk = ChunkState.PARSE_MAYBE_TRAILERS + if self._lax and chunk.startswith(b"\r"): + chunk = chunk[1:] + else: + self._chunk = ChunkState.PARSE_CHUNKED_CHUNK + self._chunk_size = size + self.payload.begin_http_chunk_receiving() + else: + self._chunk_tail = chunk + return False, b"" + + # read chunk and feed buffer + if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK: + required = self._chunk_size + chunk_len = len(chunk) + + if required > chunk_len: + self._chunk_size = required - chunk_len + self.payload.feed_data(chunk, chunk_len) + return False, b"" + else: + self._chunk_size = 0 + self.payload.feed_data(chunk[:required], required) + chunk = chunk[required:] + self._chunk = ChunkState.PARSE_CHUNKED_CHUNK_EOF + self.payload.end_http_chunk_receiving() + + # toss the CRLF at the end of the chunk + if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK_EOF: + if self._lax and chunk.startswith(b"\r"): + chunk = chunk[1:] + if chunk[: len(SEP)] == SEP: + chunk = chunk[len(SEP) :] + self._chunk = ChunkState.PARSE_CHUNKED_SIZE + else: + self._chunk_tail = chunk + return False, b"" + + # if stream does not contain trailer, after 0\r\n + # we should get another \r\n otherwise + # trailers needs to be skipped until \r\n\r\n + if self._chunk == ChunkState.PARSE_MAYBE_TRAILERS: + head = chunk[: len(SEP)] + if head == SEP: + # end of stream + self.payload.feed_eof() + return True, chunk[len(SEP) :] + # Both CR and LF, or only LF may not be received yet. It is + # expected that CRLF or LF will be shown at the very first + # byte next time, otherwise trailers should come. The last + # CRLF which marks the end of response might not be + # contained in the same TCP segment which delivered the + # size indicator. + if not head: + return False, b"" + if head == SEP[:1]: + self._chunk_tail = head + return False, b"" + self._chunk = ChunkState.PARSE_TRAILERS + + # read and discard trailer up to the CRLF terminator + if self._chunk == ChunkState.PARSE_TRAILERS: + pos = chunk.find(SEP) + if pos >= 0: + chunk = chunk[pos + len(SEP) :] + self._chunk = ChunkState.PARSE_MAYBE_TRAILERS + else: + self._chunk_tail = chunk + return False, b"" + + # Read all bytes until eof + elif self._type == ParseState.PARSE_UNTIL_EOF: + self.payload.feed_data(chunk, len(chunk)) + + return False, b"" + + +class DeflateBuffer: + """DeflateStream decompress stream and feed data into specified stream.""" + + decompressor: Any + + def __init__(self, out: StreamReader, encoding: Optional[str]) -> None: + self.out = out + self.size = 0 + self.encoding = encoding + self._started_decoding = False + + self.decompressor: Union[BrotliDecompressor, ZLibDecompressor] + if encoding == "br": + if not HAS_BROTLI: # pragma: no cover + raise ContentEncodingError( + "Can not decode content-encoding: brotli (br). " + "Please install `Brotli`" + ) + self.decompressor = BrotliDecompressor() + else: + self.decompressor = ZLibDecompressor(encoding=encoding) + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + set_exception(self.out, exc, exc_cause) + + def feed_data(self, chunk: bytes, size: int) -> None: + if not size: + return + + self.size += size + + # RFC1950 + # bits 0..3 = CM = 0b1000 = 8 = "deflate" + # bits 4..7 = CINFO = 1..7 = windows size. + if ( + not self._started_decoding + and self.encoding == "deflate" + and chunk[0] & 0xF != 8 + ): + # Change the decoder to decompress incorrectly compressed data + # Actually we should issue a warning about non-RFC-compliant data. + self.decompressor = ZLibDecompressor( + encoding=self.encoding, suppress_deflate_header=True + ) + + try: + chunk = self.decompressor.decompress_sync(chunk) + except Exception: + raise ContentEncodingError( + "Can not decode content-encoding: %s" % self.encoding + ) + + self._started_decoding = True + + if chunk: + self.out.feed_data(chunk, len(chunk)) + + def feed_eof(self) -> None: + chunk = self.decompressor.flush() + + if chunk or self.size > 0: + self.out.feed_data(chunk, len(chunk)) + if self.encoding == "deflate" and not self.decompressor.eof: + raise ContentEncodingError("deflate") + + self.out.feed_eof() + + def begin_http_chunk_receiving(self) -> None: + self.out.begin_http_chunk_receiving() + + def end_http_chunk_receiving(self) -> None: + self.out.end_http_chunk_receiving() + + +HttpRequestParserPy = HttpRequestParser +HttpResponseParserPy = HttpResponseParser +RawRequestMessagePy = RawRequestMessage +RawResponseMessagePy = RawResponseMessage + +try: + if not NO_EXTENSIONS: + from ._http_parser import ( # type: ignore[import-not-found,no-redef] + HttpRequestParser, + HttpResponseParser, + RawRequestMessage, + RawResponseMessage, + ) + + HttpRequestParserC = HttpRequestParser + HttpResponseParserC = HttpResponseParser + RawRequestMessageC = RawRequestMessage + RawResponseMessageC = RawResponseMessage +except ImportError: # pragma: no cover + pass diff --git a/env/Lib/site-packages/aiohttp/http_websocket.py b/env/Lib/site-packages/aiohttp/http_websocket.py new file mode 100644 index 0000000..db0cb42 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/http_websocket.py @@ -0,0 +1,737 @@ +"""WebSocket protocol versions 13 and 8.""" + +import asyncio +import functools +import json +import random +import re +import sys +import zlib +from enum import IntEnum +from functools import partial +from struct import Struct +from typing import ( + Any, + Callable, + Final, + List, + NamedTuple, + Optional, + Pattern, + Set, + Tuple, + Union, + cast, +) + +from .base_protocol import BaseProtocol +from .compression_utils import ZLibCompressor, ZLibDecompressor +from .helpers import NO_EXTENSIONS, set_exception +from .streams import DataQueue + +__all__ = ( + "WS_CLOSED_MESSAGE", + "WS_CLOSING_MESSAGE", + "WS_KEY", + "WebSocketReader", + "WebSocketWriter", + "WSMessage", + "WebSocketError", + "WSMsgType", + "WSCloseCode", +) + + +class WSCloseCode(IntEnum): + OK = 1000 + GOING_AWAY = 1001 + PROTOCOL_ERROR = 1002 + UNSUPPORTED_DATA = 1003 + ABNORMAL_CLOSURE = 1006 + INVALID_TEXT = 1007 + POLICY_VIOLATION = 1008 + MESSAGE_TOO_BIG = 1009 + MANDATORY_EXTENSION = 1010 + INTERNAL_ERROR = 1011 + SERVICE_RESTART = 1012 + TRY_AGAIN_LATER = 1013 + BAD_GATEWAY = 1014 + + +ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode} + +# For websockets, keeping latency low is extremely important as implementations +# generally expect to be able to send and receive messages quickly. We use a +# larger chunk size than the default to reduce the number of executor calls +# since the executor is a significant source of latency and overhead when +# the chunks are small. A size of 5KiB was chosen because it is also the +# same value python-zlib-ng choose to use as the threshold to release the GIL. + +WEBSOCKET_MAX_SYNC_CHUNK_SIZE = 5 * 1024 + + +class WSMsgType(IntEnum): + # websocket spec types + CONTINUATION = 0x0 + TEXT = 0x1 + BINARY = 0x2 + PING = 0x9 + PONG = 0xA + CLOSE = 0x8 + + # aiohttp specific types + CLOSING = 0x100 + CLOSED = 0x101 + ERROR = 0x102 + + text = TEXT + binary = BINARY + ping = PING + pong = PONG + close = CLOSE + closing = CLOSING + closed = CLOSED + error = ERROR + + +MESSAGE_TYPES_WITH_CONTENT: Final = frozenset( + { + WSMsgType.BINARY, + WSMsgType.TEXT, + WSMsgType.CONTINUATION, + } +) + +WS_KEY: Final[bytes] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11" + + +UNPACK_LEN2 = Struct("!H").unpack_from +UNPACK_LEN3 = Struct("!Q").unpack_from +UNPACK_CLOSE_CODE = Struct("!H").unpack +PACK_LEN1 = Struct("!BB").pack +PACK_LEN2 = Struct("!BBH").pack +PACK_LEN3 = Struct("!BBQ").pack +PACK_CLOSE_CODE = Struct("!H").pack +PACK_RANDBITS = Struct("!L").pack +MSG_SIZE: Final[int] = 2**14 +DEFAULT_LIMIT: Final[int] = 2**16 + + +class WSMessage(NamedTuple): + type: WSMsgType + # To type correctly, this would need some kind of tagged union for each type. + data: Any + extra: Optional[str] + + def json(self, *, loads: Callable[[Any], Any] = json.loads) -> Any: + """Return parsed JSON data. + + .. versionadded:: 0.22 + """ + return loads(self.data) + + +WS_CLOSED_MESSAGE = WSMessage(WSMsgType.CLOSED, None, None) +WS_CLOSING_MESSAGE = WSMessage(WSMsgType.CLOSING, None, None) + + +class WebSocketError(Exception): + """WebSocket protocol parser error.""" + + def __init__(self, code: int, message: str) -> None: + self.code = code + super().__init__(code, message) + + def __str__(self) -> str: + return cast(str, self.args[1]) + + +class WSHandshakeError(Exception): + """WebSocket protocol handshake error.""" + + +native_byteorder: Final[str] = sys.byteorder + + +# Used by _websocket_mask_python +@functools.lru_cache +def _xor_table() -> List[bytes]: + return [bytes(a ^ b for a in range(256)) for b in range(256)] + + +def _websocket_mask_python(mask: bytes, data: bytearray) -> None: + """Websocket masking function. + + `mask` is a `bytes` object of length 4; `data` is a `bytearray` + object of any length. The contents of `data` are masked with `mask`, + as specified in section 5.3 of RFC 6455. + + Note that this function mutates the `data` argument. + + This pure-python implementation may be replaced by an optimized + version when available. + + """ + assert isinstance(data, bytearray), data + assert len(mask) == 4, mask + + if data: + _XOR_TABLE = _xor_table() + a, b, c, d = (_XOR_TABLE[n] for n in mask) + data[::4] = data[::4].translate(a) + data[1::4] = data[1::4].translate(b) + data[2::4] = data[2::4].translate(c) + data[3::4] = data[3::4].translate(d) + + +if NO_EXTENSIONS: # pragma: no cover + _websocket_mask = _websocket_mask_python +else: + try: + from ._websocket import _websocket_mask_cython # type: ignore[import-not-found] + + _websocket_mask = _websocket_mask_cython + except ImportError: # pragma: no cover + _websocket_mask = _websocket_mask_python + +_WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF]) + + +_WS_EXT_RE: Final[Pattern[str]] = re.compile( + r"^(?:;\s*(?:" + r"(server_no_context_takeover)|" + r"(client_no_context_takeover)|" + r"(server_max_window_bits(?:=(\d+))?)|" + r"(client_max_window_bits(?:=(\d+))?)))*$" +) + +_WS_EXT_RE_SPLIT: Final[Pattern[str]] = re.compile(r"permessage-deflate([^,]+)?") + + +def ws_ext_parse(extstr: Optional[str], isserver: bool = False) -> Tuple[int, bool]: + if not extstr: + return 0, False + + compress = 0 + notakeover = False + for ext in _WS_EXT_RE_SPLIT.finditer(extstr): + defext = ext.group(1) + # Return compress = 15 when get `permessage-deflate` + if not defext: + compress = 15 + break + match = _WS_EXT_RE.match(defext) + if match: + compress = 15 + if isserver: + # Server never fail to detect compress handshake. + # Server does not need to send max wbit to client + if match.group(4): + compress = int(match.group(4)) + # Group3 must match if group4 matches + # Compress wbit 8 does not support in zlib + # If compress level not support, + # CONTINUE to next extension + if compress > 15 or compress < 9: + compress = 0 + continue + if match.group(1): + notakeover = True + # Ignore regex group 5 & 6 for client_max_window_bits + break + else: + if match.group(6): + compress = int(match.group(6)) + # Group5 must match if group6 matches + # Compress wbit 8 does not support in zlib + # If compress level not support, + # FAIL the parse progress + if compress > 15 or compress < 9: + raise WSHandshakeError("Invalid window size") + if match.group(2): + notakeover = True + # Ignore regex group 5 & 6 for client_max_window_bits + break + # Return Fail if client side and not match + elif not isserver: + raise WSHandshakeError("Extension for deflate not supported" + ext.group(1)) + + return compress, notakeover + + +def ws_ext_gen( + compress: int = 15, isserver: bool = False, server_notakeover: bool = False +) -> str: + # client_notakeover=False not used for server + # compress wbit 8 does not support in zlib + if compress < 9 or compress > 15: + raise ValueError( + "Compress wbits must between 9 and 15, " "zlib does not support wbits=8" + ) + enabledext = ["permessage-deflate"] + if not isserver: + enabledext.append("client_max_window_bits") + + if compress < 15: + enabledext.append("server_max_window_bits=" + str(compress)) + if server_notakeover: + enabledext.append("server_no_context_takeover") + # if client_notakeover: + # enabledext.append('client_no_context_takeover') + return "; ".join(enabledext) + + +class WSParserState(IntEnum): + READ_HEADER = 1 + READ_PAYLOAD_LENGTH = 2 + READ_PAYLOAD_MASK = 3 + READ_PAYLOAD = 4 + + +class WebSocketReader: + def __init__( + self, queue: DataQueue[WSMessage], max_msg_size: int, compress: bool = True + ) -> None: + self.queue = queue + self._max_msg_size = max_msg_size + + self._exc: Optional[BaseException] = None + self._partial = bytearray() + self._state = WSParserState.READ_HEADER + + self._opcode: Optional[int] = None + self._frame_fin = False + self._frame_opcode: Optional[int] = None + self._frame_payload = bytearray() + + self._tail: bytes = b"" + self._has_mask = False + self._frame_mask: Optional[bytes] = None + self._payload_length = 0 + self._payload_length_flag = 0 + self._compressed: Optional[bool] = None + self._decompressobj: Optional[ZLibDecompressor] = None + self._compress = compress + + def feed_eof(self) -> None: + self.queue.feed_eof() + + def feed_data(self, data: bytes) -> Tuple[bool, bytes]: + if self._exc: + return True, data + + try: + self._feed_data(data) + except Exception as exc: + self._exc = exc + set_exception(self.queue, exc) + return True, b"" + + return False, b"" + + def _feed_data(self, data: bytes) -> None: + for fin, opcode, payload, compressed in self.parse_frame(data): + if opcode in MESSAGE_TYPES_WITH_CONTENT: + # load text/binary + is_continuation = opcode == WSMsgType.CONTINUATION + if not fin: + # got partial frame payload + if not is_continuation: + self._opcode = opcode + self._partial += payload + if self._max_msg_size and len(self._partial) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + "Message size {} exceeds limit {}".format( + len(self._partial), self._max_msg_size + ), + ) + continue + + has_partial = bool(self._partial) + if is_continuation: + if self._opcode is None: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Continuation frame for non started message", + ) + opcode = self._opcode + self._opcode = None + # previous frame was non finished + # we should get continuation opcode + elif has_partial: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "The opcode in non-fin frame is expected " + "to be zero, got {!r}".format(opcode), + ) + + if has_partial: + assembled_payload = self._partial + payload + self._partial.clear() + else: + assembled_payload = payload + + if self._max_msg_size and len(assembled_payload) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + "Message size {} exceeds limit {}".format( + len(assembled_payload), self._max_msg_size + ), + ) + + # Decompress process must to be done after all packets + # received. + if compressed: + if not self._decompressobj: + self._decompressobj = ZLibDecompressor( + suppress_deflate_header=True + ) + payload_merged = self._decompressobj.decompress_sync( + assembled_payload + _WS_DEFLATE_TRAILING, self._max_msg_size + ) + if self._decompressobj.unconsumed_tail: + left = len(self._decompressobj.unconsumed_tail) + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + "Decompressed message size {} exceeds limit {}".format( + self._max_msg_size + left, self._max_msg_size + ), + ) + else: + payload_merged = bytes(assembled_payload) + + if opcode == WSMsgType.TEXT: + try: + text = payload_merged.decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + + self.queue.feed_data(WSMessage(WSMsgType.TEXT, text, ""), len(text)) + continue + + self.queue.feed_data( + WSMessage(WSMsgType.BINARY, payload_merged, ""), len(payload_merged) + ) + elif opcode == WSMsgType.CLOSE: + if len(payload) >= 2: + close_code = UNPACK_CLOSE_CODE(payload[:2])[0] + if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close code: {close_code}", + ) + try: + close_message = payload[2:].decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + msg = WSMessage(WSMsgType.CLOSE, close_code, close_message) + elif payload: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close frame: {fin} {opcode} {payload!r}", + ) + else: + msg = WSMessage(WSMsgType.CLOSE, 0, "") + + self.queue.feed_data(msg, 0) + + elif opcode == WSMsgType.PING: + self.queue.feed_data( + WSMessage(WSMsgType.PING, payload, ""), len(payload) + ) + + elif opcode == WSMsgType.PONG: + self.queue.feed_data( + WSMessage(WSMsgType.PONG, payload, ""), len(payload) + ) + + else: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}" + ) + + def parse_frame( + self, buf: bytes + ) -> List[Tuple[bool, Optional[int], bytearray, Optional[bool]]]: + """Return the next frame from the socket.""" + frames: List[Tuple[bool, Optional[int], bytearray, Optional[bool]]] = [] + if self._tail: + buf, self._tail = self._tail + buf, b"" + + start_pos: int = 0 + buf_length = len(buf) + + while True: + # read header + if self._state is WSParserState.READ_HEADER: + if buf_length - start_pos < 2: + break + data = buf[start_pos : start_pos + 2] + start_pos += 2 + first_byte, second_byte = data + + fin = (first_byte >> 7) & 1 + rsv1 = (first_byte >> 6) & 1 + rsv2 = (first_byte >> 5) & 1 + rsv3 = (first_byte >> 4) & 1 + opcode = first_byte & 0xF + + # frame-fin = %x0 ; more frames of this message follow + # / %x1 ; final frame of this message + # frame-rsv1 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv2 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv3 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # + # Remove rsv1 from this test for deflate development + if rsv2 or rsv3 or (rsv1 and not self._compress): + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + if opcode > 0x7 and fin == 0: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received fragmented control frame", + ) + + has_mask = (second_byte >> 7) & 1 + length = second_byte & 0x7F + + # Control frames MUST have a payload + # length of 125 bytes or less + if opcode > 0x7 and length > 125: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Control frame payload cannot be " "larger than 125 bytes", + ) + + # Set compress status if last package is FIN + # OR set compress status if this is first fragment + # Raise error if not first fragment with rsv1 = 0x1 + if self._frame_fin or self._compressed is None: + self._compressed = True if rsv1 else False + elif rsv1: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + self._frame_fin = bool(fin) + self._frame_opcode = opcode + self._has_mask = bool(has_mask) + self._payload_length_flag = length + self._state = WSParserState.READ_PAYLOAD_LENGTH + + # read payload length + if self._state is WSParserState.READ_PAYLOAD_LENGTH: + length_flag = self._payload_length_flag + if length_flag == 126: + if buf_length - start_pos < 2: + break + data = buf[start_pos : start_pos + 2] + start_pos += 2 + self._payload_length = UNPACK_LEN2(data)[0] + elif length_flag > 126: + if buf_length - start_pos < 8: + break + data = buf[start_pos : start_pos + 8] + start_pos += 8 + self._payload_length = UNPACK_LEN3(data)[0] + else: + self._payload_length = length_flag + + self._state = ( + WSParserState.READ_PAYLOAD_MASK + if self._has_mask + else WSParserState.READ_PAYLOAD + ) + + # read payload mask + if self._state is WSParserState.READ_PAYLOAD_MASK: + if buf_length - start_pos < 4: + break + self._frame_mask = buf[start_pos : start_pos + 4] + start_pos += 4 + self._state = WSParserState.READ_PAYLOAD + + if self._state is WSParserState.READ_PAYLOAD: + length = self._payload_length + payload = self._frame_payload + + chunk_len = buf_length - start_pos + if length >= chunk_len: + self._payload_length = length - chunk_len + payload += buf[start_pos:] + start_pos = buf_length + else: + self._payload_length = 0 + payload += buf[start_pos : start_pos + length] + start_pos = start_pos + length + + if self._payload_length != 0: + break + + if self._has_mask: + assert self._frame_mask is not None + _websocket_mask(self._frame_mask, payload) + + frames.append( + (self._frame_fin, self._frame_opcode, payload, self._compressed) + ) + self._frame_payload = bytearray() + self._state = WSParserState.READ_HEADER + + self._tail = buf[start_pos:] + + return frames + + +class WebSocketWriter: + def __init__( + self, + protocol: BaseProtocol, + transport: asyncio.Transport, + *, + use_mask: bool = False, + limit: int = DEFAULT_LIMIT, + random: random.Random = random.Random(), + compress: int = 0, + notakeover: bool = False, + ) -> None: + self.protocol = protocol + self.transport = transport + self.use_mask = use_mask + self.get_random_bits = partial(random.getrandbits, 32) + self.compress = compress + self.notakeover = notakeover + self._closing = False + self._limit = limit + self._output_size = 0 + self._compressobj: Any = None # actually compressobj + + async def _send_frame( + self, message: bytes, opcode: int, compress: Optional[int] = None + ) -> None: + """Send a frame over the websocket with message as its payload.""" + if self._closing and not (opcode & WSMsgType.CLOSE): + raise ConnectionResetError("Cannot write to closing transport") + + rsv = 0 + + # Only compress larger packets (disabled) + # Does small packet needs to be compressed? + # if self.compress and opcode < 8 and len(message) > 124: + if (compress or self.compress) and opcode < 8: + if compress: + # Do not set self._compress if compressing is for this frame + compressobj = self._make_compress_obj(compress) + else: # self.compress + if not self._compressobj: + self._compressobj = self._make_compress_obj(self.compress) + compressobj = self._compressobj + + message = await compressobj.compress(message) + # Its critical that we do not return control to the event + # loop until we have finished sending all the compressed + # data. Otherwise we could end up mixing compressed frames + # if there are multiple coroutines compressing data. + message += compressobj.flush( + zlib.Z_FULL_FLUSH if self.notakeover else zlib.Z_SYNC_FLUSH + ) + if message.endswith(_WS_DEFLATE_TRAILING): + message = message[:-4] + rsv = rsv | 0x40 + + msg_length = len(message) + + use_mask = self.use_mask + if use_mask: + mask_bit = 0x80 + else: + mask_bit = 0 + + if msg_length < 126: + header = PACK_LEN1(0x80 | rsv | opcode, msg_length | mask_bit) + elif msg_length < (1 << 16): + header = PACK_LEN2(0x80 | rsv | opcode, 126 | mask_bit, msg_length) + else: + header = PACK_LEN3(0x80 | rsv | opcode, 127 | mask_bit, msg_length) + if use_mask: + mask = PACK_RANDBITS(self.get_random_bits()) + message = bytearray(message) + _websocket_mask(mask, message) + self._write(header + mask + message) + self._output_size += len(header) + len(mask) + msg_length + else: + if msg_length > MSG_SIZE: + self._write(header) + self._write(message) + else: + self._write(header + message) + + self._output_size += len(header) + msg_length + + # It is safe to return control to the event loop when using compression + # after this point as we have already sent or buffered all the data. + + if self._output_size > self._limit: + self._output_size = 0 + await self.protocol._drain_helper() + + def _make_compress_obj(self, compress: int) -> ZLibCompressor: + return ZLibCompressor( + level=zlib.Z_BEST_SPEED, + wbits=-compress, + max_sync_chunk_size=WEBSOCKET_MAX_SYNC_CHUNK_SIZE, + ) + + def _write(self, data: bytes) -> None: + if self.transport is None or self.transport.is_closing(): + raise ConnectionResetError("Cannot write to closing transport") + self.transport.write(data) + + async def pong(self, message: Union[bytes, str] = b"") -> None: + """Send pong message.""" + if isinstance(message, str): + message = message.encode("utf-8") + await self._send_frame(message, WSMsgType.PONG) + + async def ping(self, message: Union[bytes, str] = b"") -> None: + """Send ping message.""" + if isinstance(message, str): + message = message.encode("utf-8") + await self._send_frame(message, WSMsgType.PING) + + async def send( + self, + message: Union[str, bytes], + binary: bool = False, + compress: Optional[int] = None, + ) -> None: + """Send a frame over the websocket with message as its payload.""" + if isinstance(message, str): + message = message.encode("utf-8") + if binary: + await self._send_frame(message, WSMsgType.BINARY, compress) + else: + await self._send_frame(message, WSMsgType.TEXT, compress) + + async def close(self, code: int = 1000, message: Union[bytes, str] = b"") -> None: + """Close the websocket, sending the specified code and message.""" + if isinstance(message, str): + message = message.encode("utf-8") + try: + await self._send_frame( + PACK_CLOSE_CODE(code) + message, opcode=WSMsgType.CLOSE + ) + finally: + self._closing = True diff --git a/env/Lib/site-packages/aiohttp/http_writer.py b/env/Lib/site-packages/aiohttp/http_writer.py new file mode 100644 index 0000000..d6b02e6 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/http_writer.py @@ -0,0 +1,198 @@ +"""Http related parsers and protocol.""" + +import asyncio +import zlib +from typing import Any, Awaitable, Callable, NamedTuple, Optional, Union # noqa + +from multidict import CIMultiDict + +from .abc import AbstractStreamWriter +from .base_protocol import BaseProtocol +from .compression_utils import ZLibCompressor +from .helpers import NO_EXTENSIONS + +__all__ = ("StreamWriter", "HttpVersion", "HttpVersion10", "HttpVersion11") + + +class HttpVersion(NamedTuple): + major: int + minor: int + + +HttpVersion10 = HttpVersion(1, 0) +HttpVersion11 = HttpVersion(1, 1) + + +_T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]] +_T_OnHeadersSent = Optional[Callable[["CIMultiDict[str]"], Awaitable[None]]] + + +class StreamWriter(AbstractStreamWriter): + def __init__( + self, + protocol: BaseProtocol, + loop: asyncio.AbstractEventLoop, + on_chunk_sent: _T_OnChunkSent = None, + on_headers_sent: _T_OnHeadersSent = None, + ) -> None: + self._protocol = protocol + + self.loop = loop + self.length = None + self.chunked = False + self.buffer_size = 0 + self.output_size = 0 + + self._eof = False + self._compress: Optional[ZLibCompressor] = None + self._drain_waiter = None + + self._on_chunk_sent: _T_OnChunkSent = on_chunk_sent + self._on_headers_sent: _T_OnHeadersSent = on_headers_sent + + @property + def transport(self) -> Optional[asyncio.Transport]: + return self._protocol.transport + + @property + def protocol(self) -> BaseProtocol: + return self._protocol + + def enable_chunking(self) -> None: + self.chunked = True + + def enable_compression( + self, encoding: str = "deflate", strategy: int = zlib.Z_DEFAULT_STRATEGY + ) -> None: + self._compress = ZLibCompressor(encoding=encoding, strategy=strategy) + + def _write(self, chunk: bytes) -> None: + size = len(chunk) + self.buffer_size += size + self.output_size += size + transport = self.transport + if not self._protocol.connected or transport is None or transport.is_closing(): + raise ConnectionResetError("Cannot write to closing transport") + transport.write(chunk) + + async def write( + self, chunk: bytes, *, drain: bool = True, LIMIT: int = 0x10000 + ) -> None: + """Writes chunk of data to a stream. + + write_eof() indicates end of stream. + writer can't be used after write_eof() method being called. + write() return drain future. + """ + if self._on_chunk_sent is not None: + await self._on_chunk_sent(chunk) + + if isinstance(chunk, memoryview): + if chunk.nbytes != len(chunk): + # just reshape it + chunk = chunk.cast("c") + + if self._compress is not None: + chunk = await self._compress.compress(chunk) + if not chunk: + return + + if self.length is not None: + chunk_len = len(chunk) + if self.length >= chunk_len: + self.length = self.length - chunk_len + else: + chunk = chunk[: self.length] + self.length = 0 + if not chunk: + return + + if chunk: + if self.chunked: + chunk_len_pre = ("%x\r\n" % len(chunk)).encode("ascii") + chunk = chunk_len_pre + chunk + b"\r\n" + + self._write(chunk) + + if self.buffer_size > LIMIT and drain: + self.buffer_size = 0 + await self.drain() + + async def write_headers( + self, status_line: str, headers: "CIMultiDict[str]" + ) -> None: + """Write request/response status and headers.""" + if self._on_headers_sent is not None: + await self._on_headers_sent(headers) + + # status + headers + buf = _serialize_headers(status_line, headers) + self._write(buf) + + async def write_eof(self, chunk: bytes = b"") -> None: + if self._eof: + return + + if chunk and self._on_chunk_sent is not None: + await self._on_chunk_sent(chunk) + + if self._compress: + if chunk: + chunk = await self._compress.compress(chunk) + + chunk += self._compress.flush() + if chunk and self.chunked: + chunk_len = ("%x\r\n" % len(chunk)).encode("ascii") + chunk = chunk_len + chunk + b"\r\n0\r\n\r\n" + else: + if self.chunked: + if chunk: + chunk_len = ("%x\r\n" % len(chunk)).encode("ascii") + chunk = chunk_len + chunk + b"\r\n0\r\n\r\n" + else: + chunk = b"0\r\n\r\n" + + if chunk: + self._write(chunk) + + await self.drain() + + self._eof = True + + async def drain(self) -> None: + """Flush the write buffer. + + The intended use is to write + + await w.write(data) + await w.drain() + """ + if self._protocol.transport is not None: + await self._protocol._drain_helper() + + +def _safe_header(string: str) -> str: + if "\r" in string or "\n" in string: + raise ValueError( + "Newline or carriage return detected in headers. " + "Potential header injection attack." + ) + return string + + +def _py_serialize_headers(status_line: str, headers: "CIMultiDict[str]") -> bytes: + headers_gen = (_safe_header(k) + ": " + _safe_header(v) for k, v in headers.items()) + line = status_line + "\r\n" + "\r\n".join(headers_gen) + "\r\n\r\n" + return line.encode("utf-8") + + +_serialize_headers = _py_serialize_headers + +try: + import aiohttp._http_writer as _http_writer # type: ignore[import-not-found] + + _c_serialize_headers = _http_writer._serialize_headers + if not NO_EXTENSIONS: + _serialize_headers = _c_serialize_headers +except ImportError: + pass diff --git a/env/Lib/site-packages/aiohttp/locks.py b/env/Lib/site-packages/aiohttp/locks.py new file mode 100644 index 0000000..de2dc83 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/locks.py @@ -0,0 +1,41 @@ +import asyncio +import collections +from typing import Any, Deque, Optional + + +class EventResultOrError: + """Event asyncio lock helper class. + + Wraps the Event asyncio lock allowing either to awake the + locked Tasks without any error or raising an exception. + + thanks to @vorpalsmith for the simple design. + """ + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop = loop + self._exc: Optional[BaseException] = None + self._event = asyncio.Event() + self._waiters: Deque[asyncio.Future[Any]] = collections.deque() + + def set(self, exc: Optional[BaseException] = None) -> None: + self._exc = exc + self._event.set() + + async def wait(self) -> Any: + waiter = self._loop.create_task(self._event.wait()) + self._waiters.append(waiter) + try: + val = await waiter + finally: + self._waiters.remove(waiter) + + if self._exc is not None: + raise self._exc + + return val + + def cancel(self) -> None: + """Cancel all waiters""" + for waiter in self._waiters: + waiter.cancel() diff --git a/env/Lib/site-packages/aiohttp/log.py b/env/Lib/site-packages/aiohttp/log.py new file mode 100644 index 0000000..3cecea2 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/log.py @@ -0,0 +1,8 @@ +import logging + +access_logger = logging.getLogger("aiohttp.access") +client_logger = logging.getLogger("aiohttp.client") +internal_logger = logging.getLogger("aiohttp.internal") +server_logger = logging.getLogger("aiohttp.server") +web_logger = logging.getLogger("aiohttp.web") +ws_logger = logging.getLogger("aiohttp.websocket") diff --git a/env/Lib/site-packages/aiohttp/multipart.py b/env/Lib/site-packages/aiohttp/multipart.py new file mode 100644 index 0000000..e3680a7 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/multipart.py @@ -0,0 +1,1056 @@ +import base64 +import binascii +import json +import re +import sys +import uuid +import warnings +import zlib +from collections import deque +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Deque, + Dict, + Iterator, + List, + Mapping, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) +from urllib.parse import parse_qsl, unquote, urlencode + +from multidict import CIMultiDict, CIMultiDictProxy + +from .compression_utils import ZLibCompressor, ZLibDecompressor +from .hdrs import ( + CONTENT_DISPOSITION, + CONTENT_ENCODING, + CONTENT_LENGTH, + CONTENT_TRANSFER_ENCODING, + CONTENT_TYPE, +) +from .helpers import CHAR, TOKEN, parse_mimetype, reify +from .http import HeadersParser +from .payload import ( + JsonPayload, + LookupError, + Order, + Payload, + StringPayload, + get_payload, + payload_type, +) +from .streams import StreamReader + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing import TypeVar + + Self = TypeVar("Self", bound="BodyPartReader") + +__all__ = ( + "MultipartReader", + "MultipartWriter", + "BodyPartReader", + "BadContentDispositionHeader", + "BadContentDispositionParam", + "parse_content_disposition", + "content_disposition_filename", +) + + +if TYPE_CHECKING: + from .client_reqrep import ClientResponse + + +class BadContentDispositionHeader(RuntimeWarning): + pass + + +class BadContentDispositionParam(RuntimeWarning): + pass + + +def parse_content_disposition( + header: Optional[str], +) -> Tuple[Optional[str], Dict[str, str]]: + def is_token(string: str) -> bool: + return bool(string) and TOKEN >= set(string) + + def is_quoted(string: str) -> bool: + return string[0] == string[-1] == '"' + + def is_rfc5987(string: str) -> bool: + return is_token(string) and string.count("'") == 2 + + def is_extended_param(string: str) -> bool: + return string.endswith("*") + + def is_continuous_param(string: str) -> bool: + pos = string.find("*") + 1 + if not pos: + return False + substring = string[pos:-1] if string.endswith("*") else string[pos:] + return substring.isdigit() + + def unescape(text: str, *, chars: str = "".join(map(re.escape, CHAR))) -> str: + return re.sub(f"\\\\([{chars}])", "\\1", text) + + if not header: + return None, {} + + disptype, *parts = header.split(";") + if not is_token(disptype): + warnings.warn(BadContentDispositionHeader(header)) + return None, {} + + params: Dict[str, str] = {} + while parts: + item = parts.pop(0) + + if "=" not in item: + warnings.warn(BadContentDispositionHeader(header)) + return None, {} + + key, value = item.split("=", 1) + key = key.lower().strip() + value = value.lstrip() + + if key in params: + warnings.warn(BadContentDispositionHeader(header)) + return None, {} + + if not is_token(key): + warnings.warn(BadContentDispositionParam(item)) + continue + + elif is_continuous_param(key): + if is_quoted(value): + value = unescape(value[1:-1]) + elif not is_token(value): + warnings.warn(BadContentDispositionParam(item)) + continue + + elif is_extended_param(key): + if is_rfc5987(value): + encoding, _, value = value.split("'", 2) + encoding = encoding or "utf-8" + else: + warnings.warn(BadContentDispositionParam(item)) + continue + + try: + value = unquote(value, encoding, "strict") + except UnicodeDecodeError: # pragma: nocover + warnings.warn(BadContentDispositionParam(item)) + continue + + else: + failed = True + if is_quoted(value): + failed = False + value = unescape(value[1:-1].lstrip("\\/")) + elif is_token(value): + failed = False + elif parts: + # maybe just ; in filename, in any case this is just + # one case fix, for proper fix we need to redesign parser + _value = f"{value};{parts[0]}" + if is_quoted(_value): + parts.pop(0) + value = unescape(_value[1:-1].lstrip("\\/")) + failed = False + + if failed: + warnings.warn(BadContentDispositionHeader(header)) + return None, {} + + params[key] = value + + return disptype.lower(), params + + +def content_disposition_filename( + params: Mapping[str, str], name: str = "filename" +) -> Optional[str]: + name_suf = "%s*" % name + if not params: + return None + elif name_suf in params: + return params[name_suf] + elif name in params: + return params[name] + else: + parts = [] + fnparams = sorted( + (key, value) for key, value in params.items() if key.startswith(name_suf) + ) + for num, (key, value) in enumerate(fnparams): + _, tail = key.split("*", 1) + if tail.endswith("*"): + tail = tail[:-1] + if tail == str(num): + parts.append(value) + else: + break + if not parts: + return None + value = "".join(parts) + if "'" in value: + encoding, _, value = value.split("'", 2) + encoding = encoding or "utf-8" + return unquote(value, encoding, "strict") + return value + + +class MultipartResponseWrapper: + """Wrapper around the MultipartReader. + + It takes care about + underlying connection and close it when it needs in. + """ + + def __init__( + self, + resp: "ClientResponse", + stream: "MultipartReader", + ) -> None: + self.resp = resp + self.stream = stream + + def __aiter__(self) -> "MultipartResponseWrapper": + return self + + async def __anext__( + self, + ) -> Union["MultipartReader", "BodyPartReader"]: + part = await self.next() + if part is None: + raise StopAsyncIteration + return part + + def at_eof(self) -> bool: + """Returns True when all response data had been read.""" + return self.resp.content.at_eof() + + async def next( + self, + ) -> Optional[Union["MultipartReader", "BodyPartReader"]]: + """Emits next multipart reader object.""" + item = await self.stream.next() + if self.stream.at_eof(): + await self.release() + return item + + async def release(self) -> None: + """Release the connection gracefully. + + All remaining content is read to the void. + """ + await self.resp.release() + + +class BodyPartReader: + """Multipart reader for single body part.""" + + chunk_size = 8192 + + def __init__( + self, + boundary: bytes, + headers: "CIMultiDictProxy[str]", + content: StreamReader, + *, + subtype: str = "mixed", + default_charset: Optional[str] = None, + ) -> None: + self.headers = headers + self._boundary = boundary + self._boundary_len = len(boundary) + 2 # Boundary + \r\n + self._content = content + self._default_charset = default_charset + self._at_eof = False + self._is_form_data = subtype == "form-data" + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8 + length = None if self._is_form_data else self.headers.get(CONTENT_LENGTH, None) + self._length = int(length) if length is not None else None + self._read_bytes = 0 + self._unread: Deque[bytes] = deque() + self._prev_chunk: Optional[bytes] = None + self._content_eof = 0 + self._cache: Dict[str, Any] = {} + + def __aiter__(self: Self) -> Self: + return self + + async def __anext__(self) -> bytes: + part = await self.next() + if part is None: + raise StopAsyncIteration + return part + + async def next(self) -> Optional[bytes]: + item = await self.read() + if not item: + return None + return item + + async def read(self, *, decode: bool = False) -> bytes: + """Reads body part data. + + decode: Decodes data following by encoding + method from Content-Encoding header. If it missed + data remains untouched + """ + if self._at_eof: + return b"" + data = bytearray() + while not self._at_eof: + data.extend(await self.read_chunk(self.chunk_size)) + if decode: + return self.decode(data) + return data + + async def read_chunk(self, size: int = chunk_size) -> bytes: + """Reads body part content chunk of the specified size. + + size: chunk size + """ + if self._at_eof: + return b"" + if self._length: + chunk = await self._read_chunk_from_length(size) + else: + chunk = await self._read_chunk_from_stream(size) + + # For the case of base64 data, we must read a fragment of size with a + # remainder of 0 by dividing by 4 for string without symbols \n or \r + encoding = self.headers.get(CONTENT_TRANSFER_ENCODING) + if encoding and encoding.lower() == "base64": + stripped_chunk = b"".join(chunk.split()) + remainder = len(stripped_chunk) % 4 + + while remainder != 0 and not self.at_eof(): + over_chunk_size = 4 - remainder + over_chunk = b"" + + if self._prev_chunk: + over_chunk = self._prev_chunk[:over_chunk_size] + self._prev_chunk = self._prev_chunk[len(over_chunk) :] + + if len(over_chunk) != over_chunk_size: + over_chunk += await self._content.read(4 - len(over_chunk)) + + if not over_chunk: + self._at_eof = True + + stripped_chunk += b"".join(over_chunk.split()) + chunk += over_chunk + remainder = len(stripped_chunk) % 4 + + self._read_bytes += len(chunk) + if self._read_bytes == self._length: + self._at_eof = True + if self._at_eof: + clrf = await self._content.readline() + assert ( + b"\r\n" == clrf + ), "reader did not read all the data or it is malformed" + return chunk + + async def _read_chunk_from_length(self, size: int) -> bytes: + # Reads body part content chunk of the specified size. + # The body part must has Content-Length header with proper value. + assert self._length is not None, "Content-Length required for chunked read" + chunk_size = min(size, self._length - self._read_bytes) + chunk = await self._content.read(chunk_size) + if self._content.at_eof(): + self._at_eof = True + return chunk + + async def _read_chunk_from_stream(self, size: int) -> bytes: + # Reads content chunk of body part with unknown length. + # The Content-Length header for body part is not necessary. + assert ( + size >= self._boundary_len + ), "Chunk size must be greater or equal than boundary length + 2" + first_chunk = self._prev_chunk is None + if first_chunk: + self._prev_chunk = await self._content.read(size) + + chunk = b"" + # content.read() may return less than size, so we need to loop to ensure + # we have enough data to detect the boundary. + while len(chunk) < self._boundary_len: + chunk += await self._content.read(size) + self._content_eof += int(self._content.at_eof()) + assert self._content_eof < 3, "Reading after EOF" + if self._content_eof: + break + if len(chunk) > size: + self._content.unread_data(chunk[size:]) + chunk = chunk[:size] + + assert self._prev_chunk is not None + window = self._prev_chunk + chunk + sub = b"\r\n" + self._boundary + if first_chunk: + idx = window.find(sub) + else: + idx = window.find(sub, max(0, len(self._prev_chunk) - len(sub))) + if idx >= 0: + # pushing boundary back to content + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + self._content.unread_data(window[idx:]) + if size > idx: + self._prev_chunk = self._prev_chunk[:idx] + chunk = window[len(self._prev_chunk) : idx] + if not chunk: + self._at_eof = True + result = self._prev_chunk + self._prev_chunk = chunk + return result + + async def readline(self) -> bytes: + """Reads body part by line by line.""" + if self._at_eof: + return b"" + + if self._unread: + line = self._unread.popleft() + else: + line = await self._content.readline() + + if line.startswith(self._boundary): + # the very last boundary may not come with \r\n, + # so set single rules for everyone + sline = line.rstrip(b"\r\n") + boundary = self._boundary + last_boundary = self._boundary + b"--" + # ensure that we read exactly the boundary, not something alike + if sline == boundary or sline == last_boundary: + self._at_eof = True + self._unread.append(line) + return b"" + else: + next_line = await self._content.readline() + if next_line.startswith(self._boundary): + line = line[:-2] # strip CRLF but only once + self._unread.append(next_line) + + return line + + async def release(self) -> None: + """Like read(), but reads all the data to the void.""" + if self._at_eof: + return + while not self._at_eof: + await self.read_chunk(self.chunk_size) + + async def text(self, *, encoding: Optional[str] = None) -> str: + """Like read(), but assumes that body part contains text data.""" + data = await self.read(decode=True) + # see https://www.w3.org/TR/html5/forms.html#multipart/form-data-encoding-algorithm + # and https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-send + encoding = encoding or self.get_charset(default="utf-8") + return data.decode(encoding) + + async def json(self, *, encoding: Optional[str] = None) -> Optional[Dict[str, Any]]: + """Like read(), but assumes that body parts contains JSON data.""" + data = await self.read(decode=True) + if not data: + return None + encoding = encoding or self.get_charset(default="utf-8") + return cast(Dict[str, Any], json.loads(data.decode(encoding))) + + async def form(self, *, encoding: Optional[str] = None) -> List[Tuple[str, str]]: + """Like read(), but assumes that body parts contain form urlencoded data.""" + data = await self.read(decode=True) + if not data: + return [] + if encoding is not None: + real_encoding = encoding + else: + real_encoding = self.get_charset(default="utf-8") + try: + decoded_data = data.rstrip().decode(real_encoding) + except UnicodeDecodeError: + raise ValueError("data cannot be decoded with %s encoding" % real_encoding) + + return parse_qsl( + decoded_data, + keep_blank_values=True, + encoding=real_encoding, + ) + + def at_eof(self) -> bool: + """Returns True if the boundary was reached or False otherwise.""" + return self._at_eof + + def decode(self, data: bytes) -> bytes: + """Decodes data. + + Decoding is done according the specified Content-Encoding + or Content-Transfer-Encoding headers value. + """ + if CONTENT_TRANSFER_ENCODING in self.headers: + data = self._decode_content_transfer(data) + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8 + if not self._is_form_data and CONTENT_ENCODING in self.headers: + return self._decode_content(data) + return data + + def _decode_content(self, data: bytes) -> bytes: + encoding = self.headers.get(CONTENT_ENCODING, "").lower() + if encoding == "identity": + return data + if encoding in {"deflate", "gzip"}: + return ZLibDecompressor( + encoding=encoding, + suppress_deflate_header=True, + ).decompress_sync(data) + + raise RuntimeError(f"unknown content encoding: {encoding}") + + def _decode_content_transfer(self, data: bytes) -> bytes: + encoding = self.headers.get(CONTENT_TRANSFER_ENCODING, "").lower() + + if encoding == "base64": + return base64.b64decode(data) + elif encoding == "quoted-printable": + return binascii.a2b_qp(data) + elif encoding in ("binary", "8bit", "7bit"): + return data + else: + raise RuntimeError( + "unknown content transfer encoding: {}" "".format(encoding) + ) + + def get_charset(self, default: str) -> str: + """Returns charset parameter from Content-Type header or default.""" + ctype = self.headers.get(CONTENT_TYPE, "") + mimetype = parse_mimetype(ctype) + return mimetype.parameters.get("charset", self._default_charset or default) + + @reify + def name(self) -> Optional[str]: + """Returns name specified in Content-Disposition header. + + If the header is missing or malformed, returns None. + """ + _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) + return content_disposition_filename(params, "name") + + @reify + def filename(self) -> Optional[str]: + """Returns filename specified in Content-Disposition header. + + Returns None if the header is missing or malformed. + """ + _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) + return content_disposition_filename(params, "filename") + + +@payload_type(BodyPartReader, order=Order.try_first) +class BodyPartReaderPayload(Payload): + def __init__(self, value: BodyPartReader, *args: Any, **kwargs: Any) -> None: + super().__init__(value, *args, **kwargs) + + params: Dict[str, str] = {} + if value.name is not None: + params["name"] = value.name + if value.filename is not None: + params["filename"] = value.filename + + if params: + self.set_content_disposition("attachment", True, **params) + + async def write(self, writer: Any) -> None: + field = self._value + chunk = await field.read_chunk(size=2**16) + while chunk: + await writer.write(field.decode(chunk)) + chunk = await field.read_chunk(size=2**16) + + +class MultipartReader: + """Multipart body reader.""" + + #: Response wrapper, used when multipart readers constructs from response. + response_wrapper_cls = MultipartResponseWrapper + #: Multipart reader class, used to handle multipart/* body parts. + #: None points to type(self) + multipart_reader_cls: Optional[Type["MultipartReader"]] = None + #: Body part reader class for non multipart/* content types. + part_reader_cls = BodyPartReader + + def __init__(self, headers: Mapping[str, str], content: StreamReader) -> None: + self._mimetype = parse_mimetype(headers[CONTENT_TYPE]) + assert self._mimetype.type == "multipart", "multipart/* content type expected" + if "boundary" not in self._mimetype.parameters: + raise ValueError( + "boundary missed for Content-Type: %s" % headers[CONTENT_TYPE] + ) + + self.headers = headers + self._boundary = ("--" + self._get_boundary()).encode() + self._content = content + self._default_charset: Optional[str] = None + self._last_part: Optional[Union["MultipartReader", BodyPartReader]] = None + self._at_eof = False + self._at_bof = True + self._unread: List[bytes] = [] + + def __aiter__(self: Self) -> Self: + return self + + async def __anext__( + self, + ) -> Optional[Union["MultipartReader", BodyPartReader]]: + part = await self.next() + if part is None: + raise StopAsyncIteration + return part + + @classmethod + def from_response( + cls, + response: "ClientResponse", + ) -> MultipartResponseWrapper: + """Constructs reader instance from HTTP response. + + :param response: :class:`~aiohttp.client.ClientResponse` instance + """ + obj = cls.response_wrapper_cls( + response, cls(response.headers, response.content) + ) + return obj + + def at_eof(self) -> bool: + """Returns True if the final boundary was reached, false otherwise.""" + return self._at_eof + + async def next( + self, + ) -> Optional[Union["MultipartReader", BodyPartReader]]: + """Emits the next multipart body part.""" + # So, if we're at BOF, we need to skip till the boundary. + if self._at_eof: + return None + await self._maybe_release_last_part() + if self._at_bof: + await self._read_until_first_boundary() + self._at_bof = False + else: + await self._read_boundary() + if self._at_eof: # we just read the last boundary, nothing to do there + return None + + part = await self.fetch_next_part() + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.6 + if ( + self._last_part is None + and self._mimetype.subtype == "form-data" + and isinstance(part, BodyPartReader) + ): + _, params = parse_content_disposition(part.headers.get(CONTENT_DISPOSITION)) + if params.get("name") == "_charset_": + # Longest encoding in https://encoding.spec.whatwg.org/encodings.json + # is 19 characters, so 32 should be more than enough for any valid encoding. + charset = await part.read_chunk(32) + if len(charset) > 31: + raise RuntimeError("Invalid default charset") + self._default_charset = charset.strip().decode() + part = await self.fetch_next_part() + self._last_part = part + return self._last_part + + async def release(self) -> None: + """Reads all the body parts to the void till the final boundary.""" + while not self._at_eof: + item = await self.next() + if item is None: + break + await item.release() + + async def fetch_next_part( + self, + ) -> Union["MultipartReader", BodyPartReader]: + """Returns the next body part reader.""" + headers = await self._read_headers() + return self._get_part_reader(headers) + + def _get_part_reader( + self, + headers: "CIMultiDictProxy[str]", + ) -> Union["MultipartReader", BodyPartReader]: + """Dispatches the response by the `Content-Type` header. + + Returns a suitable reader instance. + + :param dict headers: Response headers + """ + ctype = headers.get(CONTENT_TYPE, "") + mimetype = parse_mimetype(ctype) + + if mimetype.type == "multipart": + if self.multipart_reader_cls is None: + return type(self)(headers, self._content) + return self.multipart_reader_cls(headers, self._content) + else: + return self.part_reader_cls( + self._boundary, + headers, + self._content, + subtype=self._mimetype.subtype, + default_charset=self._default_charset, + ) + + def _get_boundary(self) -> str: + boundary = self._mimetype.parameters["boundary"] + if len(boundary) > 70: + raise ValueError("boundary %r is too long (70 chars max)" % boundary) + + return boundary + + async def _readline(self) -> bytes: + if self._unread: + return self._unread.pop() + return await self._content.readline() + + async def _read_until_first_boundary(self) -> None: + while True: + chunk = await self._readline() + if chunk == b"": + raise ValueError( + "Could not find starting boundary %r" % (self._boundary) + ) + chunk = chunk.rstrip() + if chunk == self._boundary: + return + elif chunk == self._boundary + b"--": + self._at_eof = True + return + + async def _read_boundary(self) -> None: + chunk = (await self._readline()).rstrip() + if chunk == self._boundary: + pass + elif chunk == self._boundary + b"--": + self._at_eof = True + epilogue = await self._readline() + next_line = await self._readline() + + # the epilogue is expected and then either the end of input or the + # parent multipart boundary, if the parent boundary is found then + # it should be marked as unread and handed to the parent for + # processing + if next_line[:2] == b"--": + self._unread.append(next_line) + # otherwise the request is likely missing an epilogue and both + # lines should be passed to the parent for processing + # (this handles the old behavior gracefully) + else: + self._unread.extend([next_line, epilogue]) + else: + raise ValueError(f"Invalid boundary {chunk!r}, expected {self._boundary!r}") + + async def _read_headers(self) -> "CIMultiDictProxy[str]": + lines = [b""] + while True: + chunk = await self._content.readline() + chunk = chunk.strip() + lines.append(chunk) + if not chunk: + break + parser = HeadersParser() + headers, raw_headers = parser.parse_headers(lines) + return headers + + async def _maybe_release_last_part(self) -> None: + """Ensures that the last read body part is read completely.""" + if self._last_part is not None: + if not self._last_part.at_eof(): + await self._last_part.release() + self._unread.extend(self._last_part._unread) + self._last_part = None + + +_Part = Tuple[Payload, str, str] + + +class MultipartWriter(Payload): + """Multipart body writer.""" + + def __init__(self, subtype: str = "mixed", boundary: Optional[str] = None) -> None: + boundary = boundary if boundary is not None else uuid.uuid4().hex + # The underlying Payload API demands a str (utf-8), not bytes, + # so we need to ensure we don't lose anything during conversion. + # As a result, require the boundary to be ASCII only. + # In both situations. + + try: + self._boundary = boundary.encode("ascii") + except UnicodeEncodeError: + raise ValueError("boundary should contain ASCII only chars") from None + ctype = f"multipart/{subtype}; boundary={self._boundary_value}" + + super().__init__(None, content_type=ctype) + + self._parts: List[_Part] = [] + self._is_form_data = subtype == "form-data" + + def __enter__(self) -> "MultipartWriter": + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + pass + + def __iter__(self) -> Iterator[_Part]: + return iter(self._parts) + + def __len__(self) -> int: + return len(self._parts) + + def __bool__(self) -> bool: + return True + + _valid_tchar_regex = re.compile(rb"\A[!#$%&'*+\-.^_`|~\w]+\Z") + _invalid_qdtext_char_regex = re.compile(rb"[\x00-\x08\x0A-\x1F\x7F]") + + @property + def _boundary_value(self) -> str: + """Wrap boundary parameter value in quotes, if necessary. + + Reads self.boundary and returns a unicode string. + """ + # Refer to RFCs 7231, 7230, 5234. + # + # parameter = token "=" ( token / quoted-string ) + # token = 1*tchar + # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + # qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + # obs-text = %x80-FF + # quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + # / DIGIT / ALPHA + # ; any VCHAR, except delimiters + # VCHAR = %x21-7E + value = self._boundary + if re.match(self._valid_tchar_regex, value): + return value.decode("ascii") # cannot fail + + if re.search(self._invalid_qdtext_char_regex, value): + raise ValueError("boundary value contains invalid characters") + + # escape %x5C and %x22 + quoted_value_content = value.replace(b"\\", b"\\\\") + quoted_value_content = quoted_value_content.replace(b'"', b'\\"') + + return '"' + quoted_value_content.decode("ascii") + '"' + + @property + def boundary(self) -> str: + return self._boundary.decode("ascii") + + def append(self, obj: Any, headers: Optional[Mapping[str, str]] = None) -> Payload: + if headers is None: + headers = CIMultiDict() + + if isinstance(obj, Payload): + obj.headers.update(headers) + return self.append_payload(obj) + else: + try: + payload = get_payload(obj, headers=headers) + except LookupError: + raise TypeError("Cannot create payload from %r" % obj) + else: + return self.append_payload(payload) + + def append_payload(self, payload: Payload) -> Payload: + """Adds a new body part to multipart writer.""" + encoding: Optional[str] = None + te_encoding: Optional[str] = None + if self._is_form_data: + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.7 + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8 + assert ( + not {CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TRANSFER_ENCODING} + & payload.headers.keys() + ) + # Set default Content-Disposition in case user doesn't create one + if CONTENT_DISPOSITION not in payload.headers: + name = f"section-{len(self._parts)}" + payload.set_content_disposition("form-data", name=name) + else: + # compression + encoding = payload.headers.get(CONTENT_ENCODING, "").lower() + if encoding and encoding not in ("deflate", "gzip", "identity"): + raise RuntimeError(f"unknown content encoding: {encoding}") + if encoding == "identity": + encoding = None + + # te encoding + te_encoding = payload.headers.get(CONTENT_TRANSFER_ENCODING, "").lower() + if te_encoding not in ("", "base64", "quoted-printable", "binary"): + raise RuntimeError(f"unknown content transfer encoding: {te_encoding}") + if te_encoding == "binary": + te_encoding = None + + # size + size = payload.size + if size is not None and not (encoding or te_encoding): + payload.headers[CONTENT_LENGTH] = str(size) + + self._parts.append((payload, encoding, te_encoding)) # type: ignore[arg-type] + return payload + + def append_json( + self, obj: Any, headers: Optional[Mapping[str, str]] = None + ) -> Payload: + """Helper to append JSON part.""" + if headers is None: + headers = CIMultiDict() + + return self.append_payload(JsonPayload(obj, headers=headers)) + + def append_form( + self, + obj: Union[Sequence[Tuple[str, str]], Mapping[str, str]], + headers: Optional[Mapping[str, str]] = None, + ) -> Payload: + """Helper to append form urlencoded part.""" + assert isinstance(obj, (Sequence, Mapping)) + + if headers is None: + headers = CIMultiDict() + + if isinstance(obj, Mapping): + obj = list(obj.items()) + data = urlencode(obj, doseq=True) + + return self.append_payload( + StringPayload( + data, headers=headers, content_type="application/x-www-form-urlencoded" + ) + ) + + @property + def size(self) -> Optional[int]: + """Size of the payload.""" + total = 0 + for part, encoding, te_encoding in self._parts: + if encoding or te_encoding or part.size is None: + return None + + total += int( + 2 + + len(self._boundary) + + 2 + + part.size # b'--'+self._boundary+b'\r\n' + + len(part._binary_headers) + + 2 # b'\r\n' + ) + + total += 2 + len(self._boundary) + 4 # b'--'+self._boundary+b'--\r\n' + return total + + async def write(self, writer: Any, close_boundary: bool = True) -> None: + """Write body.""" + for part, encoding, te_encoding in self._parts: + if self._is_form_data: + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.2 + assert CONTENT_DISPOSITION in part.headers + assert "name=" in part.headers[CONTENT_DISPOSITION] + + await writer.write(b"--" + self._boundary + b"\r\n") + await writer.write(part._binary_headers) + + if encoding or te_encoding: + w = MultipartPayloadWriter(writer) + if encoding: + w.enable_compression(encoding) + if te_encoding: + w.enable_encoding(te_encoding) + await part.write(w) # type: ignore[arg-type] + await w.write_eof() + else: + await part.write(writer) + + await writer.write(b"\r\n") + + if close_boundary: + await writer.write(b"--" + self._boundary + b"--\r\n") + + +class MultipartPayloadWriter: + def __init__(self, writer: Any) -> None: + self._writer = writer + self._encoding: Optional[str] = None + self._compress: Optional[ZLibCompressor] = None + self._encoding_buffer: Optional[bytearray] = None + + def enable_encoding(self, encoding: str) -> None: + if encoding == "base64": + self._encoding = encoding + self._encoding_buffer = bytearray() + elif encoding == "quoted-printable": + self._encoding = "quoted-printable" + + def enable_compression( + self, encoding: str = "deflate", strategy: int = zlib.Z_DEFAULT_STRATEGY + ) -> None: + self._compress = ZLibCompressor( + encoding=encoding, + suppress_deflate_header=True, + strategy=strategy, + ) + + async def write_eof(self) -> None: + if self._compress is not None: + chunk = self._compress.flush() + if chunk: + self._compress = None + await self.write(chunk) + + if self._encoding == "base64": + if self._encoding_buffer: + await self._writer.write(base64.b64encode(self._encoding_buffer)) + + async def write(self, chunk: bytes) -> None: + if self._compress is not None: + if chunk: + chunk = await self._compress.compress(chunk) + if not chunk: + return + + if self._encoding == "base64": + buf = self._encoding_buffer + assert buf is not None + buf.extend(chunk) + + if buf: + div, mod = divmod(len(buf), 3) + enc_chunk, self._encoding_buffer = (buf[: div * 3], buf[div * 3 :]) + if enc_chunk: + b64chunk = base64.b64encode(enc_chunk) + await self._writer.write(b64chunk) + elif self._encoding == "quoted-printable": + await self._writer.write(binascii.b2a_qp(chunk)) + else: + await self._writer.write(chunk) diff --git a/env/Lib/site-packages/aiohttp/payload.py b/env/Lib/site-packages/aiohttp/payload.py new file mode 100644 index 0000000..5271393 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/payload.py @@ -0,0 +1,464 @@ +import asyncio +import enum +import io +import json +import mimetypes +import os +import warnings +from abc import ABC, abstractmethod +from itertools import chain +from typing import ( + IO, + TYPE_CHECKING, + Any, + Dict, + Final, + Iterable, + Optional, + TextIO, + Tuple, + Type, + Union, +) + +from multidict import CIMultiDict + +from . import hdrs +from .abc import AbstractStreamWriter +from .helpers import ( + _SENTINEL, + content_disposition_header, + guess_filename, + parse_mimetype, + sentinel, +) +from .streams import StreamReader +from .typedefs import JSONEncoder, _CIMultiDict + +__all__ = ( + "PAYLOAD_REGISTRY", + "get_payload", + "payload_type", + "Payload", + "BytesPayload", + "StringPayload", + "IOBasePayload", + "BytesIOPayload", + "BufferedReaderPayload", + "TextIOPayload", + "StringIOPayload", + "JsonPayload", + "AsyncIterablePayload", +) + +TOO_LARGE_BYTES_BODY: Final[int] = 2**20 # 1 MB + +if TYPE_CHECKING: + from typing import List + + +class LookupError(Exception): + pass + + +class Order(str, enum.Enum): + normal = "normal" + try_first = "try_first" + try_last = "try_last" + + +def get_payload(data: Any, *args: Any, **kwargs: Any) -> "Payload": + return PAYLOAD_REGISTRY.get(data, *args, **kwargs) + + +def register_payload( + factory: Type["Payload"], type: Any, *, order: Order = Order.normal +) -> None: + PAYLOAD_REGISTRY.register(factory, type, order=order) + + +class payload_type: + def __init__(self, type: Any, *, order: Order = Order.normal) -> None: + self.type = type + self.order = order + + def __call__(self, factory: Type["Payload"]) -> Type["Payload"]: + register_payload(factory, self.type, order=self.order) + return factory + + +PayloadType = Type["Payload"] +_PayloadRegistryItem = Tuple[PayloadType, Any] + + +class PayloadRegistry: + """Payload registry. + + note: we need zope.interface for more efficient adapter search + """ + + def __init__(self) -> None: + self._first: List[_PayloadRegistryItem] = [] + self._normal: List[_PayloadRegistryItem] = [] + self._last: List[_PayloadRegistryItem] = [] + + def get( + self, + data: Any, + *args: Any, + _CHAIN: "Type[chain[_PayloadRegistryItem]]" = chain, + **kwargs: Any, + ) -> "Payload": + if isinstance(data, Payload): + return data + for factory, type in _CHAIN(self._first, self._normal, self._last): + if isinstance(data, type): + return factory(data, *args, **kwargs) + + raise LookupError() + + def register( + self, factory: PayloadType, type: Any, *, order: Order = Order.normal + ) -> None: + if order is Order.try_first: + self._first.append((factory, type)) + elif order is Order.normal: + self._normal.append((factory, type)) + elif order is Order.try_last: + self._last.append((factory, type)) + else: + raise ValueError(f"Unsupported order {order!r}") + + +class Payload(ABC): + + _default_content_type: str = "application/octet-stream" + _size: Optional[int] = None + + def __init__( + self, + value: Any, + headers: Optional[ + Union[_CIMultiDict, Dict[str, str], Iterable[Tuple[str, str]]] + ] = None, + content_type: Union[str, None, _SENTINEL] = sentinel, + filename: Optional[str] = None, + encoding: Optional[str] = None, + **kwargs: Any, + ) -> None: + self._encoding = encoding + self._filename = filename + self._headers: _CIMultiDict = CIMultiDict() + self._value = value + if content_type is not sentinel and content_type is not None: + self._headers[hdrs.CONTENT_TYPE] = content_type + elif self._filename is not None: + content_type = mimetypes.guess_type(self._filename)[0] + if content_type is None: + content_type = self._default_content_type + self._headers[hdrs.CONTENT_TYPE] = content_type + else: + self._headers[hdrs.CONTENT_TYPE] = self._default_content_type + self._headers.update(headers or {}) + + @property + def size(self) -> Optional[int]: + """Size of the payload.""" + return self._size + + @property + def filename(self) -> Optional[str]: + """Filename of the payload.""" + return self._filename + + @property + def headers(self) -> _CIMultiDict: + """Custom item headers""" + return self._headers + + @property + def _binary_headers(self) -> bytes: + return ( + "".join([k + ": " + v + "\r\n" for k, v in self.headers.items()]).encode( + "utf-8" + ) + + b"\r\n" + ) + + @property + def encoding(self) -> Optional[str]: + """Payload encoding""" + return self._encoding + + @property + def content_type(self) -> str: + """Content type""" + return self._headers[hdrs.CONTENT_TYPE] + + def set_content_disposition( + self, + disptype: str, + quote_fields: bool = True, + _charset: str = "utf-8", + **params: Any, + ) -> None: + """Sets ``Content-Disposition`` header.""" + self._headers[hdrs.CONTENT_DISPOSITION] = content_disposition_header( + disptype, quote_fields=quote_fields, _charset=_charset, **params + ) + + @abstractmethod + async def write(self, writer: AbstractStreamWriter) -> None: + """Write payload. + + writer is an AbstractStreamWriter instance: + """ + + +class BytesPayload(Payload): + def __init__( + self, value: Union[bytes, bytearray, memoryview], *args: Any, **kwargs: Any + ) -> None: + if not isinstance(value, (bytes, bytearray, memoryview)): + raise TypeError(f"value argument must be byte-ish, not {type(value)!r}") + + if "content_type" not in kwargs: + kwargs["content_type"] = "application/octet-stream" + + super().__init__(value, *args, **kwargs) + + if isinstance(value, memoryview): + self._size = value.nbytes + else: + self._size = len(value) + + if self._size > TOO_LARGE_BYTES_BODY: + kwargs = {"source": self} + warnings.warn( + "Sending a large body directly with raw bytes might" + " lock the event loop. You should probably pass an " + "io.BytesIO object instead", + ResourceWarning, + **kwargs, + ) + + async def write(self, writer: AbstractStreamWriter) -> None: + await writer.write(self._value) + + +class StringPayload(BytesPayload): + def __init__( + self, + value: str, + *args: Any, + encoding: Optional[str] = None, + content_type: Optional[str] = None, + **kwargs: Any, + ) -> None: + + if encoding is None: + if content_type is None: + real_encoding = "utf-8" + content_type = "text/plain; charset=utf-8" + else: + mimetype = parse_mimetype(content_type) + real_encoding = mimetype.parameters.get("charset", "utf-8") + else: + if content_type is None: + content_type = "text/plain; charset=%s" % encoding + real_encoding = encoding + + super().__init__( + value.encode(real_encoding), + encoding=real_encoding, + content_type=content_type, + *args, + **kwargs, + ) + + +class StringIOPayload(StringPayload): + def __init__(self, value: IO[str], *args: Any, **kwargs: Any) -> None: + super().__init__(value.read(), *args, **kwargs) + + +class IOBasePayload(Payload): + _value: IO[Any] + + def __init__( + self, value: IO[Any], disposition: str = "attachment", *args: Any, **kwargs: Any + ) -> None: + if "filename" not in kwargs: + kwargs["filename"] = guess_filename(value) + + super().__init__(value, *args, **kwargs) + + if self._filename is not None and disposition is not None: + if hdrs.CONTENT_DISPOSITION not in self.headers: + self.set_content_disposition(disposition, filename=self._filename) + + async def write(self, writer: AbstractStreamWriter) -> None: + loop = asyncio.get_event_loop() + try: + chunk = await loop.run_in_executor(None, self._value.read, 2**16) + while chunk: + await writer.write(chunk) + chunk = await loop.run_in_executor(None, self._value.read, 2**16) + finally: + await loop.run_in_executor(None, self._value.close) + + +class TextIOPayload(IOBasePayload): + _value: TextIO + + def __init__( + self, + value: TextIO, + *args: Any, + encoding: Optional[str] = None, + content_type: Optional[str] = None, + **kwargs: Any, + ) -> None: + + if encoding is None: + if content_type is None: + encoding = "utf-8" + content_type = "text/plain; charset=utf-8" + else: + mimetype = parse_mimetype(content_type) + encoding = mimetype.parameters.get("charset", "utf-8") + else: + if content_type is None: + content_type = "text/plain; charset=%s" % encoding + + super().__init__( + value, + content_type=content_type, + encoding=encoding, + *args, + **kwargs, + ) + + @property + def size(self) -> Optional[int]: + try: + return os.fstat(self._value.fileno()).st_size - self._value.tell() + except OSError: + return None + + async def write(self, writer: AbstractStreamWriter) -> None: + loop = asyncio.get_event_loop() + try: + chunk = await loop.run_in_executor(None, self._value.read, 2**16) + while chunk: + data = ( + chunk.encode(encoding=self._encoding) + if self._encoding + else chunk.encode() + ) + await writer.write(data) + chunk = await loop.run_in_executor(None, self._value.read, 2**16) + finally: + await loop.run_in_executor(None, self._value.close) + + +class BytesIOPayload(IOBasePayload): + @property + def size(self) -> int: + position = self._value.tell() + end = self._value.seek(0, os.SEEK_END) + self._value.seek(position) + return end - position + + +class BufferedReaderPayload(IOBasePayload): + @property + def size(self) -> Optional[int]: + try: + return os.fstat(self._value.fileno()).st_size - self._value.tell() + except OSError: + # data.fileno() is not supported, e.g. + # io.BufferedReader(io.BytesIO(b'data')) + return None + + +class JsonPayload(BytesPayload): + def __init__( + self, + value: Any, + encoding: str = "utf-8", + content_type: str = "application/json", + dumps: JSONEncoder = json.dumps, + *args: Any, + **kwargs: Any, + ) -> None: + + super().__init__( + dumps(value).encode(encoding), + content_type=content_type, + encoding=encoding, + *args, + **kwargs, + ) + + +if TYPE_CHECKING: + from typing import AsyncIterable, AsyncIterator + + _AsyncIterator = AsyncIterator[bytes] + _AsyncIterable = AsyncIterable[bytes] +else: + from collections.abc import AsyncIterable, AsyncIterator + + _AsyncIterator = AsyncIterator + _AsyncIterable = AsyncIterable + + +class AsyncIterablePayload(Payload): + + _iter: Optional[_AsyncIterator] = None + + def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None: + if not isinstance(value, AsyncIterable): + raise TypeError( + "value argument must support " + "collections.abc.AsyncIterable interface, " + "got {!r}".format(type(value)) + ) + + if "content_type" not in kwargs: + kwargs["content_type"] = "application/octet-stream" + + super().__init__(value, *args, **kwargs) + + self._iter = value.__aiter__() + + async def write(self, writer: AbstractStreamWriter) -> None: + if self._iter: + try: + # iter is not None check prevents rare cases + # when the case iterable is used twice + while True: + chunk = await self._iter.__anext__() + await writer.write(chunk) + except StopAsyncIteration: + self._iter = None + + +class StreamReaderPayload(AsyncIterablePayload): + def __init__(self, value: StreamReader, *args: Any, **kwargs: Any) -> None: + super().__init__(value.iter_any(), *args, **kwargs) + + +PAYLOAD_REGISTRY = PayloadRegistry() +PAYLOAD_REGISTRY.register(BytesPayload, (bytes, bytearray, memoryview)) +PAYLOAD_REGISTRY.register(StringPayload, str) +PAYLOAD_REGISTRY.register(StringIOPayload, io.StringIO) +PAYLOAD_REGISTRY.register(TextIOPayload, io.TextIOBase) +PAYLOAD_REGISTRY.register(BytesIOPayload, io.BytesIO) +PAYLOAD_REGISTRY.register(BufferedReaderPayload, (io.BufferedReader, io.BufferedRandom)) +PAYLOAD_REGISTRY.register(IOBasePayload, io.IOBase) +PAYLOAD_REGISTRY.register(StreamReaderPayload, StreamReader) +# try_last for giving a chance to more specialized async interables like +# multidict.BodyPartReaderPayload override the default +PAYLOAD_REGISTRY.register(AsyncIterablePayload, AsyncIterable, order=Order.try_last) diff --git a/env/Lib/site-packages/aiohttp/payload_streamer.py b/env/Lib/site-packages/aiohttp/payload_streamer.py new file mode 100644 index 0000000..364f763 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/payload_streamer.py @@ -0,0 +1,75 @@ +""" +Payload implementation for coroutines as data provider. + +As a simple case, you can upload data from file:: + + @aiohttp.streamer + async def file_sender(writer, file_name=None): + with open(file_name, 'rb') as f: + chunk = f.read(2**16) + while chunk: + await writer.write(chunk) + + chunk = f.read(2**16) + +Then you can use `file_sender` like this: + + async with session.post('http://httpbin.org/post', + data=file_sender(file_name='huge_file')) as resp: + print(await resp.text()) + +..note:: Coroutine must accept `writer` as first argument + +""" + +import types +import warnings +from typing import Any, Awaitable, Callable, Dict, Tuple + +from .abc import AbstractStreamWriter +from .payload import Payload, payload_type + +__all__ = ("streamer",) + + +class _stream_wrapper: + def __init__( + self, + coro: Callable[..., Awaitable[None]], + args: Tuple[Any, ...], + kwargs: Dict[str, Any], + ) -> None: + self.coro = types.coroutine(coro) + self.args = args + self.kwargs = kwargs + + async def __call__(self, writer: AbstractStreamWriter) -> None: + await self.coro(writer, *self.args, **self.kwargs) + + +class streamer: + def __init__(self, coro: Callable[..., Awaitable[None]]) -> None: + warnings.warn( + "@streamer is deprecated, use async generators instead", + DeprecationWarning, + stacklevel=2, + ) + self.coro = coro + + def __call__(self, *args: Any, **kwargs: Any) -> _stream_wrapper: + return _stream_wrapper(self.coro, args, kwargs) + + +@payload_type(_stream_wrapper) +class StreamWrapperPayload(Payload): + async def write(self, writer: AbstractStreamWriter) -> None: + await self._value(writer) + + +@payload_type(streamer) +class StreamPayload(StreamWrapperPayload): + def __init__(self, value: Any, *args: Any, **kwargs: Any) -> None: + super().__init__(value(), *args, **kwargs) + + async def write(self, writer: AbstractStreamWriter) -> None: + await self._value(writer) diff --git a/env/Lib/site-packages/aiohttp/py.typed b/env/Lib/site-packages/aiohttp/py.typed new file mode 100644 index 0000000..f5642f7 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/py.typed @@ -0,0 +1 @@ +Marker diff --git a/env/Lib/site-packages/aiohttp/pytest_plugin.py b/env/Lib/site-packages/aiohttp/pytest_plugin.py new file mode 100644 index 0000000..c862b40 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/pytest_plugin.py @@ -0,0 +1,407 @@ +import asyncio +import contextlib +import inspect +import warnings +from typing import ( + Any, + Awaitable, + Callable, + Dict, + Iterator, + Optional, + Protocol, + Type, + Union, +) + +import pytest + +from aiohttp.web import Application + +from .test_utils import ( + BaseTestServer, + RawTestServer, + TestClient, + TestServer, + loop_context, + setup_test_loop, + teardown_test_loop, + unused_port as _unused_port, +) + +try: + import uvloop +except ImportError: # pragma: no cover + uvloop = None # type: ignore[assignment] + +AiohttpRawServer = Callable[[Application], Awaitable[RawTestServer]] + + +class AiohttpClient(Protocol): + def __call__( + self, + __param: Union[Application, BaseTestServer], + *, + server_kwargs: Optional[Dict[str, Any]] = None, + **kwargs: Any + ) -> Awaitable[TestClient]: ... + + +class AiohttpServer(Protocol): + def __call__( + self, app: Application, *, port: Optional[int] = None, **kwargs: Any + ) -> Awaitable[TestServer]: ... + + +def pytest_addoption(parser): # type: ignore[no-untyped-def] + parser.addoption( + "--aiohttp-fast", + action="store_true", + default=False, + help="run tests faster by disabling extra checks", + ) + parser.addoption( + "--aiohttp-loop", + action="store", + default="pyloop", + help="run tests with specific loop: pyloop, uvloop or all", + ) + parser.addoption( + "--aiohttp-enable-loop-debug", + action="store_true", + default=False, + help="enable event loop debug mode", + ) + + +def pytest_fixture_setup(fixturedef): # type: ignore[no-untyped-def] + """Set up pytest fixture. + + Allow fixtures to be coroutines. Run coroutine fixtures in an event loop. + """ + func = fixturedef.func + + if inspect.isasyncgenfunction(func): + # async generator fixture + is_async_gen = True + elif asyncio.iscoroutinefunction(func): + # regular async fixture + is_async_gen = False + else: + # not an async fixture, nothing to do + return + + strip_request = False + if "request" not in fixturedef.argnames: + fixturedef.argnames += ("request",) + strip_request = True + + def wrapper(*args, **kwargs): # type: ignore[no-untyped-def] + request = kwargs["request"] + if strip_request: + del kwargs["request"] + + # if neither the fixture nor the test use the 'loop' fixture, + # 'getfixturevalue' will fail because the test is not parameterized + # (this can be removed someday if 'loop' is no longer parameterized) + if "loop" not in request.fixturenames: + raise Exception( + "Asynchronous fixtures must depend on the 'loop' fixture or " + "be used in tests depending from it." + ) + + _loop = request.getfixturevalue("loop") + + if is_async_gen: + # for async generators, we need to advance the generator once, + # then advance it again in a finalizer + gen = func(*args, **kwargs) + + def finalizer(): # type: ignore[no-untyped-def] + try: + return _loop.run_until_complete(gen.__anext__()) + except StopAsyncIteration: + pass + + request.addfinalizer(finalizer) + return _loop.run_until_complete(gen.__anext__()) + else: + return _loop.run_until_complete(func(*args, **kwargs)) + + fixturedef.func = wrapper + + +@pytest.fixture +def fast(request): # type: ignore[no-untyped-def] + """--fast config option""" + return request.config.getoption("--aiohttp-fast") + + +@pytest.fixture +def loop_debug(request): # type: ignore[no-untyped-def] + """--enable-loop-debug config option""" + return request.config.getoption("--aiohttp-enable-loop-debug") + + +@contextlib.contextmanager +def _runtime_warning_context(): # type: ignore[no-untyped-def] + """Context manager which checks for RuntimeWarnings. + + This exists specifically to + avoid "coroutine 'X' was never awaited" warnings being missed. + + If RuntimeWarnings occur in the context a RuntimeError is raised. + """ + with warnings.catch_warnings(record=True) as _warnings: + yield + rw = [ + "{w.filename}:{w.lineno}:{w.message}".format(w=w) + for w in _warnings + if w.category == RuntimeWarning + ] + if rw: + raise RuntimeError( + "{} Runtime Warning{},\n{}".format( + len(rw), "" if len(rw) == 1 else "s", "\n".join(rw) + ) + ) + + +@contextlib.contextmanager +def _passthrough_loop_context(loop, fast=False): # type: ignore[no-untyped-def] + """Passthrough loop context. + + Sets up and tears down a loop unless one is passed in via the loop + argument when it's passed straight through. + """ + if loop: + # loop already exists, pass it straight through + yield loop + else: + # this shadows loop_context's standard behavior + loop = setup_test_loop() + yield loop + teardown_test_loop(loop, fast=fast) + + +def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def] + """Fix pytest collecting for coroutines.""" + if collector.funcnamefilter(name) and asyncio.iscoroutinefunction(obj): + return list(collector._genfunctions(name, obj)) + + +def pytest_pyfunc_call(pyfuncitem): # type: ignore[no-untyped-def] + """Run coroutines in an event loop instead of a normal function call.""" + fast = pyfuncitem.config.getoption("--aiohttp-fast") + if asyncio.iscoroutinefunction(pyfuncitem.function): + existing_loop = pyfuncitem.funcargs.get( + "proactor_loop" + ) or pyfuncitem.funcargs.get("loop", None) + with _runtime_warning_context(): + with _passthrough_loop_context(existing_loop, fast=fast) as _loop: + testargs = { + arg: pyfuncitem.funcargs[arg] + for arg in pyfuncitem._fixtureinfo.argnames + } + _loop.run_until_complete(pyfuncitem.obj(**testargs)) + + return True + + +def pytest_generate_tests(metafunc): # type: ignore[no-untyped-def] + if "loop_factory" not in metafunc.fixturenames: + return + + loops = metafunc.config.option.aiohttp_loop + avail_factories: Dict[str, Type[asyncio.AbstractEventLoopPolicy]] + avail_factories = {"pyloop": asyncio.DefaultEventLoopPolicy} + + if uvloop is not None: # pragma: no cover + avail_factories["uvloop"] = uvloop.EventLoopPolicy + + if loops == "all": + loops = "pyloop,uvloop?" + + factories = {} # type: ignore[var-annotated] + for name in loops.split(","): + required = not name.endswith("?") + name = name.strip(" ?") + if name not in avail_factories: # pragma: no cover + if required: + raise ValueError( + "Unknown loop '%s', available loops: %s" + % (name, list(factories.keys())) + ) + else: + continue + factories[name] = avail_factories[name] + metafunc.parametrize( + "loop_factory", list(factories.values()), ids=list(factories.keys()) + ) + + +@pytest.fixture +def loop(loop_factory, fast, loop_debug): # type: ignore[no-untyped-def] + """Return an instance of the event loop.""" + policy = loop_factory() + asyncio.set_event_loop_policy(policy) + with loop_context(fast=fast) as _loop: + if loop_debug: + _loop.set_debug(True) # pragma: no cover + asyncio.set_event_loop(_loop) + yield _loop + + +@pytest.fixture +def proactor_loop(): # type: ignore[no-untyped-def] + policy = asyncio.WindowsProactorEventLoopPolicy() # type: ignore[attr-defined] + asyncio.set_event_loop_policy(policy) + + with loop_context(policy.new_event_loop) as _loop: + asyncio.set_event_loop(_loop) + yield _loop + + +@pytest.fixture +def unused_port(aiohttp_unused_port: Callable[[], int]) -> Callable[[], int]: + warnings.warn( + "Deprecated, use aiohttp_unused_port fixture instead", + DeprecationWarning, + stacklevel=2, + ) + return aiohttp_unused_port + + +@pytest.fixture +def aiohttp_unused_port() -> Callable[[], int]: + """Return a port that is unused on the current host.""" + return _unused_port + + +@pytest.fixture +def aiohttp_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpServer]: + """Factory to create a TestServer instance, given an app. + + aiohttp_server(app, **kwargs) + """ + servers = [] + + async def go( + app: Application, *, port: Optional[int] = None, **kwargs: Any + ) -> TestServer: + server = TestServer(app, port=port) + await server.start_server(loop=loop, **kwargs) + servers.append(server) + return server + + yield go + + async def finalize() -> None: + while servers: + await servers.pop().close() + + loop.run_until_complete(finalize()) + + +@pytest.fixture +def test_server(aiohttp_server): # type: ignore[no-untyped-def] # pragma: no cover + warnings.warn( + "Deprecated, use aiohttp_server fixture instead", + DeprecationWarning, + stacklevel=2, + ) + return aiohttp_server + + +@pytest.fixture +def aiohttp_raw_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpRawServer]: + """Factory to create a RawTestServer instance, given a web handler. + + aiohttp_raw_server(handler, **kwargs) + """ + servers = [] + + async def go(handler, *, port=None, **kwargs): # type: ignore[no-untyped-def] + server = RawTestServer(handler, port=port) + await server.start_server(loop=loop, **kwargs) + servers.append(server) + return server + + yield go + + async def finalize() -> None: + while servers: + await servers.pop().close() + + loop.run_until_complete(finalize()) + + +@pytest.fixture +def raw_test_server( # type: ignore[no-untyped-def] # pragma: no cover + aiohttp_raw_server, +): + warnings.warn( + "Deprecated, use aiohttp_raw_server fixture instead", + DeprecationWarning, + stacklevel=2, + ) + return aiohttp_raw_server + + +@pytest.fixture +def aiohttp_client( + loop: asyncio.AbstractEventLoop, +) -> Iterator[AiohttpClient]: + """Factory to create a TestClient instance. + + aiohttp_client(app, **kwargs) + aiohttp_client(server, **kwargs) + aiohttp_client(raw_server, **kwargs) + """ + clients = [] + + async def go( + __param: Union[Application, BaseTestServer], + *args: Any, + server_kwargs: Optional[Dict[str, Any]] = None, + **kwargs: Any + ) -> TestClient: + + if isinstance(__param, Callable) and not isinstance( # type: ignore[arg-type] + __param, (Application, BaseTestServer) + ): + __param = __param(loop, *args, **kwargs) + kwargs = {} + else: + assert not args, "args should be empty" + + if isinstance(__param, Application): + server_kwargs = server_kwargs or {} + server = TestServer(__param, loop=loop, **server_kwargs) + client = TestClient(server, loop=loop, **kwargs) + elif isinstance(__param, BaseTestServer): + client = TestClient(__param, loop=loop, **kwargs) + else: + raise ValueError("Unknown argument type: %r" % type(__param)) + + await client.start_server() + clients.append(client) + return client + + yield go + + async def finalize() -> None: + while clients: + await clients.pop().close() + + loop.run_until_complete(finalize()) + + +@pytest.fixture +def test_client(aiohttp_client): # type: ignore[no-untyped-def] # pragma: no cover + warnings.warn( + "Deprecated, use aiohttp_client fixture instead", + DeprecationWarning, + stacklevel=2, + ) + return aiohttp_client diff --git a/env/Lib/site-packages/aiohttp/resolver.py b/env/Lib/site-packages/aiohttp/resolver.py new file mode 100644 index 0000000..10e3626 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/resolver.py @@ -0,0 +1,188 @@ +import asyncio +import socket +import sys +from typing import Any, Dict, List, Optional, Tuple, Type, Union + +from .abc import AbstractResolver, ResolveResult + +__all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver") + + +try: + import aiodns + + aiodns_default = hasattr(aiodns.DNSResolver, "getaddrinfo") +except ImportError: # pragma: no cover + aiodns = None # type: ignore[assignment] + aiodns_default = False + + +_NUMERIC_SOCKET_FLAGS = socket.AI_NUMERICHOST | socket.AI_NUMERICSERV +_SUPPORTS_SCOPE_ID = sys.version_info >= (3, 9, 0) + + +class ThreadedResolver(AbstractResolver): + """Threaded resolver. + + Uses an Executor for synchronous getaddrinfo() calls. + concurrent.futures.ThreadPoolExecutor is used by default. + """ + + def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: + self._loop = loop or asyncio.get_running_loop() + + async def resolve( + self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET + ) -> List[ResolveResult]: + infos = await self._loop.getaddrinfo( + host, + port, + type=socket.SOCK_STREAM, + family=family, + flags=socket.AI_ADDRCONFIG, + ) + + hosts: List[ResolveResult] = [] + for family, _, proto, _, address in infos: + if family == socket.AF_INET6: + if len(address) < 3: + # IPv6 is not supported by Python build, + # or IPv6 is not enabled in the host + continue + if address[3] and _SUPPORTS_SCOPE_ID: + # This is essential for link-local IPv6 addresses. + # LL IPv6 is a VERY rare case. Strictly speaking, we should use + # getnameinfo() unconditionally, but performance makes sense. + resolved_host, _port = await self._loop.getnameinfo( + address, _NUMERIC_SOCKET_FLAGS + ) + port = int(_port) + else: + resolved_host, port = address[:2] + else: # IPv4 + assert family == socket.AF_INET + resolved_host, port = address # type: ignore[misc] + hosts.append( + ResolveResult( + hostname=host, + host=resolved_host, + port=port, + family=family, + proto=proto, + flags=_NUMERIC_SOCKET_FLAGS, + ) + ) + + return hosts + + async def close(self) -> None: + pass + + +class AsyncResolver(AbstractResolver): + """Use the `aiodns` package to make asynchronous DNS lookups""" + + def __init__( + self, + loop: Optional[asyncio.AbstractEventLoop] = None, + *args: Any, + **kwargs: Any + ) -> None: + if aiodns is None: + raise RuntimeError("Resolver requires aiodns library") + + self._resolver = aiodns.DNSResolver(*args, **kwargs) + + if not hasattr(self._resolver, "gethostbyname"): + # aiodns 1.1 is not available, fallback to DNSResolver.query + self.resolve = self._resolve_with_query # type: ignore + + async def resolve( + self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET + ) -> List[ResolveResult]: + try: + resp = await self._resolver.getaddrinfo( + host, + port=port, + type=socket.SOCK_STREAM, + family=family, + flags=socket.AI_ADDRCONFIG, + ) + except aiodns.error.DNSError as exc: + msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed" + raise OSError(msg) from exc + hosts: List[ResolveResult] = [] + for node in resp.nodes: + address: Union[Tuple[bytes, int], Tuple[bytes, int, int, int]] = node.addr + family = node.family + if family == socket.AF_INET6: + if len(address) > 3 and address[3] and _SUPPORTS_SCOPE_ID: + # This is essential for link-local IPv6 addresses. + # LL IPv6 is a VERY rare case. Strictly speaking, we should use + # getnameinfo() unconditionally, but performance makes sense. + result = await self._resolver.getnameinfo( + (address[0].decode("ascii"), *address[1:]), + _NUMERIC_SOCKET_FLAGS, + ) + resolved_host = result.node + else: + resolved_host = address[0].decode("ascii") + port = address[1] + else: # IPv4 + assert family == socket.AF_INET + resolved_host = address[0].decode("ascii") + port = address[1] + hosts.append( + ResolveResult( + hostname=host, + host=resolved_host, + port=port, + family=family, + proto=0, + flags=_NUMERIC_SOCKET_FLAGS, + ) + ) + + if not hosts: + raise OSError("DNS lookup failed") + + return hosts + + async def _resolve_with_query( + self, host: str, port: int = 0, family: int = socket.AF_INET + ) -> List[Dict[str, Any]]: + if family == socket.AF_INET6: + qtype = "AAAA" + else: + qtype = "A" + + try: + resp = await self._resolver.query(host, qtype) + except aiodns.error.DNSError as exc: + msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed" + raise OSError(msg) from exc + + hosts = [] + for rr in resp: + hosts.append( + { + "hostname": host, + "host": rr.host, + "port": port, + "family": family, + "proto": 0, + "flags": socket.AI_NUMERICHOST, + } + ) + + if not hosts: + raise OSError("DNS lookup failed") + + return hosts + + async def close(self) -> None: + self._resolver.cancel() + + +_DefaultType = Type[Union[AsyncResolver, ThreadedResolver]] +DefaultResolver: _DefaultType = AsyncResolver if aiodns_default else ThreadedResolver diff --git a/env/Lib/site-packages/aiohttp/streams.py b/env/Lib/site-packages/aiohttp/streams.py new file mode 100644 index 0000000..b9b9c3f --- /dev/null +++ b/env/Lib/site-packages/aiohttp/streams.py @@ -0,0 +1,684 @@ +import asyncio +import collections +import warnings +from typing import ( + Awaitable, + Callable, + Deque, + Final, + Generic, + List, + Optional, + Tuple, + TypeVar, +) + +from .base_protocol import BaseProtocol +from .helpers import ( + _EXC_SENTINEL, + BaseTimerContext, + TimerNoop, + set_exception, + set_result, +) +from .log import internal_logger + +__all__ = ( + "EMPTY_PAYLOAD", + "EofStream", + "StreamReader", + "DataQueue", + "FlowControlDataQueue", +) + +_T = TypeVar("_T") + + +class EofStream(Exception): + """eof stream indication.""" + + +class AsyncStreamIterator(Generic[_T]): + def __init__(self, read_func: Callable[[], Awaitable[_T]]) -> None: + self.read_func = read_func + + def __aiter__(self) -> "AsyncStreamIterator[_T]": + return self + + async def __anext__(self) -> _T: + try: + rv = await self.read_func() + except EofStream: + raise StopAsyncIteration + if rv == b"": + raise StopAsyncIteration + return rv + + +class ChunkTupleAsyncStreamIterator: + def __init__(self, stream: "StreamReader") -> None: + self._stream = stream + + def __aiter__(self) -> "ChunkTupleAsyncStreamIterator": + return self + + async def __anext__(self) -> Tuple[bytes, bool]: + rv = await self._stream.readchunk() + if rv == (b"", False): + raise StopAsyncIteration + return rv + + +class AsyncStreamReaderMixin: + def __aiter__(self) -> AsyncStreamIterator[bytes]: + return AsyncStreamIterator(self.readline) # type: ignore[attr-defined] + + def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]: + """Returns an asynchronous iterator that yields chunks of size n.""" + return AsyncStreamIterator(lambda: self.read(n)) # type: ignore[attr-defined] + + def iter_any(self) -> AsyncStreamIterator[bytes]: + """Yield all available data as soon as it is received.""" + return AsyncStreamIterator(self.readany) # type: ignore[attr-defined] + + def iter_chunks(self) -> ChunkTupleAsyncStreamIterator: + """Yield chunks of data as they are received by the server. + + The yielded objects are tuples + of (bytes, bool) as returned by the StreamReader.readchunk method. + """ + return ChunkTupleAsyncStreamIterator(self) # type: ignore[arg-type] + + +class StreamReader(AsyncStreamReaderMixin): + """An enhancement of asyncio.StreamReader. + + Supports asynchronous iteration by line, chunk or as available:: + + async for line in reader: + ... + async for chunk in reader.iter_chunked(1024): + ... + async for slice in reader.iter_any(): + ... + + """ + + total_bytes = 0 + + def __init__( + self, + protocol: BaseProtocol, + limit: int, + *, + timer: Optional[BaseTimerContext] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + ) -> None: + self._protocol = protocol + self._low_water = limit + self._high_water = limit * 2 + if loop is None: + loop = asyncio.get_event_loop() + self._loop = loop + self._size = 0 + self._cursor = 0 + self._http_chunk_splits: Optional[List[int]] = None + self._buffer: Deque[bytes] = collections.deque() + self._buffer_offset = 0 + self._eof = False + self._waiter: Optional[asyncio.Future[None]] = None + self._eof_waiter: Optional[asyncio.Future[None]] = None + self._exception: Optional[BaseException] = None + self._timer = TimerNoop() if timer is None else timer + self._eof_callbacks: List[Callable[[], None]] = [] + + def __repr__(self) -> str: + info = [self.__class__.__name__] + if self._size: + info.append("%d bytes" % self._size) + if self._eof: + info.append("eof") + if self._low_water != 2**16: # default limit + info.append("low=%d high=%d" % (self._low_water, self._high_water)) + if self._waiter: + info.append("w=%r" % self._waiter) + if self._exception: + info.append("e=%r" % self._exception) + return "<%s>" % " ".join(info) + + def get_read_buffer_limits(self) -> Tuple[int, int]: + return (self._low_water, self._high_water) + + def exception(self) -> Optional[BaseException]: + return self._exception + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + self._exception = exc + self._eof_callbacks.clear() + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_exception(waiter, exc, exc_cause) + + waiter = self._eof_waiter + if waiter is not None: + self._eof_waiter = None + set_exception(waiter, exc, exc_cause) + + def on_eof(self, callback: Callable[[], None]) -> None: + if self._eof: + try: + callback() + except Exception: + internal_logger.exception("Exception in eof callback") + else: + self._eof_callbacks.append(callback) + + def feed_eof(self) -> None: + self._eof = True + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, None) + + waiter = self._eof_waiter + if waiter is not None: + self._eof_waiter = None + set_result(waiter, None) + + for cb in self._eof_callbacks: + try: + cb() + except Exception: + internal_logger.exception("Exception in eof callback") + + self._eof_callbacks.clear() + + def is_eof(self) -> bool: + """Return True if 'feed_eof' was called.""" + return self._eof + + def at_eof(self) -> bool: + """Return True if the buffer is empty and 'feed_eof' was called.""" + return self._eof and not self._buffer + + async def wait_eof(self) -> None: + if self._eof: + return + + assert self._eof_waiter is None + self._eof_waiter = self._loop.create_future() + try: + await self._eof_waiter + finally: + self._eof_waiter = None + + def unread_data(self, data: bytes) -> None: + """rollback reading some data from stream, inserting it to buffer head.""" + warnings.warn( + "unread_data() is deprecated " + "and will be removed in future releases (#3260)", + DeprecationWarning, + stacklevel=2, + ) + if not data: + return + + if self._buffer_offset: + self._buffer[0] = self._buffer[0][self._buffer_offset :] + self._buffer_offset = 0 + self._size += len(data) + self._cursor -= len(data) + self._buffer.appendleft(data) + self._eof_counter = 0 + + # TODO: size is ignored, remove the param later + def feed_data(self, data: bytes, size: int = 0) -> None: + assert not self._eof, "feed_data after feed_eof" + + if not data: + return + + self._size += len(data) + self._buffer.append(data) + self.total_bytes += len(data) + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, None) + + if self._size > self._high_water and not self._protocol._reading_paused: + self._protocol.pause_reading() + + def begin_http_chunk_receiving(self) -> None: + if self._http_chunk_splits is None: + if self.total_bytes: + raise RuntimeError( + "Called begin_http_chunk_receiving when" "some data was already fed" + ) + self._http_chunk_splits = [] + + def end_http_chunk_receiving(self) -> None: + if self._http_chunk_splits is None: + raise RuntimeError( + "Called end_chunk_receiving without calling " + "begin_chunk_receiving first" + ) + + # self._http_chunk_splits contains logical byte offsets from start of + # the body transfer. Each offset is the offset of the end of a chunk. + # "Logical" means bytes, accessible for a user. + # If no chunks containing logical data were received, current position + # is difinitely zero. + pos = self._http_chunk_splits[-1] if self._http_chunk_splits else 0 + + if self.total_bytes == pos: + # We should not add empty chunks here. So we check for that. + # Note, when chunked + gzip is used, we can receive a chunk + # of compressed data, but that data may not be enough for gzip FSM + # to yield any uncompressed data. That's why current position may + # not change after receiving a chunk. + return + + self._http_chunk_splits.append(self.total_bytes) + + # wake up readchunk when end of http chunk received + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, None) + + async def _wait(self, func_name: str) -> None: + # StreamReader uses a future to link the protocol feed_data() method + # to a read coroutine. Running two read coroutines at the same time + # would have an unexpected behaviour. It would not possible to know + # which coroutine would get the next data. + if self._waiter is not None: + raise RuntimeError( + "%s() called while another coroutine is " + "already waiting for incoming data" % func_name + ) + + waiter = self._waiter = self._loop.create_future() + try: + with self._timer: + await waiter + finally: + self._waiter = None + + async def readline(self) -> bytes: + return await self.readuntil() + + async def readuntil(self, separator: bytes = b"\n") -> bytes: + seplen = len(separator) + if seplen == 0: + raise ValueError("Separator should be at least one-byte string") + + if self._exception is not None: + raise self._exception + + chunk = b"" + chunk_size = 0 + not_enough = True + + while not_enough: + while self._buffer and not_enough: + offset = self._buffer_offset + ichar = self._buffer[0].find(separator, offset) + 1 + # Read from current offset to found separator or to the end. + data = self._read_nowait_chunk( + ichar - offset + seplen - 1 if ichar else -1 + ) + chunk += data + chunk_size += len(data) + if ichar: + not_enough = False + + if chunk_size > self._high_water: + raise ValueError("Chunk too big") + + if self._eof: + break + + if not_enough: + await self._wait("readuntil") + + return chunk + + async def read(self, n: int = -1) -> bytes: + if self._exception is not None: + raise self._exception + + # migration problem; with DataQueue you have to catch + # EofStream exception, so common way is to run payload.read() inside + # infinite loop. what can cause real infinite loop with StreamReader + # lets keep this code one major release. + if __debug__: + if self._eof and not self._buffer: + self._eof_counter = getattr(self, "_eof_counter", 0) + 1 + if self._eof_counter > 5: + internal_logger.warning( + "Multiple access to StreamReader in eof state, " + "might be infinite loop.", + stack_info=True, + ) + + if not n: + return b"" + + if n < 0: + # This used to just loop creating a new waiter hoping to + # collect everything in self._buffer, but that would + # deadlock if the subprocess sends more than self.limit + # bytes. So just call self.readany() until EOF. + blocks = [] + while True: + block = await self.readany() + if not block: + break + blocks.append(block) + return b"".join(blocks) + + # TODO: should be `if` instead of `while` + # because waiter maybe triggered on chunk end, + # without feeding any data + while not self._buffer and not self._eof: + await self._wait("read") + + return self._read_nowait(n) + + async def readany(self) -> bytes: + if self._exception is not None: + raise self._exception + + # TODO: should be `if` instead of `while` + # because waiter maybe triggered on chunk end, + # without feeding any data + while not self._buffer and not self._eof: + await self._wait("readany") + + return self._read_nowait(-1) + + async def readchunk(self) -> Tuple[bytes, bool]: + """Returns a tuple of (data, end_of_http_chunk). + + When chunked transfer + encoding is used, end_of_http_chunk is a boolean indicating if the end + of the data corresponds to the end of a HTTP chunk , otherwise it is + always False. + """ + while True: + if self._exception is not None: + raise self._exception + + while self._http_chunk_splits: + pos = self._http_chunk_splits.pop(0) + if pos == self._cursor: + return (b"", True) + if pos > self._cursor: + return (self._read_nowait(pos - self._cursor), True) + internal_logger.warning( + "Skipping HTTP chunk end due to data " + "consumption beyond chunk boundary" + ) + + if self._buffer: + return (self._read_nowait_chunk(-1), False) + # return (self._read_nowait(-1), False) + + if self._eof: + # Special case for signifying EOF. + # (b'', True) is not a final return value actually. + return (b"", False) + + await self._wait("readchunk") + + async def readexactly(self, n: int) -> bytes: + if self._exception is not None: + raise self._exception + + blocks: List[bytes] = [] + while n > 0: + block = await self.read(n) + if not block: + partial = b"".join(blocks) + raise asyncio.IncompleteReadError(partial, len(partial) + n) + blocks.append(block) + n -= len(block) + + return b"".join(blocks) + + def read_nowait(self, n: int = -1) -> bytes: + # default was changed to be consistent with .read(-1) + # + # I believe the most users don't know about the method and + # they are not affected. + if self._exception is not None: + raise self._exception + + if self._waiter and not self._waiter.done(): + raise RuntimeError( + "Called while some coroutine is waiting for incoming data." + ) + + return self._read_nowait(n) + + def _read_nowait_chunk(self, n: int) -> bytes: + first_buffer = self._buffer[0] + offset = self._buffer_offset + if n != -1 and len(first_buffer) - offset > n: + data = first_buffer[offset : offset + n] + self._buffer_offset += n + + elif offset: + self._buffer.popleft() + data = first_buffer[offset:] + self._buffer_offset = 0 + + else: + data = self._buffer.popleft() + + self._size -= len(data) + self._cursor += len(data) + + chunk_splits = self._http_chunk_splits + # Prevent memory leak: drop useless chunk splits + while chunk_splits and chunk_splits[0] < self._cursor: + chunk_splits.pop(0) + + if self._size < self._low_water and self._protocol._reading_paused: + self._protocol.resume_reading() + return data + + def _read_nowait(self, n: int) -> bytes: + """Read not more than n bytes, or whole buffer if n == -1""" + self._timer.assert_timeout() + + chunks = [] + while self._buffer: + chunk = self._read_nowait_chunk(n) + chunks.append(chunk) + if n != -1: + n -= len(chunk) + if n == 0: + break + + return b"".join(chunks) if chunks else b"" + + +class EmptyStreamReader(StreamReader): # lgtm [py/missing-call-to-init] + def __init__(self) -> None: + self._read_eof_chunk = False + + def __repr__(self) -> str: + return "<%s>" % self.__class__.__name__ + + def exception(self) -> Optional[BaseException]: + return None + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + pass + + def on_eof(self, callback: Callable[[], None]) -> None: + try: + callback() + except Exception: + internal_logger.exception("Exception in eof callback") + + def feed_eof(self) -> None: + pass + + def is_eof(self) -> bool: + return True + + def at_eof(self) -> bool: + return True + + async def wait_eof(self) -> None: + return + + def feed_data(self, data: bytes, n: int = 0) -> None: + pass + + async def readline(self) -> bytes: + return b"" + + async def read(self, n: int = -1) -> bytes: + return b"" + + # TODO add async def readuntil + + async def readany(self) -> bytes: + return b"" + + async def readchunk(self) -> Tuple[bytes, bool]: + if not self._read_eof_chunk: + self._read_eof_chunk = True + return (b"", False) + + return (b"", True) + + async def readexactly(self, n: int) -> bytes: + raise asyncio.IncompleteReadError(b"", n) + + def read_nowait(self, n: int = -1) -> bytes: + return b"" + + +EMPTY_PAYLOAD: Final[StreamReader] = EmptyStreamReader() + + +class DataQueue(Generic[_T]): + """DataQueue is a general-purpose blocking queue with one reader.""" + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop = loop + self._eof = False + self._waiter: Optional[asyncio.Future[None]] = None + self._exception: Optional[BaseException] = None + self._size = 0 + self._buffer: Deque[Tuple[_T, int]] = collections.deque() + + def __len__(self) -> int: + return len(self._buffer) + + def is_eof(self) -> bool: + return self._eof + + def at_eof(self) -> bool: + return self._eof and not self._buffer + + def exception(self) -> Optional[BaseException]: + return self._exception + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + self._eof = True + self._exception = exc + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_exception(waiter, exc, exc_cause) + + def feed_data(self, data: _T, size: int = 0) -> None: + self._size += size + self._buffer.append((data, size)) + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, None) + + def feed_eof(self) -> None: + self._eof = True + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, None) + + async def read(self) -> _T: + if not self._buffer and not self._eof: + assert not self._waiter + self._waiter = self._loop.create_future() + try: + await self._waiter + except (asyncio.CancelledError, asyncio.TimeoutError): + self._waiter = None + raise + + if self._buffer: + data, size = self._buffer.popleft() + self._size -= size + return data + else: + if self._exception is not None: + raise self._exception + else: + raise EofStream + + def __aiter__(self) -> AsyncStreamIterator[_T]: + return AsyncStreamIterator(self.read) + + +class FlowControlDataQueue(DataQueue[_T]): + """FlowControlDataQueue resumes and pauses an underlying stream. + + It is a destination for parsed data. + """ + + def __init__( + self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop + ) -> None: + super().__init__(loop=loop) + + self._protocol = protocol + self._limit = limit * 2 + + def feed_data(self, data: _T, size: int = 0) -> None: + super().feed_data(data, size) + + if self._size > self._limit and not self._protocol._reading_paused: + self._protocol.pause_reading() + + async def read(self) -> _T: + try: + return await super().read() + finally: + if self._size < self._limit and self._protocol._reading_paused: + self._protocol.resume_reading() diff --git a/env/Lib/site-packages/aiohttp/tcp_helpers.py b/env/Lib/site-packages/aiohttp/tcp_helpers.py new file mode 100644 index 0000000..88b2442 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/tcp_helpers.py @@ -0,0 +1,37 @@ +"""Helper methods to tune a TCP connection""" + +import asyncio +import socket +from contextlib import suppress +from typing import Optional # noqa + +__all__ = ("tcp_keepalive", "tcp_nodelay") + + +if hasattr(socket, "SO_KEEPALIVE"): + + def tcp_keepalive(transport: asyncio.Transport) -> None: + sock = transport.get_extra_info("socket") + if sock is not None: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + +else: + + def tcp_keepalive(transport: asyncio.Transport) -> None: # pragma: no cover + pass + + +def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None: + sock = transport.get_extra_info("socket") + + if sock is None: + return + + if sock.family not in (socket.AF_INET, socket.AF_INET6): + return + + value = bool(value) + + # socket may be closed already, on windows OSError get raised + with suppress(OSError): + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, value) diff --git a/env/Lib/site-packages/aiohttp/test_utils.py b/env/Lib/site-packages/aiohttp/test_utils.py new file mode 100644 index 0000000..97c1469 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/test_utils.py @@ -0,0 +1,731 @@ +"""Utilities shared by tests.""" + +import asyncio +import contextlib +import gc +import inspect +import ipaddress +import os +import socket +import sys +import warnings +from abc import ABC, abstractmethod +from types import TracebackType +from typing import TYPE_CHECKING, Any, Callable, Iterator, List, Optional, Type, cast +from unittest import IsolatedAsyncioTestCase, mock + +from aiosignal import Signal +from multidict import CIMultiDict, CIMultiDictProxy +from yarl import URL + +import aiohttp +from aiohttp.client import ( + _RequestContextManager, + _RequestOptions, + _WSRequestContextManager, +) + +from . import ClientSession, hdrs +from .abc import AbstractCookieJar +from .client_reqrep import ClientResponse +from .client_ws import ClientWebSocketResponse +from .helpers import sentinel +from .http import HttpVersion, RawRequestMessage +from .typedefs import StrOrURL +from .web import ( + Application, + AppRunner, + BaseRunner, + Request, + Server, + ServerRunner, + SockSite, + UrlMappingMatchInfo, +) +from .web_protocol import _RequestHandler + +if TYPE_CHECKING: + from ssl import SSLContext +else: + SSLContext = None + +if sys.version_info >= (3, 11) and TYPE_CHECKING: + from typing import Unpack + +REUSE_ADDRESS = os.name == "posix" and sys.platform != "cygwin" + + +def get_unused_port_socket( + host: str, family: socket.AddressFamily = socket.AF_INET +) -> socket.socket: + return get_port_socket(host, 0, family) + + +def get_port_socket( + host: str, port: int, family: socket.AddressFamily +) -> socket.socket: + s = socket.socket(family, socket.SOCK_STREAM) + if REUSE_ADDRESS: + # Windows has different semantics for SO_REUSEADDR, + # so don't set it. Ref: + # https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind((host, port)) + return s + + +def unused_port() -> int: + """Return a port that is unused on the current host.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return cast(int, s.getsockname()[1]) + + +class BaseTestServer(ABC): + __test__ = False + + def __init__( + self, + *, + scheme: str = "", + loop: Optional[asyncio.AbstractEventLoop] = None, + host: str = "127.0.0.1", + port: Optional[int] = None, + skip_url_asserts: bool = False, + socket_factory: Callable[ + [str, int, socket.AddressFamily], socket.socket + ] = get_port_socket, + **kwargs: Any, + ) -> None: + self._loop = loop + self.runner: Optional[BaseRunner] = None + self._root: Optional[URL] = None + self.host = host + self.port = port + self._closed = False + self.scheme = scheme + self.skip_url_asserts = skip_url_asserts + self.socket_factory = socket_factory + + async def start_server( + self, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any + ) -> None: + if self.runner: + return + self._loop = loop + self._ssl = kwargs.pop("ssl", None) + self.runner = await self._make_runner(handler_cancellation=True, **kwargs) + await self.runner.setup() + if not self.port: + self.port = 0 + try: + version = ipaddress.ip_address(self.host).version + except ValueError: + version = 4 + family = socket.AF_INET6 if version == 6 else socket.AF_INET + _sock = self.socket_factory(self.host, self.port, family) + self.host, self.port = _sock.getsockname()[:2] + site = SockSite(self.runner, sock=_sock, ssl_context=self._ssl) + await site.start() + server = site._server + assert server is not None + sockets = server.sockets # type: ignore[attr-defined] + assert sockets is not None + self.port = sockets[0].getsockname()[1] + if not self.scheme: + self.scheme = "https" if self._ssl else "http" + self._root = URL(f"{self.scheme}://{self.host}:{self.port}") + + @abstractmethod # pragma: no cover + async def _make_runner(self, **kwargs: Any) -> BaseRunner: + pass + + def make_url(self, path: StrOrURL) -> URL: + assert self._root is not None + url = URL(path) + if not self.skip_url_asserts: + assert not url.is_absolute() + return self._root.join(url) + else: + return URL(str(self._root) + str(path)) + + @property + def started(self) -> bool: + return self.runner is not None + + @property + def closed(self) -> bool: + return self._closed + + @property + def handler(self) -> Server: + # for backward compatibility + # web.Server instance + runner = self.runner + assert runner is not None + assert runner.server is not None + return runner.server + + async def close(self) -> None: + """Close all fixtures created by the test client. + + After that point, the TestClient is no longer usable. + + This is an idempotent function: running close multiple times + will not have any additional effects. + + close is also run when the object is garbage collected, and on + exit when used as a context manager. + + """ + if self.started and not self.closed: + assert self.runner is not None + await self.runner.cleanup() + self._root = None + self.port = None + self._closed = True + + def __enter__(self) -> None: + raise TypeError("Use async with instead") + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + # __exit__ should exist in pair with __enter__ but never executed + pass # pragma: no cover + + async def __aenter__(self) -> "BaseTestServer": + await self.start_server(loop=self._loop) + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + await self.close() + + +class TestServer(BaseTestServer): + def __init__( + self, + app: Application, + *, + scheme: str = "", + host: str = "127.0.0.1", + port: Optional[int] = None, + **kwargs: Any, + ): + self.app = app + super().__init__(scheme=scheme, host=host, port=port, **kwargs) + + async def _make_runner(self, **kwargs: Any) -> BaseRunner: + return AppRunner(self.app, **kwargs) + + +class RawTestServer(BaseTestServer): + def __init__( + self, + handler: _RequestHandler, + *, + scheme: str = "", + host: str = "127.0.0.1", + port: Optional[int] = None, + **kwargs: Any, + ) -> None: + self._handler = handler + super().__init__(scheme=scheme, host=host, port=port, **kwargs) + + async def _make_runner(self, debug: bool = True, **kwargs: Any) -> ServerRunner: + srv = Server(self._handler, loop=self._loop, debug=debug, **kwargs) + return ServerRunner(srv, debug=debug, **kwargs) + + +class TestClient: + """ + A test client implementation. + + To write functional tests for aiohttp based servers. + + """ + + __test__ = False + + def __init__( + self, + server: BaseTestServer, + *, + cookie_jar: Optional[AbstractCookieJar] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + **kwargs: Any, + ) -> None: + if not isinstance(server, BaseTestServer): + raise TypeError( + "server must be TestServer " "instance, found type: %r" % type(server) + ) + self._server = server + self._loop = loop + if cookie_jar is None: + cookie_jar = aiohttp.CookieJar(unsafe=True, loop=loop) + self._session = ClientSession(loop=loop, cookie_jar=cookie_jar, **kwargs) + self._closed = False + self._responses: List[ClientResponse] = [] + self._websockets: List[ClientWebSocketResponse] = [] + + async def start_server(self) -> None: + await self._server.start_server(loop=self._loop) + + @property + def host(self) -> str: + return self._server.host + + @property + def port(self) -> Optional[int]: + return self._server.port + + @property + def server(self) -> BaseTestServer: + return self._server + + @property + def app(self) -> Optional[Application]: + return cast(Optional[Application], getattr(self._server, "app", None)) + + @property + def session(self) -> ClientSession: + """An internal aiohttp.ClientSession. + + Unlike the methods on the TestClient, client session requests + do not automatically include the host in the url queried, and + will require an absolute path to the resource. + + """ + return self._session + + def make_url(self, path: StrOrURL) -> URL: + return self._server.make_url(path) + + async def _request( + self, method: str, path: StrOrURL, **kwargs: Any + ) -> ClientResponse: + resp = await self._session.request(method, self.make_url(path), **kwargs) + # save it to close later + self._responses.append(resp) + return resp + + if sys.version_info >= (3, 11) and TYPE_CHECKING: + + def request( + self, method: str, path: StrOrURL, **kwargs: Unpack[_RequestOptions] + ) -> _RequestContextManager: ... + + def get( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def options( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def head( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def post( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def put( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def patch( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def delete( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + else: + + def request( + self, method: str, path: StrOrURL, **kwargs: Any + ) -> _RequestContextManager: + """Routes a request to tested http server. + + The interface is identical to aiohttp.ClientSession.request, + except the loop kwarg is overridden by the instance used by the + test server. + + """ + return _RequestContextManager(self._request(method, path, **kwargs)) + + def get(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP GET request.""" + return _RequestContextManager(self._request(hdrs.METH_GET, path, **kwargs)) + + def post(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP POST request.""" + return _RequestContextManager(self._request(hdrs.METH_POST, path, **kwargs)) + + def options(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP OPTIONS request.""" + return _RequestContextManager( + self._request(hdrs.METH_OPTIONS, path, **kwargs) + ) + + def head(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP HEAD request.""" + return _RequestContextManager(self._request(hdrs.METH_HEAD, path, **kwargs)) + + def put(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP PUT request.""" + return _RequestContextManager(self._request(hdrs.METH_PUT, path, **kwargs)) + + def patch(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP PATCH request.""" + return _RequestContextManager( + self._request(hdrs.METH_PATCH, path, **kwargs) + ) + + def delete(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP PATCH request.""" + return _RequestContextManager( + self._request(hdrs.METH_DELETE, path, **kwargs) + ) + + def ws_connect(self, path: StrOrURL, **kwargs: Any) -> _WSRequestContextManager: + """Initiate websocket connection. + + The api corresponds to aiohttp.ClientSession.ws_connect. + + """ + return _WSRequestContextManager(self._ws_connect(path, **kwargs)) + + async def _ws_connect( + self, path: StrOrURL, **kwargs: Any + ) -> ClientWebSocketResponse: + ws = await self._session.ws_connect(self.make_url(path), **kwargs) + self._websockets.append(ws) + return ws + + async def close(self) -> None: + """Close all fixtures created by the test client. + + After that point, the TestClient is no longer usable. + + This is an idempotent function: running close multiple times + will not have any additional effects. + + close is also run on exit when used as a(n) (asynchronous) + context manager. + + """ + if not self._closed: + for resp in self._responses: + resp.close() + for ws in self._websockets: + await ws.close() + await self._session.close() + await self._server.close() + self._closed = True + + def __enter__(self) -> None: + raise TypeError("Use async with instead") + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + # __exit__ should exist in pair with __enter__ but never executed + pass # pragma: no cover + + async def __aenter__(self) -> "TestClient": + await self.start_server() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + await self.close() + + +class AioHTTPTestCase(IsolatedAsyncioTestCase): + """A base class to allow for unittest web applications using aiohttp. + + Provides the following: + + * self.client (aiohttp.test_utils.TestClient): an aiohttp test client. + * self.loop (asyncio.BaseEventLoop): the event loop in which the + application and server are running. + * self.app (aiohttp.web.Application): the application returned by + self.get_application() + + Note that the TestClient's methods are asynchronous: you have to + execute function on the test client using asynchronous methods. + """ + + async def get_application(self) -> Application: + """Get application. + + This method should be overridden + to return the aiohttp.web.Application + object to test. + """ + return self.get_app() + + def get_app(self) -> Application: + """Obsolete method used to constructing web application. + + Use .get_application() coroutine instead. + """ + raise RuntimeError("Did you forget to define get_application()?") + + async def asyncSetUp(self) -> None: + self.loop = asyncio.get_running_loop() + return await self.setUpAsync() + + async def setUpAsync(self) -> None: + self.app = await self.get_application() + self.server = await self.get_server(self.app) + self.client = await self.get_client(self.server) + + await self.client.start_server() + + async def asyncTearDown(self) -> None: + return await self.tearDownAsync() + + async def tearDownAsync(self) -> None: + await self.client.close() + + async def get_server(self, app: Application) -> TestServer: + """Return a TestServer instance.""" + return TestServer(app, loop=self.loop) + + async def get_client(self, server: TestServer) -> TestClient: + """Return a TestClient instance.""" + return TestClient(server, loop=self.loop) + + +def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any: + """ + A decorator dedicated to use with asynchronous AioHTTPTestCase test methods. + + In 3.8+, this does nothing. + """ + warnings.warn( + "Decorator `@unittest_run_loop` is no longer needed in aiohttp 3.8+", + DeprecationWarning, + stacklevel=2, + ) + return func + + +_LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop] + + +@contextlib.contextmanager +def loop_context( + loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, fast: bool = False +) -> Iterator[asyncio.AbstractEventLoop]: + """A contextmanager that creates an event_loop, for test purposes. + + Handles the creation and cleanup of a test loop. + """ + loop = setup_test_loop(loop_factory) + yield loop + teardown_test_loop(loop, fast=fast) + + +def setup_test_loop( + loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, +) -> asyncio.AbstractEventLoop: + """Create and return an asyncio.BaseEventLoop instance. + + The caller should also call teardown_test_loop, + once they are done with the loop. + """ + loop = loop_factory() + asyncio.set_event_loop(loop) + return loop + + +def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None: + """Teardown and cleanup an event_loop created by setup_test_loop.""" + closed = loop.is_closed() + if not closed: + loop.call_soon(loop.stop) + loop.run_forever() + loop.close() + + if not fast: + gc.collect() + + asyncio.set_event_loop(None) + + +def _create_app_mock() -> mock.MagicMock: + def get_dict(app: Any, key: str) -> Any: + return app.__app_dict[key] + + def set_dict(app: Any, key: str, value: Any) -> None: + app.__app_dict[key] = value + + app = mock.MagicMock(spec=Application) + app.__app_dict = {} + app.__getitem__ = get_dict + app.__setitem__ = set_dict + + app._debug = False + app.on_response_prepare = Signal(app) + app.on_response_prepare.freeze() + return app + + +def _create_transport(sslcontext: Optional[SSLContext] = None) -> mock.Mock: + transport = mock.Mock() + + def get_extra_info(key: str) -> Optional[SSLContext]: + if key == "sslcontext": + return sslcontext + else: + return None + + transport.get_extra_info.side_effect = get_extra_info + return transport + + +def make_mocked_request( + method: str, + path: str, + headers: Any = None, + *, + match_info: Any = sentinel, + version: HttpVersion = HttpVersion(1, 1), + closing: bool = False, + app: Any = None, + writer: Any = sentinel, + protocol: Any = sentinel, + transport: Any = sentinel, + payload: Any = sentinel, + sslcontext: Optional[SSLContext] = None, + client_max_size: int = 1024**2, + loop: Any = ..., +) -> Request: + """Creates mocked web.Request testing purposes. + + Useful in unit tests, when spinning full web server is overkill or + specific conditions and errors are hard to trigger. + """ + task = mock.Mock() + if loop is ...: + # no loop passed, try to get the current one if + # its is running as we need a real loop to create + # executor jobs to be able to do testing + # with a real executor + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = mock.Mock() + loop.create_future.return_value = () + + if version < HttpVersion(1, 1): + closing = True + + if headers: + headers = CIMultiDictProxy(CIMultiDict(headers)) + raw_hdrs = tuple( + (k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items() + ) + else: + headers = CIMultiDictProxy(CIMultiDict()) + raw_hdrs = () + + chunked = "chunked" in headers.get(hdrs.TRANSFER_ENCODING, "").lower() + + message = RawRequestMessage( + method, + path, + version, + headers, + raw_hdrs, + closing, + None, + False, + chunked, + URL(path), + ) + if app is None: + app = _create_app_mock() + + if transport is sentinel: + transport = _create_transport(sslcontext) + + if protocol is sentinel: + protocol = mock.Mock() + protocol.transport = transport + + if writer is sentinel: + writer = mock.Mock() + writer.write_headers = make_mocked_coro(None) + writer.write = make_mocked_coro(None) + writer.write_eof = make_mocked_coro(None) + writer.drain = make_mocked_coro(None) + writer.transport = transport + + protocol.transport = transport + protocol.writer = writer + + if payload is sentinel: + payload = mock.Mock() + + req = Request( + message, payload, protocol, writer, task, loop, client_max_size=client_max_size + ) + + match_info = UrlMappingMatchInfo( + {} if match_info is sentinel else match_info, mock.Mock() + ) + match_info.add_app(app) + req._match_info = match_info + + return req + + +def make_mocked_coro( + return_value: Any = sentinel, raise_exception: Any = sentinel +) -> Any: + """Creates a coroutine mock.""" + + async def mock_coro(*args: Any, **kwargs: Any) -> Any: + if raise_exception is not sentinel: + raise raise_exception + if not inspect.isawaitable(return_value): + return return_value + await return_value + + return mock.Mock(wraps=mock_coro) diff --git a/env/Lib/site-packages/aiohttp/tracing.py b/env/Lib/site-packages/aiohttp/tracing.py new file mode 100644 index 0000000..012ed7b --- /dev/null +++ b/env/Lib/site-packages/aiohttp/tracing.py @@ -0,0 +1,470 @@ +from types import SimpleNamespace +from typing import TYPE_CHECKING, Awaitable, Mapping, Optional, Protocol, Type, TypeVar + +import attr +from aiosignal import Signal +from multidict import CIMultiDict +from yarl import URL + +from .client_reqrep import ClientResponse + +if TYPE_CHECKING: + from .client import ClientSession + + _ParamT_contra = TypeVar("_ParamT_contra", contravariant=True) + + class _SignalCallback(Protocol[_ParamT_contra]): + def __call__( + self, + __client_session: ClientSession, + __trace_config_ctx: SimpleNamespace, + __params: _ParamT_contra, + ) -> Awaitable[None]: ... + + +__all__ = ( + "TraceConfig", + "TraceRequestStartParams", + "TraceRequestEndParams", + "TraceRequestExceptionParams", + "TraceConnectionQueuedStartParams", + "TraceConnectionQueuedEndParams", + "TraceConnectionCreateStartParams", + "TraceConnectionCreateEndParams", + "TraceConnectionReuseconnParams", + "TraceDnsResolveHostStartParams", + "TraceDnsResolveHostEndParams", + "TraceDnsCacheHitParams", + "TraceDnsCacheMissParams", + "TraceRequestRedirectParams", + "TraceRequestChunkSentParams", + "TraceResponseChunkReceivedParams", + "TraceRequestHeadersSentParams", +) + + +class TraceConfig: + """First-class used to trace requests launched via ClientSession objects.""" + + def __init__( + self, trace_config_ctx_factory: Type[SimpleNamespace] = SimpleNamespace + ) -> None: + self._on_request_start: Signal[_SignalCallback[TraceRequestStartParams]] = ( + Signal(self) + ) + self._on_request_chunk_sent: Signal[ + _SignalCallback[TraceRequestChunkSentParams] + ] = Signal(self) + self._on_response_chunk_received: Signal[ + _SignalCallback[TraceResponseChunkReceivedParams] + ] = Signal(self) + self._on_request_end: Signal[_SignalCallback[TraceRequestEndParams]] = Signal( + self + ) + self._on_request_exception: Signal[ + _SignalCallback[TraceRequestExceptionParams] + ] = Signal(self) + self._on_request_redirect: Signal[ + _SignalCallback[TraceRequestRedirectParams] + ] = Signal(self) + self._on_connection_queued_start: Signal[ + _SignalCallback[TraceConnectionQueuedStartParams] + ] = Signal(self) + self._on_connection_queued_end: Signal[ + _SignalCallback[TraceConnectionQueuedEndParams] + ] = Signal(self) + self._on_connection_create_start: Signal[ + _SignalCallback[TraceConnectionCreateStartParams] + ] = Signal(self) + self._on_connection_create_end: Signal[ + _SignalCallback[TraceConnectionCreateEndParams] + ] = Signal(self) + self._on_connection_reuseconn: Signal[ + _SignalCallback[TraceConnectionReuseconnParams] + ] = Signal(self) + self._on_dns_resolvehost_start: Signal[ + _SignalCallback[TraceDnsResolveHostStartParams] + ] = Signal(self) + self._on_dns_resolvehost_end: Signal[ + _SignalCallback[TraceDnsResolveHostEndParams] + ] = Signal(self) + self._on_dns_cache_hit: Signal[_SignalCallback[TraceDnsCacheHitParams]] = ( + Signal(self) + ) + self._on_dns_cache_miss: Signal[_SignalCallback[TraceDnsCacheMissParams]] = ( + Signal(self) + ) + self._on_request_headers_sent: Signal[ + _SignalCallback[TraceRequestHeadersSentParams] + ] = Signal(self) + + self._trace_config_ctx_factory = trace_config_ctx_factory + + def trace_config_ctx( + self, trace_request_ctx: Optional[Mapping[str, str]] = None + ) -> SimpleNamespace: + """Return a new trace_config_ctx instance""" + return self._trace_config_ctx_factory(trace_request_ctx=trace_request_ctx) + + def freeze(self) -> None: + self._on_request_start.freeze() + self._on_request_chunk_sent.freeze() + self._on_response_chunk_received.freeze() + self._on_request_end.freeze() + self._on_request_exception.freeze() + self._on_request_redirect.freeze() + self._on_connection_queued_start.freeze() + self._on_connection_queued_end.freeze() + self._on_connection_create_start.freeze() + self._on_connection_create_end.freeze() + self._on_connection_reuseconn.freeze() + self._on_dns_resolvehost_start.freeze() + self._on_dns_resolvehost_end.freeze() + self._on_dns_cache_hit.freeze() + self._on_dns_cache_miss.freeze() + self._on_request_headers_sent.freeze() + + @property + def on_request_start(self) -> "Signal[_SignalCallback[TraceRequestStartParams]]": + return self._on_request_start + + @property + def on_request_chunk_sent( + self, + ) -> "Signal[_SignalCallback[TraceRequestChunkSentParams]]": + return self._on_request_chunk_sent + + @property + def on_response_chunk_received( + self, + ) -> "Signal[_SignalCallback[TraceResponseChunkReceivedParams]]": + return self._on_response_chunk_received + + @property + def on_request_end(self) -> "Signal[_SignalCallback[TraceRequestEndParams]]": + return self._on_request_end + + @property + def on_request_exception( + self, + ) -> "Signal[_SignalCallback[TraceRequestExceptionParams]]": + return self._on_request_exception + + @property + def on_request_redirect( + self, + ) -> "Signal[_SignalCallback[TraceRequestRedirectParams]]": + return self._on_request_redirect + + @property + def on_connection_queued_start( + self, + ) -> "Signal[_SignalCallback[TraceConnectionQueuedStartParams]]": + return self._on_connection_queued_start + + @property + def on_connection_queued_end( + self, + ) -> "Signal[_SignalCallback[TraceConnectionQueuedEndParams]]": + return self._on_connection_queued_end + + @property + def on_connection_create_start( + self, + ) -> "Signal[_SignalCallback[TraceConnectionCreateStartParams]]": + return self._on_connection_create_start + + @property + def on_connection_create_end( + self, + ) -> "Signal[_SignalCallback[TraceConnectionCreateEndParams]]": + return self._on_connection_create_end + + @property + def on_connection_reuseconn( + self, + ) -> "Signal[_SignalCallback[TraceConnectionReuseconnParams]]": + return self._on_connection_reuseconn + + @property + def on_dns_resolvehost_start( + self, + ) -> "Signal[_SignalCallback[TraceDnsResolveHostStartParams]]": + return self._on_dns_resolvehost_start + + @property + def on_dns_resolvehost_end( + self, + ) -> "Signal[_SignalCallback[TraceDnsResolveHostEndParams]]": + return self._on_dns_resolvehost_end + + @property + def on_dns_cache_hit(self) -> "Signal[_SignalCallback[TraceDnsCacheHitParams]]": + return self._on_dns_cache_hit + + @property + def on_dns_cache_miss(self) -> "Signal[_SignalCallback[TraceDnsCacheMissParams]]": + return self._on_dns_cache_miss + + @property + def on_request_headers_sent( + self, + ) -> "Signal[_SignalCallback[TraceRequestHeadersSentParams]]": + return self._on_request_headers_sent + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestStartParams: + """Parameters sent by the `on_request_start` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestChunkSentParams: + """Parameters sent by the `on_request_chunk_sent` signal""" + + method: str + url: URL + chunk: bytes + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceResponseChunkReceivedParams: + """Parameters sent by the `on_response_chunk_received` signal""" + + method: str + url: URL + chunk: bytes + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestEndParams: + """Parameters sent by the `on_request_end` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + response: ClientResponse + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestExceptionParams: + """Parameters sent by the `on_request_exception` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + exception: BaseException + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestRedirectParams: + """Parameters sent by the `on_request_redirect` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + response: ClientResponse + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionQueuedStartParams: + """Parameters sent by the `on_connection_queued_start` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionQueuedEndParams: + """Parameters sent by the `on_connection_queued_end` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionCreateStartParams: + """Parameters sent by the `on_connection_create_start` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionCreateEndParams: + """Parameters sent by the `on_connection_create_end` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionReuseconnParams: + """Parameters sent by the `on_connection_reuseconn` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceDnsResolveHostStartParams: + """Parameters sent by the `on_dns_resolvehost_start` signal""" + + host: str + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceDnsResolveHostEndParams: + """Parameters sent by the `on_dns_resolvehost_end` signal""" + + host: str + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceDnsCacheHitParams: + """Parameters sent by the `on_dns_cache_hit` signal""" + + host: str + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceDnsCacheMissParams: + """Parameters sent by the `on_dns_cache_miss` signal""" + + host: str + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestHeadersSentParams: + """Parameters sent by the `on_request_headers_sent` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + + +class Trace: + """Internal dependency holder class. + + Used to keep together the main dependencies used + at the moment of send a signal. + """ + + def __init__( + self, + session: "ClientSession", + trace_config: TraceConfig, + trace_config_ctx: SimpleNamespace, + ) -> None: + self._trace_config = trace_config + self._trace_config_ctx = trace_config_ctx + self._session = session + + async def send_request_start( + self, method: str, url: URL, headers: "CIMultiDict[str]" + ) -> None: + return await self._trace_config.on_request_start.send( + self._session, + self._trace_config_ctx, + TraceRequestStartParams(method, url, headers), + ) + + async def send_request_chunk_sent( + self, method: str, url: URL, chunk: bytes + ) -> None: + return await self._trace_config.on_request_chunk_sent.send( + self._session, + self._trace_config_ctx, + TraceRequestChunkSentParams(method, url, chunk), + ) + + async def send_response_chunk_received( + self, method: str, url: URL, chunk: bytes + ) -> None: + return await self._trace_config.on_response_chunk_received.send( + self._session, + self._trace_config_ctx, + TraceResponseChunkReceivedParams(method, url, chunk), + ) + + async def send_request_end( + self, + method: str, + url: URL, + headers: "CIMultiDict[str]", + response: ClientResponse, + ) -> None: + return await self._trace_config.on_request_end.send( + self._session, + self._trace_config_ctx, + TraceRequestEndParams(method, url, headers, response), + ) + + async def send_request_exception( + self, + method: str, + url: URL, + headers: "CIMultiDict[str]", + exception: BaseException, + ) -> None: + return await self._trace_config.on_request_exception.send( + self._session, + self._trace_config_ctx, + TraceRequestExceptionParams(method, url, headers, exception), + ) + + async def send_request_redirect( + self, + method: str, + url: URL, + headers: "CIMultiDict[str]", + response: ClientResponse, + ) -> None: + return await self._trace_config._on_request_redirect.send( + self._session, + self._trace_config_ctx, + TraceRequestRedirectParams(method, url, headers, response), + ) + + async def send_connection_queued_start(self) -> None: + return await self._trace_config.on_connection_queued_start.send( + self._session, self._trace_config_ctx, TraceConnectionQueuedStartParams() + ) + + async def send_connection_queued_end(self) -> None: + return await self._trace_config.on_connection_queued_end.send( + self._session, self._trace_config_ctx, TraceConnectionQueuedEndParams() + ) + + async def send_connection_create_start(self) -> None: + return await self._trace_config.on_connection_create_start.send( + self._session, self._trace_config_ctx, TraceConnectionCreateStartParams() + ) + + async def send_connection_create_end(self) -> None: + return await self._trace_config.on_connection_create_end.send( + self._session, self._trace_config_ctx, TraceConnectionCreateEndParams() + ) + + async def send_connection_reuseconn(self) -> None: + return await self._trace_config.on_connection_reuseconn.send( + self._session, self._trace_config_ctx, TraceConnectionReuseconnParams() + ) + + async def send_dns_resolvehost_start(self, host: str) -> None: + return await self._trace_config.on_dns_resolvehost_start.send( + self._session, self._trace_config_ctx, TraceDnsResolveHostStartParams(host) + ) + + async def send_dns_resolvehost_end(self, host: str) -> None: + return await self._trace_config.on_dns_resolvehost_end.send( + self._session, self._trace_config_ctx, TraceDnsResolveHostEndParams(host) + ) + + async def send_dns_cache_hit(self, host: str) -> None: + return await self._trace_config.on_dns_cache_hit.send( + self._session, self._trace_config_ctx, TraceDnsCacheHitParams(host) + ) + + async def send_dns_cache_miss(self, host: str) -> None: + return await self._trace_config.on_dns_cache_miss.send( + self._session, self._trace_config_ctx, TraceDnsCacheMissParams(host) + ) + + async def send_request_headers( + self, method: str, url: URL, headers: "CIMultiDict[str]" + ) -> None: + return await self._trace_config._on_request_headers_sent.send( + self._session, + self._trace_config_ctx, + TraceRequestHeadersSentParams(method, url, headers), + ) diff --git a/env/Lib/site-packages/aiohttp/typedefs.py b/env/Lib/site-packages/aiohttp/typedefs.py new file mode 100644 index 0000000..9fb21c1 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/typedefs.py @@ -0,0 +1,67 @@ +import json +import os +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Iterable, + Mapping, + Protocol, + Tuple, + Union, +) + +from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy, istr +from yarl import URL + +DEFAULT_JSON_ENCODER = json.dumps +DEFAULT_JSON_DECODER = json.loads + +if TYPE_CHECKING: + _CIMultiDict = CIMultiDict[str] + _CIMultiDictProxy = CIMultiDictProxy[str] + _MultiDict = MultiDict[str] + _MultiDictProxy = MultiDictProxy[str] + from http.cookies import BaseCookie, Morsel + + from .web import Request, StreamResponse +else: + _CIMultiDict = CIMultiDict + _CIMultiDictProxy = CIMultiDictProxy + _MultiDict = MultiDict + _MultiDictProxy = MultiDictProxy + +Byteish = Union[bytes, bytearray, memoryview] +JSONEncoder = Callable[[Any], str] +JSONDecoder = Callable[[str], Any] +LooseHeaders = Union[ + Mapping[str, str], + Mapping[istr, str], + _CIMultiDict, + _CIMultiDictProxy, + Iterable[Tuple[Union[str, istr], str]], +] +RawHeaders = Tuple[Tuple[bytes, bytes], ...] +StrOrURL = Union[str, URL] + +LooseCookiesMappings = Mapping[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]] +LooseCookiesIterables = Iterable[ + Tuple[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]] +] +LooseCookies = Union[ + LooseCookiesMappings, + LooseCookiesIterables, + "BaseCookie[str]", +] + +Handler = Callable[["Request"], Awaitable["StreamResponse"]] + + +class Middleware(Protocol): + def __call__( + self, request: "Request", handler: Handler + ) -> Awaitable["StreamResponse"]: ... + + +PathLike = Union[str, "os.PathLike[str]"] diff --git a/env/Lib/site-packages/aiohttp/web.py b/env/Lib/site-packages/aiohttp/web.py new file mode 100644 index 0000000..8708f1f --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web.py @@ -0,0 +1,590 @@ +import asyncio +import logging +import os +import socket +import sys +import warnings +from argparse import ArgumentParser +from collections.abc import Iterable +from importlib import import_module +from typing import ( + Any, + Awaitable, + Callable, + Iterable as TypingIterable, + List, + Optional, + Set, + Type, + Union, + cast, +) + +from .abc import AbstractAccessLogger +from .helpers import AppKey as AppKey +from .log import access_logger +from .typedefs import PathLike +from .web_app import Application as Application, CleanupError as CleanupError +from .web_exceptions import ( + HTTPAccepted as HTTPAccepted, + HTTPBadGateway as HTTPBadGateway, + HTTPBadRequest as HTTPBadRequest, + HTTPClientError as HTTPClientError, + HTTPConflict as HTTPConflict, + HTTPCreated as HTTPCreated, + HTTPError as HTTPError, + HTTPException as HTTPException, + HTTPExpectationFailed as HTTPExpectationFailed, + HTTPFailedDependency as HTTPFailedDependency, + HTTPForbidden as HTTPForbidden, + HTTPFound as HTTPFound, + HTTPGatewayTimeout as HTTPGatewayTimeout, + HTTPGone as HTTPGone, + HTTPInsufficientStorage as HTTPInsufficientStorage, + HTTPInternalServerError as HTTPInternalServerError, + HTTPLengthRequired as HTTPLengthRequired, + HTTPMethodNotAllowed as HTTPMethodNotAllowed, + HTTPMisdirectedRequest as HTTPMisdirectedRequest, + HTTPMove as HTTPMove, + HTTPMovedPermanently as HTTPMovedPermanently, + HTTPMultipleChoices as HTTPMultipleChoices, + HTTPNetworkAuthenticationRequired as HTTPNetworkAuthenticationRequired, + HTTPNoContent as HTTPNoContent, + HTTPNonAuthoritativeInformation as HTTPNonAuthoritativeInformation, + HTTPNotAcceptable as HTTPNotAcceptable, + HTTPNotExtended as HTTPNotExtended, + HTTPNotFound as HTTPNotFound, + HTTPNotImplemented as HTTPNotImplemented, + HTTPNotModified as HTTPNotModified, + HTTPOk as HTTPOk, + HTTPPartialContent as HTTPPartialContent, + HTTPPaymentRequired as HTTPPaymentRequired, + HTTPPermanentRedirect as HTTPPermanentRedirect, + HTTPPreconditionFailed as HTTPPreconditionFailed, + HTTPPreconditionRequired as HTTPPreconditionRequired, + HTTPProxyAuthenticationRequired as HTTPProxyAuthenticationRequired, + HTTPRedirection as HTTPRedirection, + HTTPRequestEntityTooLarge as HTTPRequestEntityTooLarge, + HTTPRequestHeaderFieldsTooLarge as HTTPRequestHeaderFieldsTooLarge, + HTTPRequestRangeNotSatisfiable as HTTPRequestRangeNotSatisfiable, + HTTPRequestTimeout as HTTPRequestTimeout, + HTTPRequestURITooLong as HTTPRequestURITooLong, + HTTPResetContent as HTTPResetContent, + HTTPSeeOther as HTTPSeeOther, + HTTPServerError as HTTPServerError, + HTTPServiceUnavailable as HTTPServiceUnavailable, + HTTPSuccessful as HTTPSuccessful, + HTTPTemporaryRedirect as HTTPTemporaryRedirect, + HTTPTooManyRequests as HTTPTooManyRequests, + HTTPUnauthorized as HTTPUnauthorized, + HTTPUnavailableForLegalReasons as HTTPUnavailableForLegalReasons, + HTTPUnprocessableEntity as HTTPUnprocessableEntity, + HTTPUnsupportedMediaType as HTTPUnsupportedMediaType, + HTTPUpgradeRequired as HTTPUpgradeRequired, + HTTPUseProxy as HTTPUseProxy, + HTTPVariantAlsoNegotiates as HTTPVariantAlsoNegotiates, + HTTPVersionNotSupported as HTTPVersionNotSupported, + NotAppKeyWarning as NotAppKeyWarning, +) +from .web_fileresponse import FileResponse as FileResponse +from .web_log import AccessLogger +from .web_middlewares import ( + middleware as middleware, + normalize_path_middleware as normalize_path_middleware, +) +from .web_protocol import ( + PayloadAccessError as PayloadAccessError, + RequestHandler as RequestHandler, + RequestPayloadError as RequestPayloadError, +) +from .web_request import ( + BaseRequest as BaseRequest, + FileField as FileField, + Request as Request, +) +from .web_response import ( + ContentCoding as ContentCoding, + Response as Response, + StreamResponse as StreamResponse, + json_response as json_response, +) +from .web_routedef import ( + AbstractRouteDef as AbstractRouteDef, + RouteDef as RouteDef, + RouteTableDef as RouteTableDef, + StaticDef as StaticDef, + delete as delete, + get as get, + head as head, + options as options, + patch as patch, + post as post, + put as put, + route as route, + static as static, + view as view, +) +from .web_runner import ( + AppRunner as AppRunner, + BaseRunner as BaseRunner, + BaseSite as BaseSite, + GracefulExit as GracefulExit, + NamedPipeSite as NamedPipeSite, + ServerRunner as ServerRunner, + SockSite as SockSite, + TCPSite as TCPSite, + UnixSite as UnixSite, +) +from .web_server import Server as Server +from .web_urldispatcher import ( + AbstractResource as AbstractResource, + AbstractRoute as AbstractRoute, + DynamicResource as DynamicResource, + PlainResource as PlainResource, + PrefixedSubAppResource as PrefixedSubAppResource, + Resource as Resource, + ResourceRoute as ResourceRoute, + StaticResource as StaticResource, + UrlDispatcher as UrlDispatcher, + UrlMappingMatchInfo as UrlMappingMatchInfo, + View as View, +) +from .web_ws import ( + WebSocketReady as WebSocketReady, + WebSocketResponse as WebSocketResponse, + WSMsgType as WSMsgType, +) + +__all__ = ( + # web_app + "AppKey", + "Application", + "CleanupError", + # web_exceptions + "NotAppKeyWarning", + "HTTPAccepted", + "HTTPBadGateway", + "HTTPBadRequest", + "HTTPClientError", + "HTTPConflict", + "HTTPCreated", + "HTTPError", + "HTTPException", + "HTTPExpectationFailed", + "HTTPFailedDependency", + "HTTPForbidden", + "HTTPFound", + "HTTPGatewayTimeout", + "HTTPGone", + "HTTPInsufficientStorage", + "HTTPInternalServerError", + "HTTPLengthRequired", + "HTTPMethodNotAllowed", + "HTTPMisdirectedRequest", + "HTTPMove", + "HTTPMovedPermanently", + "HTTPMultipleChoices", + "HTTPNetworkAuthenticationRequired", + "HTTPNoContent", + "HTTPNonAuthoritativeInformation", + "HTTPNotAcceptable", + "HTTPNotExtended", + "HTTPNotFound", + "HTTPNotImplemented", + "HTTPNotModified", + "HTTPOk", + "HTTPPartialContent", + "HTTPPaymentRequired", + "HTTPPermanentRedirect", + "HTTPPreconditionFailed", + "HTTPPreconditionRequired", + "HTTPProxyAuthenticationRequired", + "HTTPRedirection", + "HTTPRequestEntityTooLarge", + "HTTPRequestHeaderFieldsTooLarge", + "HTTPRequestRangeNotSatisfiable", + "HTTPRequestTimeout", + "HTTPRequestURITooLong", + "HTTPResetContent", + "HTTPSeeOther", + "HTTPServerError", + "HTTPServiceUnavailable", + "HTTPSuccessful", + "HTTPTemporaryRedirect", + "HTTPTooManyRequests", + "HTTPUnauthorized", + "HTTPUnavailableForLegalReasons", + "HTTPUnprocessableEntity", + "HTTPUnsupportedMediaType", + "HTTPUpgradeRequired", + "HTTPUseProxy", + "HTTPVariantAlsoNegotiates", + "HTTPVersionNotSupported", + # web_fileresponse + "FileResponse", + # web_middlewares + "middleware", + "normalize_path_middleware", + # web_protocol + "PayloadAccessError", + "RequestHandler", + "RequestPayloadError", + # web_request + "BaseRequest", + "FileField", + "Request", + # web_response + "ContentCoding", + "Response", + "StreamResponse", + "json_response", + # web_routedef + "AbstractRouteDef", + "RouteDef", + "RouteTableDef", + "StaticDef", + "delete", + "get", + "head", + "options", + "patch", + "post", + "put", + "route", + "static", + "view", + # web_runner + "AppRunner", + "BaseRunner", + "BaseSite", + "GracefulExit", + "ServerRunner", + "SockSite", + "TCPSite", + "UnixSite", + "NamedPipeSite", + # web_server + "Server", + # web_urldispatcher + "AbstractResource", + "AbstractRoute", + "DynamicResource", + "PlainResource", + "PrefixedSubAppResource", + "Resource", + "ResourceRoute", + "StaticResource", + "UrlDispatcher", + "UrlMappingMatchInfo", + "View", + # web_ws + "WebSocketReady", + "WebSocketResponse", + "WSMsgType", + # web + "run_app", +) + + +try: + from ssl import SSLContext +except ImportError: # pragma: no cover + SSLContext = Any # type: ignore[misc,assignment] + +# Only display warning when using -Wdefault, -We, -X dev or similar. +warnings.filterwarnings("ignore", category=NotAppKeyWarning, append=True) + +HostSequence = TypingIterable[str] + + +async def _run_app( + app: Union[Application, Awaitable[Application]], + *, + host: Optional[Union[str, HostSequence]] = None, + port: Optional[int] = None, + path: Union[PathLike, TypingIterable[PathLike], None] = None, + sock: Optional[Union[socket.socket, TypingIterable[socket.socket]]] = None, + shutdown_timeout: float = 60.0, + keepalive_timeout: float = 75.0, + ssl_context: Optional[SSLContext] = None, + print: Optional[Callable[..., None]] = print, + backlog: int = 128, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + access_log_format: str = AccessLogger.LOG_FORMAT, + access_log: Optional[logging.Logger] = access_logger, + handle_signals: bool = True, + reuse_address: Optional[bool] = None, + reuse_port: Optional[bool] = None, + handler_cancellation: bool = False, +) -> None: + # An internal function to actually do all dirty job for application running + if asyncio.iscoroutine(app): + app = await app + + app = cast(Application, app) + + runner = AppRunner( + app, + handle_signals=handle_signals, + access_log_class=access_log_class, + access_log_format=access_log_format, + access_log=access_log, + keepalive_timeout=keepalive_timeout, + shutdown_timeout=shutdown_timeout, + handler_cancellation=handler_cancellation, + ) + + await runner.setup() + + sites: List[BaseSite] = [] + + try: + if host is not None: + if isinstance(host, (str, bytes, bytearray, memoryview)): + sites.append( + TCPSite( + runner, + host, + port, + ssl_context=ssl_context, + backlog=backlog, + reuse_address=reuse_address, + reuse_port=reuse_port, + ) + ) + else: + for h in host: + sites.append( + TCPSite( + runner, + h, + port, + ssl_context=ssl_context, + backlog=backlog, + reuse_address=reuse_address, + reuse_port=reuse_port, + ) + ) + elif path is None and sock is None or port is not None: + sites.append( + TCPSite( + runner, + port=port, + ssl_context=ssl_context, + backlog=backlog, + reuse_address=reuse_address, + reuse_port=reuse_port, + ) + ) + + if path is not None: + if isinstance(path, (str, os.PathLike)): + sites.append( + UnixSite( + runner, + path, + ssl_context=ssl_context, + backlog=backlog, + ) + ) + else: + for p in path: + sites.append( + UnixSite( + runner, + p, + ssl_context=ssl_context, + backlog=backlog, + ) + ) + + if sock is not None: + if not isinstance(sock, Iterable): + sites.append( + SockSite( + runner, + sock, + ssl_context=ssl_context, + backlog=backlog, + ) + ) + else: + for s in sock: + sites.append( + SockSite( + runner, + s, + ssl_context=ssl_context, + backlog=backlog, + ) + ) + for site in sites: + await site.start() + + if print: # pragma: no branch + names = sorted(str(s.name) for s in runner.sites) + print( + "======== Running on {} ========\n" + "(Press CTRL+C to quit)".format(", ".join(names)) + ) + + # sleep forever by 1 hour intervals, + while True: + await asyncio.sleep(3600) + finally: + await runner.cleanup() + + +def _cancel_tasks( + to_cancel: Set["asyncio.Task[Any]"], loop: asyncio.AbstractEventLoop +) -> None: + if not to_cancel: + return + + for task in to_cancel: + task.cancel() + + loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True)) + + for task in to_cancel: + if task.cancelled(): + continue + if task.exception() is not None: + loop.call_exception_handler( + { + "message": "unhandled exception during asyncio.run() shutdown", + "exception": task.exception(), + "task": task, + } + ) + + +def run_app( + app: Union[Application, Awaitable[Application]], + *, + host: Optional[Union[str, HostSequence]] = None, + port: Optional[int] = None, + path: Union[PathLike, TypingIterable[PathLike], None] = None, + sock: Optional[Union[socket.socket, TypingIterable[socket.socket]]] = None, + shutdown_timeout: float = 60.0, + keepalive_timeout: float = 75.0, + ssl_context: Optional[SSLContext] = None, + print: Optional[Callable[..., None]] = print, + backlog: int = 128, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + access_log_format: str = AccessLogger.LOG_FORMAT, + access_log: Optional[logging.Logger] = access_logger, + handle_signals: bool = True, + reuse_address: Optional[bool] = None, + reuse_port: Optional[bool] = None, + handler_cancellation: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, +) -> None: + """Run an app locally""" + if loop is None: + loop = asyncio.new_event_loop() + + # Configure if and only if in debugging mode and using the default logger + if loop.get_debug() and access_log and access_log.name == "aiohttp.access": + if access_log.level == logging.NOTSET: + access_log.setLevel(logging.DEBUG) + if not access_log.hasHandlers(): + access_log.addHandler(logging.StreamHandler()) + + main_task = loop.create_task( + _run_app( + app, + host=host, + port=port, + path=path, + sock=sock, + shutdown_timeout=shutdown_timeout, + keepalive_timeout=keepalive_timeout, + ssl_context=ssl_context, + print=print, + backlog=backlog, + access_log_class=access_log_class, + access_log_format=access_log_format, + access_log=access_log, + handle_signals=handle_signals, + reuse_address=reuse_address, + reuse_port=reuse_port, + handler_cancellation=handler_cancellation, + ) + ) + + try: + asyncio.set_event_loop(loop) + loop.run_until_complete(main_task) + except (GracefulExit, KeyboardInterrupt): # pragma: no cover + pass + finally: + _cancel_tasks({main_task}, loop) + _cancel_tasks(asyncio.all_tasks(loop), loop) + loop.run_until_complete(loop.shutdown_asyncgens()) + loop.close() + + +def main(argv: List[str]) -> None: + arg_parser = ArgumentParser( + description="aiohttp.web Application server", prog="aiohttp.web" + ) + arg_parser.add_argument( + "entry_func", + help=( + "Callable returning the `aiohttp.web.Application` instance to " + "run. Should be specified in the 'module:function' syntax." + ), + metavar="entry-func", + ) + arg_parser.add_argument( + "-H", + "--hostname", + help="TCP/IP hostname to serve on (default: %(default)r)", + default="localhost", + ) + arg_parser.add_argument( + "-P", + "--port", + help="TCP/IP port to serve on (default: %(default)r)", + type=int, + default="8080", + ) + arg_parser.add_argument( + "-U", + "--path", + help="Unix file system path to serve on. Specifying a path will cause " + "hostname and port arguments to be ignored.", + ) + args, extra_argv = arg_parser.parse_known_args(argv) + + # Import logic + mod_str, _, func_str = args.entry_func.partition(":") + if not func_str or not mod_str: + arg_parser.error("'entry-func' not in 'module:function' syntax") + if mod_str.startswith("."): + arg_parser.error("relative module names not supported") + try: + module = import_module(mod_str) + except ImportError as ex: + arg_parser.error(f"unable to import {mod_str}: {ex}") + try: + func = getattr(module, func_str) + except AttributeError: + arg_parser.error(f"module {mod_str!r} has no attribute {func_str!r}") + + # Compatibility logic + if args.path is not None and not hasattr(socket, "AF_UNIX"): + arg_parser.error( + "file system paths not supported by your operating" " environment" + ) + + logging.basicConfig(level=logging.DEBUG) + + app = func(extra_argv) + run_app(app, host=args.hostname, port=args.port, path=args.path) + arg_parser.exit(message="Stopped\n") + + +if __name__ == "__main__": # pragma: no branch + main(sys.argv[1:]) # pragma: no cover diff --git a/env/Lib/site-packages/aiohttp/web_app.py b/env/Lib/site-packages/aiohttp/web_app.py new file mode 100644 index 0000000..3b4b648 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_app.py @@ -0,0 +1,590 @@ +import asyncio +import logging +import warnings +from functools import partial, update_wrapper +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterator, + Awaitable, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + MutableMapping, + Optional, + Sequence, + Tuple, + Type, + TypeVar, + Union, + cast, + overload, +) + +from aiosignal import Signal +from frozenlist import FrozenList + +from . import hdrs +from .abc import ( + AbstractAccessLogger, + AbstractMatchInfo, + AbstractRouter, + AbstractStreamWriter, +) +from .helpers import DEBUG, AppKey +from .http_parser import RawRequestMessage +from .log import web_logger +from .streams import StreamReader +from .typedefs import Middleware +from .web_exceptions import NotAppKeyWarning +from .web_log import AccessLogger +from .web_middlewares import _fix_request_current_app +from .web_protocol import RequestHandler +from .web_request import Request +from .web_response import StreamResponse +from .web_routedef import AbstractRouteDef +from .web_server import Server +from .web_urldispatcher import ( + AbstractResource, + AbstractRoute, + Domain, + MaskDomain, + MatchedSubAppResource, + PrefixedSubAppResource, + UrlDispatcher, +) + +__all__ = ("Application", "CleanupError") + + +if TYPE_CHECKING: + _AppSignal = Signal[Callable[["Application"], Awaitable[None]]] + _RespPrepareSignal = Signal[Callable[[Request, StreamResponse], Awaitable[None]]] + _Middlewares = FrozenList[Middleware] + _MiddlewaresHandlers = Optional[Sequence[Tuple[Middleware, bool]]] + _Subapps = List["Application"] +else: + # No type checker mode, skip types + _AppSignal = Signal + _RespPrepareSignal = Signal + _Middlewares = FrozenList + _MiddlewaresHandlers = Optional[Sequence] + _Subapps = List + +_T = TypeVar("_T") +_U = TypeVar("_U") +_Resource = TypeVar("_Resource", bound=AbstractResource) + + +class Application(MutableMapping[Union[str, AppKey[Any]], Any]): + ATTRS = frozenset( + [ + "logger", + "_debug", + "_router", + "_loop", + "_handler_args", + "_middlewares", + "_middlewares_handlers", + "_run_middlewares", + "_state", + "_frozen", + "_pre_frozen", + "_subapps", + "_on_response_prepare", + "_on_startup", + "_on_shutdown", + "_on_cleanup", + "_client_max_size", + "_cleanup_ctx", + ] + ) + + def __init__( + self, + *, + logger: logging.Logger = web_logger, + router: Optional[UrlDispatcher] = None, + middlewares: Iterable[Middleware] = (), + handler_args: Optional[Mapping[str, Any]] = None, + client_max_size: int = 1024**2, + loop: Optional[asyncio.AbstractEventLoop] = None, + debug: Any = ..., # mypy doesn't support ellipsis + ) -> None: + if router is None: + router = UrlDispatcher() + else: + warnings.warn( + "router argument is deprecated", DeprecationWarning, stacklevel=2 + ) + assert isinstance(router, AbstractRouter), router + + if loop is not None: + warnings.warn( + "loop argument is deprecated", DeprecationWarning, stacklevel=2 + ) + + if debug is not ...: + warnings.warn( + "debug argument is deprecated", DeprecationWarning, stacklevel=2 + ) + self._debug = debug + self._router: UrlDispatcher = router + self._loop = loop + self._handler_args = handler_args + self.logger = logger + + self._middlewares: _Middlewares = FrozenList(middlewares) + + # initialized on freezing + self._middlewares_handlers: _MiddlewaresHandlers = None + # initialized on freezing + self._run_middlewares: Optional[bool] = None + + self._state: Dict[Union[AppKey[Any], str], object] = {} + self._frozen = False + self._pre_frozen = False + self._subapps: _Subapps = [] + + self._on_response_prepare: _RespPrepareSignal = Signal(self) + self._on_startup: _AppSignal = Signal(self) + self._on_shutdown: _AppSignal = Signal(self) + self._on_cleanup: _AppSignal = Signal(self) + self._cleanup_ctx = CleanupContext() + self._on_startup.append(self._cleanup_ctx._on_startup) + self._on_cleanup.append(self._cleanup_ctx._on_cleanup) + self._client_max_size = client_max_size + + def __init_subclass__(cls: Type["Application"]) -> None: + warnings.warn( + "Inheritance class {} from web.Application " + "is discouraged".format(cls.__name__), + DeprecationWarning, + stacklevel=3, + ) + + if DEBUG: # pragma: no cover + + def __setattr__(self, name: str, val: Any) -> None: + if name not in self.ATTRS: + warnings.warn( + "Setting custom web.Application.{} attribute " + "is discouraged".format(name), + DeprecationWarning, + stacklevel=2, + ) + super().__setattr__(name, val) + + # MutableMapping API + + def __eq__(self, other: object) -> bool: + return self is other + + @overload # type: ignore[override] + def __getitem__(self, key: AppKey[_T]) -> _T: ... + + @overload + def __getitem__(self, key: str) -> Any: ... + + def __getitem__(self, key: Union[str, AppKey[_T]]) -> Any: + return self._state[key] + + def _check_frozen(self) -> None: + if self._frozen: + warnings.warn( + "Changing state of started or joined " "application is deprecated", + DeprecationWarning, + stacklevel=3, + ) + + @overload # type: ignore[override] + def __setitem__(self, key: AppKey[_T], value: _T) -> None: ... + + @overload + def __setitem__(self, key: str, value: Any) -> None: ... + + def __setitem__(self, key: Union[str, AppKey[_T]], value: Any) -> None: + self._check_frozen() + if not isinstance(key, AppKey): + warnings.warn( + "It is recommended to use web.AppKey instances for keys.\n" + + "https://docs.aiohttp.org/en/stable/web_advanced.html" + + "#application-s-config", + category=NotAppKeyWarning, + stacklevel=2, + ) + self._state[key] = value + + def __delitem__(self, key: Union[str, AppKey[_T]]) -> None: + self._check_frozen() + del self._state[key] + + def __len__(self) -> int: + return len(self._state) + + def __iter__(self) -> Iterator[Union[str, AppKey[Any]]]: + return iter(self._state) + + @overload # type: ignore[override] + def get(self, key: AppKey[_T], default: None = ...) -> Optional[_T]: ... + + @overload + def get(self, key: AppKey[_T], default: _U) -> Union[_T, _U]: ... + + @overload + def get(self, key: str, default: Any = ...) -> Any: ... + + def get(self, key: Union[str, AppKey[_T]], default: Any = None) -> Any: + return self._state.get(key, default) + + ######## + @property + def loop(self) -> asyncio.AbstractEventLoop: + # Technically the loop can be None + # but we mask it by explicit type cast + # to provide more convenient type annotation + warnings.warn("loop property is deprecated", DeprecationWarning, stacklevel=2) + return cast(asyncio.AbstractEventLoop, self._loop) + + def _set_loop(self, loop: Optional[asyncio.AbstractEventLoop]) -> None: + if loop is None: + loop = asyncio.get_event_loop() + if self._loop is not None and self._loop is not loop: + raise RuntimeError( + "web.Application instance initialized with different loop" + ) + + self._loop = loop + + # set loop debug + if self._debug is ...: + self._debug = loop.get_debug() + + # set loop to sub applications + for subapp in self._subapps: + subapp._set_loop(loop) + + @property + def pre_frozen(self) -> bool: + return self._pre_frozen + + def pre_freeze(self) -> None: + if self._pre_frozen: + return + + self._pre_frozen = True + self._middlewares.freeze() + self._router.freeze() + self._on_response_prepare.freeze() + self._cleanup_ctx.freeze() + self._on_startup.freeze() + self._on_shutdown.freeze() + self._on_cleanup.freeze() + self._middlewares_handlers = tuple(self._prepare_middleware()) + + # If current app and any subapp do not have middlewares avoid run all + # of the code footprint that it implies, which have a middleware + # hardcoded per app that sets up the current_app attribute. If no + # middlewares are configured the handler will receive the proper + # current_app without needing all of this code. + self._run_middlewares = True if self.middlewares else False + + for subapp in self._subapps: + subapp.pre_freeze() + self._run_middlewares = self._run_middlewares or subapp._run_middlewares + + @property + def frozen(self) -> bool: + return self._frozen + + def freeze(self) -> None: + if self._frozen: + return + + self.pre_freeze() + self._frozen = True + for subapp in self._subapps: + subapp.freeze() + + @property + def debug(self) -> bool: + warnings.warn("debug property is deprecated", DeprecationWarning, stacklevel=2) + return self._debug # type: ignore[no-any-return] + + def _reg_subapp_signals(self, subapp: "Application") -> None: + def reg_handler(signame: str) -> None: + subsig = getattr(subapp, signame) + + async def handler(app: "Application") -> None: + await subsig.send(subapp) + + appsig = getattr(self, signame) + appsig.append(handler) + + reg_handler("on_startup") + reg_handler("on_shutdown") + reg_handler("on_cleanup") + + def add_subapp(self, prefix: str, subapp: "Application") -> PrefixedSubAppResource: + if not isinstance(prefix, str): + raise TypeError("Prefix must be str") + prefix = prefix.rstrip("/") + if not prefix: + raise ValueError("Prefix cannot be empty") + factory = partial(PrefixedSubAppResource, prefix, subapp) + return self._add_subapp(factory, subapp) + + def _add_subapp( + self, resource_factory: Callable[[], _Resource], subapp: "Application" + ) -> _Resource: + if self.frozen: + raise RuntimeError("Cannot add sub application to frozen application") + if subapp.frozen: + raise RuntimeError("Cannot add frozen application") + resource = resource_factory() + self.router.register_resource(resource) + self._reg_subapp_signals(subapp) + self._subapps.append(subapp) + subapp.pre_freeze() + if self._loop is not None: + subapp._set_loop(self._loop) + return resource + + def add_domain(self, domain: str, subapp: "Application") -> MatchedSubAppResource: + if not isinstance(domain, str): + raise TypeError("Domain must be str") + elif "*" in domain: + rule: Domain = MaskDomain(domain) + else: + rule = Domain(domain) + factory = partial(MatchedSubAppResource, rule, subapp) + return self._add_subapp(factory, subapp) + + def add_routes(self, routes: Iterable[AbstractRouteDef]) -> List[AbstractRoute]: + return self.router.add_routes(routes) + + @property + def on_response_prepare(self) -> _RespPrepareSignal: + return self._on_response_prepare + + @property + def on_startup(self) -> _AppSignal: + return self._on_startup + + @property + def on_shutdown(self) -> _AppSignal: + return self._on_shutdown + + @property + def on_cleanup(self) -> _AppSignal: + return self._on_cleanup + + @property + def cleanup_ctx(self) -> "CleanupContext": + return self._cleanup_ctx + + @property + def router(self) -> UrlDispatcher: + return self._router + + @property + def middlewares(self) -> _Middlewares: + return self._middlewares + + def _make_handler( + self, + *, + loop: Optional[asyncio.AbstractEventLoop] = None, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + **kwargs: Any, + ) -> Server: + + if not issubclass(access_log_class, AbstractAccessLogger): + raise TypeError( + "access_log_class must be subclass of " + "aiohttp.abc.AbstractAccessLogger, got {}".format(access_log_class) + ) + + self._set_loop(loop) + self.freeze() + + kwargs["debug"] = self._debug + kwargs["access_log_class"] = access_log_class + if self._handler_args: + for k, v in self._handler_args.items(): + kwargs[k] = v + + return Server( + self._handle, # type: ignore[arg-type] + request_factory=self._make_request, + loop=self._loop, + **kwargs, + ) + + def make_handler( + self, + *, + loop: Optional[asyncio.AbstractEventLoop] = None, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + **kwargs: Any, + ) -> Server: + + warnings.warn( + "Application.make_handler(...) is deprecated, " "use AppRunner API instead", + DeprecationWarning, + stacklevel=2, + ) + + return self._make_handler( + loop=loop, access_log_class=access_log_class, **kwargs + ) + + async def startup(self) -> None: + """Causes on_startup signal + + Should be called in the event loop along with the request handler. + """ + await self.on_startup.send(self) + + async def shutdown(self) -> None: + """Causes on_shutdown signal + + Should be called before cleanup() + """ + await self.on_shutdown.send(self) + + async def cleanup(self) -> None: + """Causes on_cleanup signal + + Should be called after shutdown() + """ + if self.on_cleanup.frozen: + await self.on_cleanup.send(self) + else: + # If an exception occurs in startup, ensure cleanup contexts are completed. + await self._cleanup_ctx._on_cleanup(self) + + def _make_request( + self, + message: RawRequestMessage, + payload: StreamReader, + protocol: RequestHandler, + writer: AbstractStreamWriter, + task: "asyncio.Task[None]", + _cls: Type[Request] = Request, + ) -> Request: + return _cls( + message, + payload, + protocol, + writer, + task, + self._loop, + client_max_size=self._client_max_size, + ) + + def _prepare_middleware(self) -> Iterator[Tuple[Middleware, bool]]: + for m in reversed(self._middlewares): + if getattr(m, "__middleware_version__", None) == 1: + yield m, True + else: + warnings.warn( + 'old-style middleware "{!r}" deprecated, ' "see #2252".format(m), + DeprecationWarning, + stacklevel=2, + ) + yield m, False + + yield _fix_request_current_app(self), True + + async def _handle(self, request: Request) -> StreamResponse: + loop = asyncio.get_event_loop() + debug = loop.get_debug() + match_info = await self._router.resolve(request) + if debug: # pragma: no cover + if not isinstance(match_info, AbstractMatchInfo): + raise TypeError( + "match_info should be AbstractMatchInfo " + "instance, not {!r}".format(match_info) + ) + match_info.add_app(self) + + match_info.freeze() + + resp = None + request._match_info = match_info + expect = request.headers.get(hdrs.EXPECT) + if expect: + resp = await match_info.expect_handler(request) + await request.writer.drain() + + if resp is None: + handler = match_info.handler + + if self._run_middlewares: + for app in match_info.apps[::-1]: + for m, new_style in app._middlewares_handlers: # type: ignore[union-attr] + if new_style: + handler = update_wrapper( + partial(m, handler=handler), handler # type: ignore[misc] + ) + else: + handler = await m(app, handler) # type: ignore[arg-type,assignment] + + resp = await handler(request) + + return resp + + def __call__(self) -> "Application": + """gunicorn compatibility""" + return self + + def __repr__(self) -> str: + return f"" + + def __bool__(self) -> bool: + return True + + +class CleanupError(RuntimeError): + @property + def exceptions(self) -> List[BaseException]: + return cast(List[BaseException], self.args[1]) + + +if TYPE_CHECKING: + _CleanupContextBase = FrozenList[Callable[[Application], AsyncIterator[None]]] +else: + _CleanupContextBase = FrozenList + + +class CleanupContext(_CleanupContextBase): + def __init__(self) -> None: + super().__init__() + self._exits: List[AsyncIterator[None]] = [] + + async def _on_startup(self, app: Application) -> None: + for cb in self: + it = cb(app).__aiter__() + await it.__anext__() + self._exits.append(it) + + async def _on_cleanup(self, app: Application) -> None: + errors = [] + for it in reversed(self._exits): + try: + await it.__anext__() + except StopAsyncIteration: + pass + except Exception as exc: + errors.append(exc) + else: + errors.append(RuntimeError(f"{it!r} has more than one 'yield'")) + if errors: + if len(errors) == 1: + raise errors[0] + else: + raise CleanupError("Multiple errors on cleanup stage", errors) diff --git a/env/Lib/site-packages/aiohttp/web_exceptions.py b/env/Lib/site-packages/aiohttp/web_exceptions.py new file mode 100644 index 0000000..ee2c1e7 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_exceptions.py @@ -0,0 +1,452 @@ +import warnings +from typing import Any, Dict, Iterable, List, Optional, Set # noqa + +from yarl import URL + +from .typedefs import LooseHeaders, StrOrURL +from .web_response import Response + +__all__ = ( + "HTTPException", + "HTTPError", + "HTTPRedirection", + "HTTPSuccessful", + "HTTPOk", + "HTTPCreated", + "HTTPAccepted", + "HTTPNonAuthoritativeInformation", + "HTTPNoContent", + "HTTPResetContent", + "HTTPPartialContent", + "HTTPMove", + "HTTPMultipleChoices", + "HTTPMovedPermanently", + "HTTPFound", + "HTTPSeeOther", + "HTTPNotModified", + "HTTPUseProxy", + "HTTPTemporaryRedirect", + "HTTPPermanentRedirect", + "HTTPClientError", + "HTTPBadRequest", + "HTTPUnauthorized", + "HTTPPaymentRequired", + "HTTPForbidden", + "HTTPNotFound", + "HTTPMethodNotAllowed", + "HTTPNotAcceptable", + "HTTPProxyAuthenticationRequired", + "HTTPRequestTimeout", + "HTTPConflict", + "HTTPGone", + "HTTPLengthRequired", + "HTTPPreconditionFailed", + "HTTPRequestEntityTooLarge", + "HTTPRequestURITooLong", + "HTTPUnsupportedMediaType", + "HTTPRequestRangeNotSatisfiable", + "HTTPExpectationFailed", + "HTTPMisdirectedRequest", + "HTTPUnprocessableEntity", + "HTTPFailedDependency", + "HTTPUpgradeRequired", + "HTTPPreconditionRequired", + "HTTPTooManyRequests", + "HTTPRequestHeaderFieldsTooLarge", + "HTTPUnavailableForLegalReasons", + "HTTPServerError", + "HTTPInternalServerError", + "HTTPNotImplemented", + "HTTPBadGateway", + "HTTPServiceUnavailable", + "HTTPGatewayTimeout", + "HTTPVersionNotSupported", + "HTTPVariantAlsoNegotiates", + "HTTPInsufficientStorage", + "HTTPNotExtended", + "HTTPNetworkAuthenticationRequired", +) + + +class NotAppKeyWarning(UserWarning): + """Warning when not using AppKey in Application.""" + + +############################################################ +# HTTP Exceptions +############################################################ + + +class HTTPException(Response, Exception): + + # You should set in subclasses: + # status = 200 + + status_code = -1 + empty_body = False + + __http_exception__ = True + + def __init__( + self, + *, + headers: Optional[LooseHeaders] = None, + reason: Optional[str] = None, + body: Any = None, + text: Optional[str] = None, + content_type: Optional[str] = None, + ) -> None: + if body is not None: + warnings.warn( + "body argument is deprecated for http web exceptions", + DeprecationWarning, + ) + Response.__init__( + self, + status=self.status_code, + headers=headers, + reason=reason, + body=body, + text=text, + content_type=content_type, + ) + Exception.__init__(self, self.reason) + if self.body is None and not self.empty_body: + self.text = f"{self.status}: {self.reason}" + + def __bool__(self) -> bool: + return True + + +class HTTPError(HTTPException): + """Base class for exceptions with status codes in the 400s and 500s.""" + + +class HTTPRedirection(HTTPException): + """Base class for exceptions with status codes in the 300s.""" + + +class HTTPSuccessful(HTTPException): + """Base class for exceptions with status codes in the 200s.""" + + +class HTTPOk(HTTPSuccessful): + status_code = 200 + + +class HTTPCreated(HTTPSuccessful): + status_code = 201 + + +class HTTPAccepted(HTTPSuccessful): + status_code = 202 + + +class HTTPNonAuthoritativeInformation(HTTPSuccessful): + status_code = 203 + + +class HTTPNoContent(HTTPSuccessful): + status_code = 204 + empty_body = True + + +class HTTPResetContent(HTTPSuccessful): + status_code = 205 + empty_body = True + + +class HTTPPartialContent(HTTPSuccessful): + status_code = 206 + + +############################################################ +# 3xx redirection +############################################################ + + +class HTTPMove(HTTPRedirection): + def __init__( + self, + location: StrOrURL, + *, + headers: Optional[LooseHeaders] = None, + reason: Optional[str] = None, + body: Any = None, + text: Optional[str] = None, + content_type: Optional[str] = None, + ) -> None: + if not location: + raise ValueError("HTTP redirects need a location to redirect to.") + super().__init__( + headers=headers, + reason=reason, + body=body, + text=text, + content_type=content_type, + ) + self.headers["Location"] = str(URL(location)) + self.location = location + + +class HTTPMultipleChoices(HTTPMove): + status_code = 300 + + +class HTTPMovedPermanently(HTTPMove): + status_code = 301 + + +class HTTPFound(HTTPMove): + status_code = 302 + + +# This one is safe after a POST (the redirected location will be +# retrieved with GET): +class HTTPSeeOther(HTTPMove): + status_code = 303 + + +class HTTPNotModified(HTTPRedirection): + # FIXME: this should include a date or etag header + status_code = 304 + empty_body = True + + +class HTTPUseProxy(HTTPMove): + # Not a move, but looks a little like one + status_code = 305 + + +class HTTPTemporaryRedirect(HTTPMove): + status_code = 307 + + +class HTTPPermanentRedirect(HTTPMove): + status_code = 308 + + +############################################################ +# 4xx client error +############################################################ + + +class HTTPClientError(HTTPError): + pass + + +class HTTPBadRequest(HTTPClientError): + status_code = 400 + + +class HTTPUnauthorized(HTTPClientError): + status_code = 401 + + +class HTTPPaymentRequired(HTTPClientError): + status_code = 402 + + +class HTTPForbidden(HTTPClientError): + status_code = 403 + + +class HTTPNotFound(HTTPClientError): + status_code = 404 + + +class HTTPMethodNotAllowed(HTTPClientError): + status_code = 405 + + def __init__( + self, + method: str, + allowed_methods: Iterable[str], + *, + headers: Optional[LooseHeaders] = None, + reason: Optional[str] = None, + body: Any = None, + text: Optional[str] = None, + content_type: Optional[str] = None, + ) -> None: + allow = ",".join(sorted(allowed_methods)) + super().__init__( + headers=headers, + reason=reason, + body=body, + text=text, + content_type=content_type, + ) + self.headers["Allow"] = allow + self.allowed_methods: Set[str] = set(allowed_methods) + self.method = method.upper() + + +class HTTPNotAcceptable(HTTPClientError): + status_code = 406 + + +class HTTPProxyAuthenticationRequired(HTTPClientError): + status_code = 407 + + +class HTTPRequestTimeout(HTTPClientError): + status_code = 408 + + +class HTTPConflict(HTTPClientError): + status_code = 409 + + +class HTTPGone(HTTPClientError): + status_code = 410 + + +class HTTPLengthRequired(HTTPClientError): + status_code = 411 + + +class HTTPPreconditionFailed(HTTPClientError): + status_code = 412 + + +class HTTPRequestEntityTooLarge(HTTPClientError): + status_code = 413 + + def __init__(self, max_size: float, actual_size: float, **kwargs: Any) -> None: + kwargs.setdefault( + "text", + "Maximum request body size {} exceeded, " + "actual body size {}".format(max_size, actual_size), + ) + super().__init__(**kwargs) + + +class HTTPRequestURITooLong(HTTPClientError): + status_code = 414 + + +class HTTPUnsupportedMediaType(HTTPClientError): + status_code = 415 + + +class HTTPRequestRangeNotSatisfiable(HTTPClientError): + status_code = 416 + + +class HTTPExpectationFailed(HTTPClientError): + status_code = 417 + + +class HTTPMisdirectedRequest(HTTPClientError): + status_code = 421 + + +class HTTPUnprocessableEntity(HTTPClientError): + status_code = 422 + + +class HTTPFailedDependency(HTTPClientError): + status_code = 424 + + +class HTTPUpgradeRequired(HTTPClientError): + status_code = 426 + + +class HTTPPreconditionRequired(HTTPClientError): + status_code = 428 + + +class HTTPTooManyRequests(HTTPClientError): + status_code = 429 + + +class HTTPRequestHeaderFieldsTooLarge(HTTPClientError): + status_code = 431 + + +class HTTPUnavailableForLegalReasons(HTTPClientError): + status_code = 451 + + def __init__( + self, + link: Optional[StrOrURL], + *, + headers: Optional[LooseHeaders] = None, + reason: Optional[str] = None, + body: Any = None, + text: Optional[str] = None, + content_type: Optional[str] = None, + ) -> None: + super().__init__( + headers=headers, + reason=reason, + body=body, + text=text, + content_type=content_type, + ) + self._link = None + if link: + self._link = URL(link) + self.headers["Link"] = f'<{str(self._link)}>; rel="blocked-by"' + + @property + def link(self) -> Optional[URL]: + return self._link + + +############################################################ +# 5xx Server Error +############################################################ +# Response status codes beginning with the digit "5" indicate cases in +# which the server is aware that it has erred or is incapable of +# performing the request. Except when responding to a HEAD request, the +# server SHOULD include an entity containing an explanation of the error +# situation, and whether it is a temporary or permanent condition. User +# agents SHOULD display any included entity to the user. These response +# codes are applicable to any request method. + + +class HTTPServerError(HTTPError): + pass + + +class HTTPInternalServerError(HTTPServerError): + status_code = 500 + + +class HTTPNotImplemented(HTTPServerError): + status_code = 501 + + +class HTTPBadGateway(HTTPServerError): + status_code = 502 + + +class HTTPServiceUnavailable(HTTPServerError): + status_code = 503 + + +class HTTPGatewayTimeout(HTTPServerError): + status_code = 504 + + +class HTTPVersionNotSupported(HTTPServerError): + status_code = 505 + + +class HTTPVariantAlsoNegotiates(HTTPServerError): + status_code = 506 + + +class HTTPInsufficientStorage(HTTPServerError): + status_code = 507 + + +class HTTPNotExtended(HTTPServerError): + status_code = 510 + + +class HTTPNetworkAuthenticationRequired(HTTPServerError): + status_code = 511 diff --git a/env/Lib/site-packages/aiohttp/web_fileresponse.py b/env/Lib/site-packages/aiohttp/web_fileresponse.py new file mode 100644 index 0000000..0c23e37 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_fileresponse.py @@ -0,0 +1,357 @@ +import asyncio +import os +import pathlib +import sys +from contextlib import suppress +from mimetypes import MimeTypes +from stat import S_ISREG +from types import MappingProxyType +from typing import ( # noqa + IO, + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Final, + Iterator, + List, + Optional, + Tuple, + Union, + cast, +) + +from . import hdrs +from .abc import AbstractStreamWriter +from .helpers import ETAG_ANY, ETag, must_be_empty_body +from .typedefs import LooseHeaders, PathLike +from .web_exceptions import ( + HTTPForbidden, + HTTPNotFound, + HTTPNotModified, + HTTPPartialContent, + HTTPPreconditionFailed, + HTTPRequestRangeNotSatisfiable, +) +from .web_response import StreamResponse + +__all__ = ("FileResponse",) + +if TYPE_CHECKING: + from .web_request import BaseRequest + + +_T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]] + + +NOSENDFILE: Final[bool] = bool(os.environ.get("AIOHTTP_NOSENDFILE")) + +CONTENT_TYPES: Final[MimeTypes] = MimeTypes() + +if sys.version_info < (3, 9): + CONTENT_TYPES.encodings_map[".br"] = "br" + +# File extension to IANA encodings map that will be checked in the order defined. +ENCODING_EXTENSIONS = MappingProxyType( + {ext: CONTENT_TYPES.encodings_map[ext] for ext in (".br", ".gz")} +) + +FALLBACK_CONTENT_TYPE = "application/octet-stream" + +# Provide additional MIME type/extension pairs to be recognized. +# https://en.wikipedia.org/wiki/List_of_archive_formats#Compression_only +ADDITIONAL_CONTENT_TYPES = MappingProxyType( + { + "application/gzip": ".gz", + "application/x-brotli": ".br", + "application/x-bzip2": ".bz2", + "application/x-compress": ".Z", + "application/x-xz": ".xz", + } +) + +# Add custom pairs and clear the encodings map so guess_type ignores them. +CONTENT_TYPES.encodings_map.clear() +for content_type, extension in ADDITIONAL_CONTENT_TYPES.items(): + CONTENT_TYPES.add_type(content_type, extension) # type: ignore[attr-defined] + + +class FileResponse(StreamResponse): + """A response object can be used to send files.""" + + def __init__( + self, + path: PathLike, + chunk_size: int = 256 * 1024, + status: int = 200, + reason: Optional[str] = None, + headers: Optional[LooseHeaders] = None, + ) -> None: + super().__init__(status=status, reason=reason, headers=headers) + + self._path = pathlib.Path(path) + self._chunk_size = chunk_size + + async def _sendfile_fallback( + self, writer: AbstractStreamWriter, fobj: IO[Any], offset: int, count: int + ) -> AbstractStreamWriter: + # To keep memory usage low,fobj is transferred in chunks + # controlled by the constructor's chunk_size argument. + + chunk_size = self._chunk_size + loop = asyncio.get_event_loop() + + await loop.run_in_executor(None, fobj.seek, offset) + + chunk = await loop.run_in_executor(None, fobj.read, chunk_size) + while chunk: + await writer.write(chunk) + count = count - chunk_size + if count <= 0: + break + chunk = await loop.run_in_executor(None, fobj.read, min(chunk_size, count)) + + await writer.drain() + return writer + + async def _sendfile( + self, request: "BaseRequest", fobj: IO[Any], offset: int, count: int + ) -> AbstractStreamWriter: + writer = await super().prepare(request) + assert writer is not None + + if NOSENDFILE or self.compression: + return await self._sendfile_fallback(writer, fobj, offset, count) + + loop = request._loop + transport = request.transport + assert transport is not None + + try: + await loop.sendfile(transport, fobj, offset, count) + except NotImplementedError: + return await self._sendfile_fallback(writer, fobj, offset, count) + + await super().write_eof() + return writer + + @staticmethod + def _strong_etag_match(etag_value: str, etags: Tuple[ETag, ...]) -> bool: + if len(etags) == 1 and etags[0].value == ETAG_ANY: + return True + return any(etag.value == etag_value for etag in etags if not etag.is_weak) + + async def _not_modified( + self, request: "BaseRequest", etag_value: str, last_modified: float + ) -> Optional[AbstractStreamWriter]: + self.set_status(HTTPNotModified.status_code) + self._length_check = False + self.etag = etag_value # type: ignore[assignment] + self.last_modified = last_modified # type: ignore[assignment] + # Delete any Content-Length headers provided by user. HTTP 304 + # should always have empty response body + return await super().prepare(request) + + async def _precondition_failed( + self, request: "BaseRequest" + ) -> Optional[AbstractStreamWriter]: + self.set_status(HTTPPreconditionFailed.status_code) + self.content_length = 0 + return await super().prepare(request) + + def _get_file_path_stat_encoding( + self, accept_encoding: str + ) -> Tuple[pathlib.Path, os.stat_result, Optional[str]]: + """Return the file path, stat result, and encoding. + + If an uncompressed file is returned, the encoding is set to + :py:data:`None`. + + This method should be called from a thread executor + since it calls os.stat which may block. + """ + file_path = self._path + for file_extension, file_encoding in ENCODING_EXTENSIONS.items(): + if file_encoding not in accept_encoding: + continue + + compressed_path = file_path.with_suffix(file_path.suffix + file_extension) + with suppress(OSError): + # Do not follow symlinks and ignore any non-regular files. + st = compressed_path.lstat() + if S_ISREG(st.st_mode): + return compressed_path, st, file_encoding + + # Fallback to the uncompressed file + return file_path, file_path.stat(), None + + async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]: + loop = asyncio.get_running_loop() + # Encoding comparisons should be case-insensitive + # https://www.rfc-editor.org/rfc/rfc9110#section-8.4.1 + accept_encoding = request.headers.get(hdrs.ACCEPT_ENCODING, "").lower() + try: + file_path, st, file_encoding = await loop.run_in_executor( + None, self._get_file_path_stat_encoding, accept_encoding + ) + except OSError: + # Most likely to be FileNotFoundError or OSError for circular + # symlinks in python >= 3.13, so respond with 404. + self.set_status(HTTPNotFound.status_code) + return await super().prepare(request) + + # Forbid special files like sockets, pipes, devices, etc. + if not S_ISREG(st.st_mode): + self.set_status(HTTPForbidden.status_code) + return await super().prepare(request) + + etag_value = f"{st.st_mtime_ns:x}-{st.st_size:x}" + last_modified = st.st_mtime + + # https://tools.ietf.org/html/rfc7232#section-6 + ifmatch = request.if_match + if ifmatch is not None and not self._strong_etag_match(etag_value, ifmatch): + return await self._precondition_failed(request) + + unmodsince = request.if_unmodified_since + if ( + unmodsince is not None + and ifmatch is None + and st.st_mtime > unmodsince.timestamp() + ): + return await self._precondition_failed(request) + + ifnonematch = request.if_none_match + if ifnonematch is not None and self._strong_etag_match(etag_value, ifnonematch): + return await self._not_modified(request, etag_value, last_modified) + + modsince = request.if_modified_since + if ( + modsince is not None + and ifnonematch is None + and st.st_mtime <= modsince.timestamp() + ): + return await self._not_modified(request, etag_value, last_modified) + + status = self._status + file_size = st.st_size + count = file_size + + start = None + + ifrange = request.if_range + if ifrange is None or st.st_mtime <= ifrange.timestamp(): + # If-Range header check: + # condition = cached date >= last modification date + # return 206 if True else 200. + # if False: + # Range header would not be processed, return 200 + # if True but Range header missing + # return 200 + try: + rng = request.http_range + start = rng.start + end = rng.stop + except ValueError: + # https://tools.ietf.org/html/rfc7233: + # A server generating a 416 (Range Not Satisfiable) response to + # a byte-range request SHOULD send a Content-Range header field + # with an unsatisfied-range value. + # The complete-length in a 416 response indicates the current + # length of the selected representation. + # + # Will do the same below. Many servers ignore this and do not + # send a Content-Range header with HTTP 416 + self.headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" + self.set_status(HTTPRequestRangeNotSatisfiable.status_code) + return await super().prepare(request) + + # If a range request has been made, convert start, end slice + # notation into file pointer offset and count + if start is not None or end is not None: + if start < 0 and end is None: # return tail of file + start += file_size + if start < 0: + # if Range:bytes=-1000 in request header but file size + # is only 200, there would be trouble without this + start = 0 + count = file_size - start + else: + # rfc7233:If the last-byte-pos value is + # absent, or if the value is greater than or equal to + # the current length of the representation data, + # the byte range is interpreted as the remainder + # of the representation (i.e., the server replaces the + # value of last-byte-pos with a value that is one less than + # the current length of the selected representation). + count = ( + min(end if end is not None else file_size, file_size) - start + ) + + if start >= file_size: + # HTTP 416 should be returned in this case. + # + # According to https://tools.ietf.org/html/rfc7233: + # If a valid byte-range-set includes at least one + # byte-range-spec with a first-byte-pos that is less than + # the current length of the representation, or at least one + # suffix-byte-range-spec with a non-zero suffix-length, + # then the byte-range-set is satisfiable. Otherwise, the + # byte-range-set is unsatisfiable. + self.headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" + self.set_status(HTTPRequestRangeNotSatisfiable.status_code) + return await super().prepare(request) + + status = HTTPPartialContent.status_code + # Even though you are sending the whole file, you should still + # return a HTTP 206 for a Range request. + self.set_status(status) + + # If the Content-Type header is not already set, guess it based on the + # extension of the request path. The encoding returned by guess_type + # can be ignored since the map was cleared above. + if hdrs.CONTENT_TYPE not in self.headers: + self.content_type = ( + CONTENT_TYPES.guess_type(self._path)[0] or FALLBACK_CONTENT_TYPE + ) + + if file_encoding: + self.headers[hdrs.CONTENT_ENCODING] = file_encoding + self.headers[hdrs.VARY] = hdrs.ACCEPT_ENCODING + # Disable compression if we are already sending + # a compressed file since we don't want to double + # compress. + self._compression = False + + self.etag = etag_value # type: ignore[assignment] + self.last_modified = st.st_mtime # type: ignore[assignment] + self.content_length = count + + self.headers[hdrs.ACCEPT_RANGES] = "bytes" + + real_start = cast(int, start) + + if status == HTTPPartialContent.status_code: + self.headers[hdrs.CONTENT_RANGE] = "bytes {}-{}/{}".format( + real_start, real_start + count - 1, file_size + ) + + # If we are sending 0 bytes calling sendfile() will throw a ValueError + if count == 0 or must_be_empty_body(request.method, self.status): + return await super().prepare(request) + + try: + fobj = await loop.run_in_executor(None, file_path.open, "rb") + except PermissionError: + self.set_status(HTTPForbidden.status_code) + return await super().prepare(request) + + if start: # be aware that start could be None or int=0 here. + offset = start + else: + offset = 0 + + try: + return await self._sendfile(request, fobj, offset, count) + finally: + await asyncio.shield(loop.run_in_executor(None, fobj.close)) diff --git a/env/Lib/site-packages/aiohttp/web_log.py b/env/Lib/site-packages/aiohttp/web_log.py new file mode 100644 index 0000000..633e9e3 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_log.py @@ -0,0 +1,213 @@ +import datetime +import functools +import logging +import os +import re +import time as time_mod +from collections import namedtuple +from typing import Any, Callable, Dict, Iterable, List, Tuple # noqa + +from .abc import AbstractAccessLogger +from .web_request import BaseRequest +from .web_response import StreamResponse + +KeyMethod = namedtuple("KeyMethod", "key method") + + +class AccessLogger(AbstractAccessLogger): + """Helper object to log access. + + Usage: + log = logging.getLogger("spam") + log_format = "%a %{User-Agent}i" + access_logger = AccessLogger(log, log_format) + access_logger.log(request, response, time) + + Format: + %% The percent sign + %a Remote IP-address (IP-address of proxy if using reverse proxy) + %t Time when the request was started to process + %P The process ID of the child that serviced the request + %r First line of request + %s Response status code + %b Size of response in bytes, including HTTP headers + %T Time taken to serve the request, in seconds + %Tf Time taken to serve the request, in seconds with floating fraction + in .06f format + %D Time taken to serve the request, in microseconds + %{FOO}i request.headers['FOO'] + %{FOO}o response.headers['FOO'] + %{FOO}e os.environ['FOO'] + + """ + + LOG_FORMAT_MAP = { + "a": "remote_address", + "t": "request_start_time", + "P": "process_id", + "r": "first_request_line", + "s": "response_status", + "b": "response_size", + "T": "request_time", + "Tf": "request_time_frac", + "D": "request_time_micro", + "i": "request_header", + "o": "response_header", + } + + LOG_FORMAT = '%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"' + FORMAT_RE = re.compile(r"%(\{([A-Za-z0-9\-_]+)\}([ioe])|[atPrsbOD]|Tf?)") + CLEANUP_RE = re.compile(r"(%[^s])") + _FORMAT_CACHE: Dict[str, Tuple[str, List[KeyMethod]]] = {} + + def __init__(self, logger: logging.Logger, log_format: str = LOG_FORMAT) -> None: + """Initialise the logger. + + logger is a logger object to be used for logging. + log_format is a string with apache compatible log format description. + + """ + super().__init__(logger, log_format=log_format) + + _compiled_format = AccessLogger._FORMAT_CACHE.get(log_format) + if not _compiled_format: + _compiled_format = self.compile_format(log_format) + AccessLogger._FORMAT_CACHE[log_format] = _compiled_format + + self._log_format, self._methods = _compiled_format + + def compile_format(self, log_format: str) -> Tuple[str, List[KeyMethod]]: + """Translate log_format into form usable by modulo formatting + + All known atoms will be replaced with %s + Also methods for formatting of those atoms will be added to + _methods in appropriate order + + For example we have log_format = "%a %t" + This format will be translated to "%s %s" + Also contents of _methods will be + [self._format_a, self._format_t] + These method will be called and results will be passed + to translated string format. + + Each _format_* method receive 'args' which is list of arguments + given to self.log + + Exceptions are _format_e, _format_i and _format_o methods which + also receive key name (by functools.partial) + + """ + # list of (key, method) tuples, we don't use an OrderedDict as users + # can repeat the same key more than once + methods = list() + + for atom in self.FORMAT_RE.findall(log_format): + if atom[1] == "": + format_key1 = self.LOG_FORMAT_MAP[atom[0]] + m = getattr(AccessLogger, "_format_%s" % atom[0]) + key_method = KeyMethod(format_key1, m) + else: + format_key2 = (self.LOG_FORMAT_MAP[atom[2]], atom[1]) + m = getattr(AccessLogger, "_format_%s" % atom[2]) + key_method = KeyMethod(format_key2, functools.partial(m, atom[1])) + + methods.append(key_method) + + log_format = self.FORMAT_RE.sub(r"%s", log_format) + log_format = self.CLEANUP_RE.sub(r"%\1", log_format) + return log_format, methods + + @staticmethod + def _format_i( + key: str, request: BaseRequest, response: StreamResponse, time: float + ) -> str: + if request is None: + return "(no headers)" + + # suboptimal, make istr(key) once + return request.headers.get(key, "-") + + @staticmethod + def _format_o( + key: str, request: BaseRequest, response: StreamResponse, time: float + ) -> str: + # suboptimal, make istr(key) once + return response.headers.get(key, "-") + + @staticmethod + def _format_a(request: BaseRequest, response: StreamResponse, time: float) -> str: + if request is None: + return "-" + ip = request.remote + return ip if ip is not None else "-" + + @staticmethod + def _format_t(request: BaseRequest, response: StreamResponse, time: float) -> str: + tz = datetime.timezone(datetime.timedelta(seconds=-time_mod.timezone)) + now = datetime.datetime.now(tz) + start_time = now - datetime.timedelta(seconds=time) + return start_time.strftime("[%d/%b/%Y:%H:%M:%S %z]") + + @staticmethod + def _format_P(request: BaseRequest, response: StreamResponse, time: float) -> str: + return "<%s>" % os.getpid() + + @staticmethod + def _format_r(request: BaseRequest, response: StreamResponse, time: float) -> str: + if request is None: + return "-" + return "{} {} HTTP/{}.{}".format( + request.method, + request.path_qs, + request.version.major, + request.version.minor, + ) + + @staticmethod + def _format_s(request: BaseRequest, response: StreamResponse, time: float) -> int: + return response.status + + @staticmethod + def _format_b(request: BaseRequest, response: StreamResponse, time: float) -> int: + return response.body_length + + @staticmethod + def _format_T(request: BaseRequest, response: StreamResponse, time: float) -> str: + return str(round(time)) + + @staticmethod + def _format_Tf(request: BaseRequest, response: StreamResponse, time: float) -> str: + return "%06f" % time + + @staticmethod + def _format_D(request: BaseRequest, response: StreamResponse, time: float) -> str: + return str(round(time * 1000000)) + + def _format_line( + self, request: BaseRequest, response: StreamResponse, time: float + ) -> Iterable[Tuple[str, Callable[[BaseRequest, StreamResponse, float], str]]]: + return [(key, method(request, response, time)) for key, method in self._methods] + + def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None: + if not self.logger.isEnabledFor(logging.INFO): + # Avoid formatting the log line if it will not be emitted. + return + try: + fmt_info = self._format_line(request, response, time) + + values = list() + extra = dict() + for key, value in fmt_info: + values.append(value) + + if key.__class__ is str: + extra[key] = value + else: + k1, k2 = key # type: ignore[misc] + dct = extra.get(k1, {}) # type: ignore[var-annotated,has-type] + dct[k2] = value # type: ignore[index,has-type] + extra[k1] = dct # type: ignore[has-type,assignment] + + self.logger.info(self._log_format % tuple(values), extra=extra) + except Exception: + self.logger.exception("Error in logging") diff --git a/env/Lib/site-packages/aiohttp/web_middlewares.py b/env/Lib/site-packages/aiohttp/web_middlewares.py new file mode 100644 index 0000000..5da1533 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_middlewares.py @@ -0,0 +1,116 @@ +import re +from typing import TYPE_CHECKING, Tuple, Type, TypeVar + +from .typedefs import Handler, Middleware +from .web_exceptions import HTTPMove, HTTPPermanentRedirect +from .web_request import Request +from .web_response import StreamResponse +from .web_urldispatcher import SystemRoute + +__all__ = ( + "middleware", + "normalize_path_middleware", +) + +if TYPE_CHECKING: + from .web_app import Application + +_Func = TypeVar("_Func") + + +async def _check_request_resolves(request: Request, path: str) -> Tuple[bool, Request]: + alt_request = request.clone(rel_url=path) + + match_info = await request.app.router.resolve(alt_request) + alt_request._match_info = match_info + + if match_info.http_exception is None: + return True, alt_request + + return False, request + + +def middleware(f: _Func) -> _Func: + f.__middleware_version__ = 1 # type: ignore[attr-defined] + return f + + +def normalize_path_middleware( + *, + append_slash: bool = True, + remove_slash: bool = False, + merge_slashes: bool = True, + redirect_class: Type[HTTPMove] = HTTPPermanentRedirect, +) -> Middleware: + """Factory for producing a middleware that normalizes the path of a request. + + Normalizing means: + - Add or remove a trailing slash to the path. + - Double slashes are replaced by one. + + The middleware returns as soon as it finds a path that resolves + correctly. The order if both merge and append/remove are enabled is + 1) merge slashes + 2) append/remove slash + 3) both merge slashes and append/remove slash. + If the path resolves with at least one of those conditions, it will + redirect to the new path. + + Only one of `append_slash` and `remove_slash` can be enabled. If both + are `True` the factory will raise an assertion error + + If `append_slash` is `True` the middleware will append a slash when + needed. If a resource is defined with trailing slash and the request + comes without it, it will append it automatically. + + If `remove_slash` is `True`, `append_slash` must be `False`. When enabled + the middleware will remove trailing slashes and redirect if the resource + is defined + + If merge_slashes is True, merge multiple consecutive slashes in the + path into one. + """ + correct_configuration = not (append_slash and remove_slash) + assert correct_configuration, "Cannot both remove and append slash" + + @middleware + async def impl(request: Request, handler: Handler) -> StreamResponse: + if isinstance(request.match_info.route, SystemRoute): + paths_to_check = [] + if "?" in request.raw_path: + path, query = request.raw_path.split("?", 1) + query = "?" + query + else: + query = "" + path = request.raw_path + + if merge_slashes: + paths_to_check.append(re.sub("//+", "/", path)) + if append_slash and not request.path.endswith("/"): + paths_to_check.append(path + "/") + if remove_slash and request.path.endswith("/"): + paths_to_check.append(path[:-1]) + if merge_slashes and append_slash: + paths_to_check.append(re.sub("//+", "/", path + "/")) + if merge_slashes and remove_slash: + merged_slashes = re.sub("//+", "/", path) + paths_to_check.append(merged_slashes[:-1]) + + for path in paths_to_check: + path = re.sub("^//+", "/", path) # SECURITY: GHSA-v6wp-4m6f-gcjg + resolves, request = await _check_request_resolves(request, path) + if resolves: + raise redirect_class(request.raw_path + query) + + return await handler(request) + + return impl + + +def _fix_request_current_app(app: "Application") -> Middleware: + @middleware + async def impl(request: Request, handler: Handler) -> StreamResponse: + with request.match_info.set_current_app(app): + return await handler(request) + + return impl diff --git a/env/Lib/site-packages/aiohttp/web_protocol.py b/env/Lib/site-packages/aiohttp/web_protocol.py new file mode 100644 index 0000000..39e1c8b --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_protocol.py @@ -0,0 +1,714 @@ +import asyncio +import asyncio.streams +import sys +import traceback +import warnings +from collections import deque +from contextlib import suppress +from html import escape as html_escape +from http import HTTPStatus +from logging import Logger +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Deque, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import attr +import yarl + +from .abc import AbstractAccessLogger, AbstractStreamWriter +from .base_protocol import BaseProtocol +from .helpers import ceil_timeout, set_exception +from .http import ( + HttpProcessingError, + HttpRequestParser, + HttpVersion10, + RawRequestMessage, + StreamWriter, +) +from .log import access_logger, server_logger +from .streams import EMPTY_PAYLOAD, StreamReader +from .tcp_helpers import tcp_keepalive +from .web_exceptions import HTTPException +from .web_log import AccessLogger +from .web_request import BaseRequest +from .web_response import Response, StreamResponse + +__all__ = ("RequestHandler", "RequestPayloadError", "PayloadAccessError") + +if TYPE_CHECKING: + from .web_server import Server + + +_RequestFactory = Callable[ + [ + RawRequestMessage, + StreamReader, + "RequestHandler", + AbstractStreamWriter, + "asyncio.Task[None]", + ], + BaseRequest, +] + +_RequestHandler = Callable[[BaseRequest], Awaitable[StreamResponse]] + +ERROR = RawRequestMessage( + "UNKNOWN", + "/", + HttpVersion10, + {}, # type: ignore[arg-type] + {}, # type: ignore[arg-type] + True, + None, + False, + False, + yarl.URL("/"), +) + + +class RequestPayloadError(Exception): + """Payload parsing error.""" + + +class PayloadAccessError(Exception): + """Payload was accessed after response was sent.""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class _ErrInfo: + status: int + exc: BaseException + message: str + + +_MsgType = Tuple[Union[RawRequestMessage, _ErrInfo], StreamReader] + + +class RequestHandler(BaseProtocol): + """HTTP protocol implementation. + + RequestHandler handles incoming HTTP request. It reads request line, + request headers and request payload and calls handle_request() method. + By default it always returns with 404 response. + + RequestHandler handles errors in incoming request, like bad + status line, bad headers or incomplete payload. If any error occurs, + connection gets closed. + + keepalive_timeout -- number of seconds before closing + keep-alive connection + + tcp_keepalive -- TCP keep-alive is on, default is on + + debug -- enable debug mode + + logger -- custom logger object + + access_log_class -- custom class for access_logger + + access_log -- custom logging object + + access_log_format -- access log format string + + loop -- Optional event loop + + max_line_size -- Optional maximum header line size + + max_field_size -- Optional maximum header field size + + max_headers -- Optional maximum header size + + timeout_ceil_threshold -- Optional value to specify + threshold to ceil() timeout + values + + """ + + __slots__ = ( + "_request_count", + "_keepalive", + "_manager", + "_request_handler", + "_request_factory", + "_tcp_keepalive", + "_next_keepalive_close_time", + "_keepalive_handle", + "_keepalive_timeout", + "_lingering_time", + "_messages", + "_message_tail", + "_handler_waiter", + "_waiter", + "_task_handler", + "_upgrade", + "_payload_parser", + "_request_parser", + "_reading_paused", + "logger", + "debug", + "access_log", + "access_logger", + "_close", + "_force_close", + "_current_request", + "_timeout_ceil_threshold", + ) + + def __init__( + self, + manager: "Server", + *, + loop: asyncio.AbstractEventLoop, + keepalive_timeout: float = 75.0, # NGINX default is 75 secs + tcp_keepalive: bool = True, + logger: Logger = server_logger, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + access_log: Logger = access_logger, + access_log_format: str = AccessLogger.LOG_FORMAT, + debug: bool = False, + max_line_size: int = 8190, + max_headers: int = 32768, + max_field_size: int = 8190, + lingering_time: float = 10.0, + read_bufsize: int = 2**16, + auto_decompress: bool = True, + timeout_ceil_threshold: float = 5, + ): + super().__init__(loop) + + self._request_count = 0 + self._keepalive = False + self._current_request: Optional[BaseRequest] = None + self._manager: Optional[Server] = manager + self._request_handler: Optional[_RequestHandler] = manager.request_handler + self._request_factory: Optional[_RequestFactory] = manager.request_factory + + self._tcp_keepalive = tcp_keepalive + # placeholder to be replaced on keepalive timeout setup + self._next_keepalive_close_time = 0.0 + self._keepalive_handle: Optional[asyncio.Handle] = None + self._keepalive_timeout = keepalive_timeout + self._lingering_time = float(lingering_time) + + self._messages: Deque[_MsgType] = deque() + self._message_tail = b"" + + self._waiter: Optional[asyncio.Future[None]] = None + self._handler_waiter: Optional[asyncio.Future[None]] = None + self._task_handler: Optional[asyncio.Task[None]] = None + + self._upgrade = False + self._payload_parser: Any = None + self._request_parser: Optional[HttpRequestParser] = HttpRequestParser( + self, + loop, + read_bufsize, + max_line_size=max_line_size, + max_field_size=max_field_size, + max_headers=max_headers, + payload_exception=RequestPayloadError, + auto_decompress=auto_decompress, + ) + + self._timeout_ceil_threshold: float = 5 + try: + self._timeout_ceil_threshold = float(timeout_ceil_threshold) + except (TypeError, ValueError): + pass + + self.logger = logger + self.debug = debug + self.access_log = access_log + if access_log: + self.access_logger: Optional[AbstractAccessLogger] = access_log_class( + access_log, access_log_format + ) + else: + self.access_logger = None + + self._close = False + self._force_close = False + + def __repr__(self) -> str: + return "<{} {}>".format( + self.__class__.__name__, + "connected" if self.transport is not None else "disconnected", + ) + + @property + def keepalive_timeout(self) -> float: + return self._keepalive_timeout + + async def shutdown(self, timeout: Optional[float] = 15.0) -> None: + """Do worker process exit preparations. + + We need to clean up everything and stop accepting requests. + It is especially important for keep-alive connections. + """ + self._force_close = True + + if self._keepalive_handle is not None: + self._keepalive_handle.cancel() + + if self._waiter: + self._waiter.cancel() + + # Wait for graceful handler completion + if self._handler_waiter is not None: + with suppress(asyncio.CancelledError, asyncio.TimeoutError): + async with ceil_timeout(timeout): + await self._handler_waiter + # Then cancel handler and wait + with suppress(asyncio.CancelledError, asyncio.TimeoutError): + async with ceil_timeout(timeout): + if self._current_request is not None: + self._current_request._cancel(asyncio.CancelledError()) + + if self._task_handler is not None and not self._task_handler.done(): + await self._task_handler + + # force-close non-idle handler + if self._task_handler is not None: + self._task_handler.cancel() + + if self.transport is not None: + self.transport.close() + self.transport = None + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + super().connection_made(transport) + + real_transport = cast(asyncio.Transport, transport) + if self._tcp_keepalive: + tcp_keepalive(real_transport) + + assert self._manager is not None + self._manager.connection_made(self, real_transport) + + loop = self._loop + if sys.version_info >= (3, 12): + task = asyncio.Task(self.start(), loop=loop, eager_start=True) + else: + task = loop.create_task(self.start()) + self._task_handler = task + + def connection_lost(self, exc: Optional[BaseException]) -> None: + if self._manager is None: + return + self._manager.connection_lost(self, exc) + + super().connection_lost(exc) + + # Grab value before setting _manager to None. + handler_cancellation = self._manager.handler_cancellation + + self._manager = None + self._force_close = True + self._request_factory = None + self._request_handler = None + self._request_parser = None + + if self._keepalive_handle is not None: + self._keepalive_handle.cancel() + + if self._current_request is not None: + if exc is None: + exc = ConnectionResetError("Connection lost") + self._current_request._cancel(exc) + + if self._waiter is not None: + self._waiter.cancel() + + if handler_cancellation and self._task_handler is not None: + self._task_handler.cancel() + + self._task_handler = None + + if self._payload_parser is not None: + self._payload_parser.feed_eof() + self._payload_parser = None + + def set_parser(self, parser: Any) -> None: + # Actual type is WebReader + assert self._payload_parser is None + + self._payload_parser = parser + + if self._message_tail: + self._payload_parser.feed_data(self._message_tail) + self._message_tail = b"" + + def eof_received(self) -> None: + pass + + def data_received(self, data: bytes) -> None: + if self._force_close or self._close: + return + # parse http messages + messages: Sequence[_MsgType] + if self._payload_parser is None and not self._upgrade: + assert self._request_parser is not None + try: + messages, upgraded, tail = self._request_parser.feed_data(data) + except HttpProcessingError as exc: + messages = [ + (_ErrInfo(status=400, exc=exc, message=exc.message), EMPTY_PAYLOAD) + ] + upgraded = False + tail = b"" + + for msg, payload in messages or (): + self._request_count += 1 + self._messages.append((msg, payload)) + + waiter = self._waiter + if messages and waiter is not None and not waiter.done(): + # don't set result twice + waiter.set_result(None) + + self._upgrade = upgraded + if upgraded and tail: + self._message_tail = tail + + # no parser, just store + elif self._payload_parser is None and self._upgrade and data: + self._message_tail += data + + # feed payload + elif data: + eof, tail = self._payload_parser.feed_data(data) + if eof: + self.close() + + def keep_alive(self, val: bool) -> None: + """Set keep-alive connection mode. + + :param bool val: new state. + """ + self._keepalive = val + if self._keepalive_handle: + self._keepalive_handle.cancel() + self._keepalive_handle = None + + def close(self) -> None: + """Close connection. + + Stop accepting new pipelining messages and close + connection when handlers done processing messages. + """ + self._close = True + if self._waiter: + self._waiter.cancel() + + def force_close(self) -> None: + """Forcefully close connection.""" + self._force_close = True + if self._waiter: + self._waiter.cancel() + if self.transport is not None: + self.transport.close() + self.transport = None + + def log_access( + self, request: BaseRequest, response: StreamResponse, time: float + ) -> None: + if self.access_logger is not None: + self.access_logger.log(request, response, self._loop.time() - time) + + def log_debug(self, *args: Any, **kw: Any) -> None: + if self.debug: + self.logger.debug(*args, **kw) + + def log_exception(self, *args: Any, **kw: Any) -> None: + self.logger.exception(*args, **kw) + + def _process_keepalive(self) -> None: + self._keepalive_handle = None + if self._force_close or not self._keepalive: + return + + loop = self._loop + now = loop.time() + close_time = self._next_keepalive_close_time + if now <= close_time: + # Keep alive close check fired too early, reschedule + self._keepalive_handle = loop.call_at(close_time, self._process_keepalive) + return + + # handler in idle state + if self._waiter: + self.force_close() + + async def _handle_request( + self, + request: BaseRequest, + start_time: float, + request_handler: Callable[[BaseRequest], Awaitable[StreamResponse]], + ) -> Tuple[StreamResponse, bool]: + self._handler_waiter = self._loop.create_future() + try: + try: + self._current_request = request + resp = await request_handler(request) + finally: + self._current_request = None + except HTTPException as exc: + resp = exc + reset = await self.finish_response(request, resp, start_time) + except asyncio.CancelledError: + raise + except asyncio.TimeoutError as exc: + self.log_debug("Request handler timed out.", exc_info=exc) + resp = self.handle_error(request, 504) + reset = await self.finish_response(request, resp, start_time) + except Exception as exc: + resp = self.handle_error(request, 500, exc) + reset = await self.finish_response(request, resp, start_time) + else: + # Deprecation warning (See #2415) + if getattr(resp, "__http_exception__", False): + warnings.warn( + "returning HTTPException object is deprecated " + "(#2415) and will be removed, " + "please raise the exception instead", + DeprecationWarning, + ) + + reset = await self.finish_response(request, resp, start_time) + finally: + self._handler_waiter.set_result(None) + + return resp, reset + + async def start(self) -> None: + """Process incoming request. + + It reads request line, request headers and request payload, then + calls handle_request() method. Subclass has to override + handle_request(). start() handles various exceptions in request + or response handling. Connection is being closed always unless + keep_alive(True) specified. + """ + loop = self._loop + handler = asyncio.current_task(loop) + assert handler is not None + manager = self._manager + assert manager is not None + keepalive_timeout = self._keepalive_timeout + resp = None + assert self._request_factory is not None + assert self._request_handler is not None + + while not self._force_close: + if not self._messages: + try: + # wait for next request + self._waiter = loop.create_future() + await self._waiter + except asyncio.CancelledError: + break + finally: + self._waiter = None + + message, payload = self._messages.popleft() + + start = loop.time() + + manager.requests_count += 1 + writer = StreamWriter(self, loop) + if isinstance(message, _ErrInfo): + # make request_factory work + request_handler = self._make_error_handler(message) + message = ERROR + else: + request_handler = self._request_handler + + request = self._request_factory(message, payload, self, writer, handler) + try: + # a new task is used for copy context vars (#3406) + coro = self._handle_request(request, start, request_handler) + if sys.version_info >= (3, 12): + task = asyncio.Task(coro, loop=loop, eager_start=True) + else: + task = loop.create_task(coro) + try: + resp, reset = await task + except (asyncio.CancelledError, ConnectionError): + self.log_debug("Ignored premature client disconnection") + break + + # Drop the processed task from asyncio.Task.all_tasks() early + del task + if reset: + self.log_debug("Ignored premature client disconnection 2") + break + + # notify server about keep-alive + self._keepalive = bool(resp.keep_alive) + + # check payload + if not payload.is_eof(): + lingering_time = self._lingering_time + if not self._force_close and lingering_time: + self.log_debug( + "Start lingering close timer for %s sec.", lingering_time + ) + + now = loop.time() + end_t = now + lingering_time + + with suppress(asyncio.TimeoutError, asyncio.CancelledError): + while not payload.is_eof() and now < end_t: + async with ceil_timeout(end_t - now): + # read and ignore + await payload.readany() + now = loop.time() + + # if payload still uncompleted + if not payload.is_eof() and not self._force_close: + self.log_debug("Uncompleted request.") + self.close() + + set_exception(payload, PayloadAccessError()) + + except asyncio.CancelledError: + self.log_debug("Ignored premature client disconnection ") + break + except RuntimeError as exc: + if self.debug: + self.log_exception("Unhandled runtime exception", exc_info=exc) + self.force_close() + except Exception as exc: + self.log_exception("Unhandled exception", exc_info=exc) + self.force_close() + finally: + if self.transport is None and resp is not None: + self.log_debug("Ignored premature client disconnection.") + elif not self._force_close: + if self._keepalive and not self._close: + # start keep-alive timer + if keepalive_timeout is not None: + now = loop.time() + close_time = now + keepalive_timeout + self._next_keepalive_close_time = close_time + if self._keepalive_handle is None: + self._keepalive_handle = loop.call_at( + close_time, self._process_keepalive + ) + else: + break + + # remove handler, close transport if no handlers left + if not self._force_close: + self._task_handler = None + if self.transport is not None: + self.transport.close() + + async def finish_response( + self, request: BaseRequest, resp: StreamResponse, start_time: float + ) -> bool: + """Prepare the response and write_eof, then log access. + + This has to + be called within the context of any exception so the access logger + can get exception information. Returns True if the client disconnects + prematurely. + """ + request._finish() + if self._request_parser is not None: + self._request_parser.set_upgraded(False) + self._upgrade = False + if self._message_tail: + self._request_parser.feed_data(self._message_tail) + self._message_tail = b"" + try: + prepare_meth = resp.prepare + except AttributeError: + if resp is None: + raise RuntimeError("Missing return " "statement on request handler") + else: + raise RuntimeError( + "Web-handler should return " + "a response instance, " + "got {!r}".format(resp) + ) + try: + await prepare_meth(request) + await resp.write_eof() + except ConnectionError: + self.log_access(request, resp, start_time) + return True + else: + self.log_access(request, resp, start_time) + return False + + def handle_error( + self, + request: BaseRequest, + status: int = 500, + exc: Optional[BaseException] = None, + message: Optional[str] = None, + ) -> StreamResponse: + """Handle errors. + + Returns HTTP response with specific status code. Logs additional + information. It always closes current connection. + """ + self.log_exception("Error handling request", exc_info=exc) + + # some data already got sent, connection is broken + if request.writer.output_size > 0: + raise ConnectionError( + "Response is sent already, cannot send another response " + "with the error message" + ) + + ct = "text/plain" + if status == HTTPStatus.INTERNAL_SERVER_ERROR: + title = "{0.value} {0.phrase}".format(HTTPStatus.INTERNAL_SERVER_ERROR) + msg = HTTPStatus.INTERNAL_SERVER_ERROR.description + tb = None + if self.debug: + with suppress(Exception): + tb = traceback.format_exc() + + if "text/html" in request.headers.get("Accept", ""): + if tb: + tb = html_escape(tb) + msg = f"

Traceback:

\n
{tb}
" + message = ( + "" + "{title}" + "\n

{title}

" + "\n{msg}\n\n" + ).format(title=title, msg=msg) + ct = "text/html" + else: + if tb: + msg = tb + message = title + "\n\n" + msg + + resp = Response(status=status, text=message, content_type=ct) + resp.force_close() + + return resp + + def _make_error_handler( + self, err_info: _ErrInfo + ) -> Callable[[BaseRequest], Awaitable[StreamResponse]]: + async def handler(request: BaseRequest) -> StreamResponse: + return self.handle_error( + request, err_info.status, err_info.exc, err_info.message + ) + + return handler diff --git a/env/Lib/site-packages/aiohttp/web_request.py b/env/Lib/site-packages/aiohttp/web_request.py new file mode 100644 index 0000000..a485f0d --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_request.py @@ -0,0 +1,914 @@ +import asyncio +import datetime +import io +import re +import socket +import string +import tempfile +import types +import warnings +from http.cookies import SimpleCookie +from types import MappingProxyType +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Final, + Iterator, + Mapping, + MutableMapping, + Optional, + Pattern, + Tuple, + Union, + cast, +) +from urllib.parse import parse_qsl + +import attr +from multidict import ( + CIMultiDict, + CIMultiDictProxy, + MultiDict, + MultiDictProxy, + MultiMapping, +) +from yarl import URL + +from . import hdrs +from .abc import AbstractStreamWriter +from .helpers import ( + _SENTINEL, + DEBUG, + ETAG_ANY, + LIST_QUOTED_ETAG_RE, + ChainMapProxy, + ETag, + HeadersMixin, + parse_http_date, + reify, + sentinel, + set_exception, +) +from .http_parser import RawRequestMessage +from .http_writer import HttpVersion +from .multipart import BodyPartReader, MultipartReader +from .streams import EmptyStreamReader, StreamReader +from .typedefs import ( + DEFAULT_JSON_DECODER, + JSONDecoder, + LooseHeaders, + RawHeaders, + StrOrURL, +) +from .web_exceptions import HTTPRequestEntityTooLarge +from .web_response import StreamResponse + +__all__ = ("BaseRequest", "FileField", "Request") + + +if TYPE_CHECKING: + from .web_app import Application + from .web_protocol import RequestHandler + from .web_urldispatcher import UrlMappingMatchInfo + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class FileField: + name: str + filename: str + file: io.BufferedReader + content_type: str + headers: "CIMultiDictProxy[str]" + + +_TCHAR: Final[str] = string.digits + string.ascii_letters + r"!#$%&'*+.^_`|~-" +# '-' at the end to prevent interpretation as range in a char class + +_TOKEN: Final[str] = rf"[{_TCHAR}]+" + +_QDTEXT: Final[str] = r"[{}]".format( + r"".join(chr(c) for c in (0x09, 0x20, 0x21) + tuple(range(0x23, 0x7F))) +) +# qdtext includes 0x5C to escape 0x5D ('\]') +# qdtext excludes obs-text (because obsoleted, and encoding not specified) + +_QUOTED_PAIR: Final[str] = r"\\[\t !-~]" + +_QUOTED_STRING: Final[str] = r'"(?:{quoted_pair}|{qdtext})*"'.format( + qdtext=_QDTEXT, quoted_pair=_QUOTED_PAIR +) + +_FORWARDED_PAIR: Final[str] = ( + r"({token})=({token}|{quoted_string})(:\d{{1,4}})?".format( + token=_TOKEN, quoted_string=_QUOTED_STRING + ) +) + +_QUOTED_PAIR_REPLACE_RE: Final[Pattern[str]] = re.compile(r"\\([\t !-~])") +# same pattern as _QUOTED_PAIR but contains a capture group + +_FORWARDED_PAIR_RE: Final[Pattern[str]] = re.compile(_FORWARDED_PAIR) + +############################################################ +# HTTP Request +############################################################ + + +class BaseRequest(MutableMapping[str, Any], HeadersMixin): + + POST_METHODS = { + hdrs.METH_PATCH, + hdrs.METH_POST, + hdrs.METH_PUT, + hdrs.METH_TRACE, + hdrs.METH_DELETE, + } + + ATTRS = HeadersMixin.ATTRS | frozenset( + [ + "_message", + "_protocol", + "_payload_writer", + "_payload", + "_headers", + "_method", + "_version", + "_rel_url", + "_post", + "_read_bytes", + "_state", + "_cache", + "_task", + "_client_max_size", + "_loop", + "_transport_sslcontext", + "_transport_peername", + ] + ) + + def __init__( + self, + message: RawRequestMessage, + payload: StreamReader, + protocol: "RequestHandler", + payload_writer: AbstractStreamWriter, + task: "asyncio.Task[None]", + loop: asyncio.AbstractEventLoop, + *, + client_max_size: int = 1024**2, + state: Optional[Dict[str, Any]] = None, + scheme: Optional[str] = None, + host: Optional[str] = None, + remote: Optional[str] = None, + ) -> None: + if state is None: + state = {} + self._message = message + self._protocol = protocol + self._payload_writer = payload_writer + + self._payload = payload + self._headers = message.headers + self._method = message.method + self._version = message.version + self._cache: Dict[str, Any] = {} + url = message.url + if url.is_absolute(): + # absolute URL is given, + # override auto-calculating url, host, and scheme + # all other properties should be good + self._cache["url"] = url + self._cache["host"] = url.host + self._cache["scheme"] = url.scheme + self._rel_url = url.relative() + else: + self._rel_url = message.url + self._post: Optional[MultiDictProxy[Union[str, bytes, FileField]]] = None + self._read_bytes: Optional[bytes] = None + + self._state = state + self._task = task + self._client_max_size = client_max_size + self._loop = loop + + transport = self._protocol.transport + assert transport is not None + self._transport_sslcontext = transport.get_extra_info("sslcontext") + self._transport_peername = transport.get_extra_info("peername") + + if scheme is not None: + self._cache["scheme"] = scheme + if host is not None: + self._cache["host"] = host + if remote is not None: + self._cache["remote"] = remote + + def clone( + self, + *, + method: Union[str, _SENTINEL] = sentinel, + rel_url: Union[StrOrURL, _SENTINEL] = sentinel, + headers: Union[LooseHeaders, _SENTINEL] = sentinel, + scheme: Union[str, _SENTINEL] = sentinel, + host: Union[str, _SENTINEL] = sentinel, + remote: Union[str, _SENTINEL] = sentinel, + client_max_size: Union[int, _SENTINEL] = sentinel, + ) -> "BaseRequest": + """Clone itself with replacement some attributes. + + Creates and returns a new instance of Request object. If no parameters + are given, an exact copy is returned. If a parameter is not passed, it + will reuse the one from the current request object. + """ + if self._read_bytes: + raise RuntimeError("Cannot clone request " "after reading its content") + + dct: Dict[str, Any] = {} + if method is not sentinel: + dct["method"] = method + if rel_url is not sentinel: + new_url: URL = URL(rel_url) + dct["url"] = new_url + dct["path"] = str(new_url) + if headers is not sentinel: + # a copy semantic + dct["headers"] = CIMultiDictProxy(CIMultiDict(headers)) + dct["raw_headers"] = tuple( + (k.encode("utf-8"), v.encode("utf-8")) + for k, v in dct["headers"].items() + ) + + message = self._message._replace(**dct) + + kwargs = {} + if scheme is not sentinel: + kwargs["scheme"] = scheme + if host is not sentinel: + kwargs["host"] = host + if remote is not sentinel: + kwargs["remote"] = remote + if client_max_size is sentinel: + client_max_size = self._client_max_size + + return self.__class__( + message, + self._payload, + self._protocol, + self._payload_writer, + self._task, + self._loop, + client_max_size=client_max_size, + state=self._state.copy(), + **kwargs, + ) + + @property + def task(self) -> "asyncio.Task[None]": + return self._task + + @property + def protocol(self) -> "RequestHandler": + return self._protocol + + @property + def transport(self) -> Optional[asyncio.Transport]: + if self._protocol is None: + return None + return self._protocol.transport + + @property + def writer(self) -> AbstractStreamWriter: + return self._payload_writer + + @property + def client_max_size(self) -> int: + return self._client_max_size + + @reify + def message(self) -> RawRequestMessage: + warnings.warn("Request.message is deprecated", DeprecationWarning, stacklevel=3) + return self._message + + @reify + def rel_url(self) -> URL: + return self._rel_url + + @reify + def loop(self) -> asyncio.AbstractEventLoop: + warnings.warn( + "request.loop property is deprecated", DeprecationWarning, stacklevel=2 + ) + return self._loop + + # MutableMapping API + + def __getitem__(self, key: str) -> Any: + return self._state[key] + + def __setitem__(self, key: str, value: Any) -> None: + self._state[key] = value + + def __delitem__(self, key: str) -> None: + del self._state[key] + + def __len__(self) -> int: + return len(self._state) + + def __iter__(self) -> Iterator[str]: + return iter(self._state) + + ######## + + @reify + def secure(self) -> bool: + """A bool indicating if the request is handled with SSL.""" + return self.scheme == "https" + + @reify + def forwarded(self) -> Tuple[Mapping[str, str], ...]: + """A tuple containing all parsed Forwarded header(s). + + Makes an effort to parse Forwarded headers as specified by RFC 7239: + + - It adds one (immutable) dictionary per Forwarded 'field-value', ie + per proxy. The element corresponds to the data in the Forwarded + field-value added by the first proxy encountered by the client. Each + subsequent item corresponds to those added by later proxies. + - It checks that every value has valid syntax in general as specified + in section 4: either a 'token' or a 'quoted-string'. + - It un-escapes found escape sequences. + - It does NOT validate 'by' and 'for' contents as specified in section + 6. + - It does NOT validate 'host' contents (Host ABNF). + - It does NOT validate 'proto' contents for valid URI scheme names. + + Returns a tuple containing one or more immutable dicts + """ + elems = [] + for field_value in self._message.headers.getall(hdrs.FORWARDED, ()): + length = len(field_value) + pos = 0 + need_separator = False + elem: Dict[str, str] = {} + elems.append(types.MappingProxyType(elem)) + while 0 <= pos < length: + match = _FORWARDED_PAIR_RE.match(field_value, pos) + if match is not None: # got a valid forwarded-pair + if need_separator: + # bad syntax here, skip to next comma + pos = field_value.find(",", pos) + else: + name, value, port = match.groups() + if value[0] == '"': + # quoted string: remove quotes and unescape + value = _QUOTED_PAIR_REPLACE_RE.sub(r"\1", value[1:-1]) + if port: + value += port + elem[name.lower()] = value + pos += len(match.group(0)) + need_separator = True + elif field_value[pos] == ",": # next forwarded-element + need_separator = False + elem = {} + elems.append(types.MappingProxyType(elem)) + pos += 1 + elif field_value[pos] == ";": # next forwarded-pair + need_separator = False + pos += 1 + elif field_value[pos] in " \t": + # Allow whitespace even between forwarded-pairs, though + # RFC 7239 doesn't. This simplifies code and is in line + # with Postel's law. + pos += 1 + else: + # bad syntax here, skip to next comma + pos = field_value.find(",", pos) + return tuple(elems) + + @reify + def scheme(self) -> str: + """A string representing the scheme of the request. + + Hostname is resolved in this order: + + - overridden value by .clone(scheme=new_scheme) call. + - type of connection to peer: HTTPS if socket is SSL, HTTP otherwise. + + 'http' or 'https'. + """ + if self._transport_sslcontext: + return "https" + else: + return "http" + + @reify + def method(self) -> str: + """Read only property for getting HTTP method. + + The value is upper-cased str like 'GET', 'POST', 'PUT' etc. + """ + return self._method + + @reify + def version(self) -> HttpVersion: + """Read only property for getting HTTP version of request. + + Returns aiohttp.protocol.HttpVersion instance. + """ + return self._version + + @reify + def host(self) -> str: + """Hostname of the request. + + Hostname is resolved in this order: + + - overridden value by .clone(host=new_host) call. + - HOST HTTP header + - socket.getfqdn() value + """ + host = self._message.headers.get(hdrs.HOST) + if host is not None: + return host + return socket.getfqdn() + + @reify + def remote(self) -> Optional[str]: + """Remote IP of client initiated HTTP request. + + The IP is resolved in this order: + + - overridden value by .clone(remote=new_remote) call. + - peername of opened socket + """ + if self._transport_peername is None: + return None + if isinstance(self._transport_peername, (list, tuple)): + return str(self._transport_peername[0]) + return str(self._transport_peername) + + @reify + def url(self) -> URL: + url = URL.build(scheme=self.scheme, host=self.host) + return url.join(self._rel_url) + + @reify + def path(self) -> str: + """The URL including *PATH INFO* without the host or scheme. + + E.g., ``/app/blog`` + """ + return self._rel_url.path + + @reify + def path_qs(self) -> str: + """The URL including PATH_INFO and the query string. + + E.g, /app/blog?id=10 + """ + return str(self._rel_url) + + @reify + def raw_path(self) -> str: + """The URL including raw *PATH INFO* without the host or scheme. + + Warning, the path is unquoted and may contains non valid URL characters + + E.g., ``/my%2Fpath%7Cwith%21some%25strange%24characters`` + """ + return self._message.path + + @reify + def query(self) -> "MultiMapping[str]": + """A multidict with all the variables in the query string.""" + return MultiDictProxy(self._rel_url.query) + + @reify + def query_string(self) -> str: + """The query string in the URL. + + E.g., id=10 + """ + return self._rel_url.query_string + + @reify + def headers(self) -> "MultiMapping[str]": + """A case-insensitive multidict proxy with all headers.""" + return self._headers + + @reify + def raw_headers(self) -> RawHeaders: + """A sequence of pairs for all headers.""" + return self._message.raw_headers + + @reify + def if_modified_since(self) -> Optional[datetime.datetime]: + """The value of If-Modified-Since HTTP header, or None. + + This header is represented as a `datetime` object. + """ + return parse_http_date(self.headers.get(hdrs.IF_MODIFIED_SINCE)) + + @reify + def if_unmodified_since(self) -> Optional[datetime.datetime]: + """The value of If-Unmodified-Since HTTP header, or None. + + This header is represented as a `datetime` object. + """ + return parse_http_date(self.headers.get(hdrs.IF_UNMODIFIED_SINCE)) + + @staticmethod + def _etag_values(etag_header: str) -> Iterator[ETag]: + """Extract `ETag` objects from raw header.""" + if etag_header == ETAG_ANY: + yield ETag( + is_weak=False, + value=ETAG_ANY, + ) + else: + for match in LIST_QUOTED_ETAG_RE.finditer(etag_header): + is_weak, value, garbage = match.group(2, 3, 4) + # Any symbol captured by 4th group means + # that the following sequence is invalid. + if garbage: + break + + yield ETag( + is_weak=bool(is_weak), + value=value, + ) + + @classmethod + def _if_match_or_none_impl( + cls, header_value: Optional[str] + ) -> Optional[Tuple[ETag, ...]]: + if not header_value: + return None + + return tuple(cls._etag_values(header_value)) + + @reify + def if_match(self) -> Optional[Tuple[ETag, ...]]: + """The value of If-Match HTTP header, or None. + + This header is represented as a `tuple` of `ETag` objects. + """ + return self._if_match_or_none_impl(self.headers.get(hdrs.IF_MATCH)) + + @reify + def if_none_match(self) -> Optional[Tuple[ETag, ...]]: + """The value of If-None-Match HTTP header, or None. + + This header is represented as a `tuple` of `ETag` objects. + """ + return self._if_match_or_none_impl(self.headers.get(hdrs.IF_NONE_MATCH)) + + @reify + def if_range(self) -> Optional[datetime.datetime]: + """The value of If-Range HTTP header, or None. + + This header is represented as a `datetime` object. + """ + return parse_http_date(self.headers.get(hdrs.IF_RANGE)) + + @reify + def keep_alive(self) -> bool: + """Is keepalive enabled by client?""" + return not self._message.should_close + + @reify + def cookies(self) -> Mapping[str, str]: + """Return request cookies. + + A read-only dictionary-like object. + """ + raw = self.headers.get(hdrs.COOKIE, "") + parsed = SimpleCookie(raw) + return MappingProxyType({key: val.value for key, val in parsed.items()}) + + @reify + def http_range(self) -> slice: + """The content of Range HTTP header. + + Return a slice instance. + + """ + rng = self._headers.get(hdrs.RANGE) + start, end = None, None + if rng is not None: + try: + pattern = r"^bytes=(\d*)-(\d*)$" + start, end = re.findall(pattern, rng)[0] + except IndexError: # pattern was not found in header + raise ValueError("range not in acceptable format") + + end = int(end) if end else None + start = int(start) if start else None + + if start is None and end is not None: + # end with no start is to return tail of content + start = -end + end = None + + if start is not None and end is not None: + # end is inclusive in range header, exclusive for slice + end += 1 + + if start >= end: + raise ValueError("start cannot be after end") + + if start is end is None: # No valid range supplied + raise ValueError("No start or end of range specified") + + return slice(start, end, 1) + + @reify + def content(self) -> StreamReader: + """Return raw payload stream.""" + return self._payload + + @property + def has_body(self) -> bool: + """Return True if request's HTTP BODY can be read, False otherwise.""" + warnings.warn( + "Deprecated, use .can_read_body #2005", DeprecationWarning, stacklevel=2 + ) + return not self._payload.at_eof() + + @property + def can_read_body(self) -> bool: + """Return True if request's HTTP BODY can be read, False otherwise.""" + return not self._payload.at_eof() + + @reify + def body_exists(self) -> bool: + """Return True if request has HTTP BODY, False otherwise.""" + return type(self._payload) is not EmptyStreamReader + + async def release(self) -> None: + """Release request. + + Eat unread part of HTTP BODY if present. + """ + while not self._payload.at_eof(): + await self._payload.readany() + + async def read(self) -> bytes: + """Read request body if present. + + Returns bytes object with full request content. + """ + if self._read_bytes is None: + body = bytearray() + while True: + chunk = await self._payload.readany() + body.extend(chunk) + if self._client_max_size: + body_size = len(body) + if body_size >= self._client_max_size: + raise HTTPRequestEntityTooLarge( + max_size=self._client_max_size, actual_size=body_size + ) + if not chunk: + break + self._read_bytes = bytes(body) + return self._read_bytes + + async def text(self) -> str: + """Return BODY as text using encoding from .charset.""" + bytes_body = await self.read() + encoding = self.charset or "utf-8" + return bytes_body.decode(encoding) + + async def json(self, *, loads: JSONDecoder = DEFAULT_JSON_DECODER) -> Any: + """Return BODY as JSON.""" + body = await self.text() + return loads(body) + + async def multipart(self) -> MultipartReader: + """Return async iterator to process BODY as multipart.""" + return MultipartReader(self._headers, self._payload) + + async def post(self) -> "MultiDictProxy[Union[str, bytes, FileField]]": + """Return POST parameters.""" + if self._post is not None: + return self._post + if self._method not in self.POST_METHODS: + self._post = MultiDictProxy(MultiDict()) + return self._post + + content_type = self.content_type + if content_type not in ( + "", + "application/x-www-form-urlencoded", + "multipart/form-data", + ): + self._post = MultiDictProxy(MultiDict()) + return self._post + + out: MultiDict[Union[str, bytes, FileField]] = MultiDict() + + if content_type == "multipart/form-data": + multipart = await self.multipart() + max_size = self._client_max_size + + field = await multipart.next() + while field is not None: + size = 0 + field_ct = field.headers.get(hdrs.CONTENT_TYPE) + + if isinstance(field, BodyPartReader): + assert field.name is not None + + # Note that according to RFC 7578, the Content-Type header + # is optional, even for files, so we can't assume it's + # present. + # https://tools.ietf.org/html/rfc7578#section-4.4 + if field.filename: + # store file in temp file + tmp = await self._loop.run_in_executor( + None, tempfile.TemporaryFile + ) + chunk = await field.read_chunk(size=2**16) + while chunk: + chunk = field.decode(chunk) + await self._loop.run_in_executor(None, tmp.write, chunk) + size += len(chunk) + if 0 < max_size < size: + await self._loop.run_in_executor(None, tmp.close) + raise HTTPRequestEntityTooLarge( + max_size=max_size, actual_size=size + ) + chunk = await field.read_chunk(size=2**16) + await self._loop.run_in_executor(None, tmp.seek, 0) + + if field_ct is None: + field_ct = "application/octet-stream" + + ff = FileField( + field.name, + field.filename, + cast(io.BufferedReader, tmp), + field_ct, + field.headers, + ) + out.add(field.name, ff) + else: + # deal with ordinary data + value = await field.read(decode=True) + if field_ct is None or field_ct.startswith("text/"): + charset = field.get_charset(default="utf-8") + out.add(field.name, value.decode(charset)) + else: + out.add(field.name, value) + size += len(value) + if 0 < max_size < size: + raise HTTPRequestEntityTooLarge( + max_size=max_size, actual_size=size + ) + else: + raise ValueError( + "To decode nested multipart you need " "to use custom reader", + ) + + field = await multipart.next() + else: + data = await self.read() + if data: + charset = self.charset or "utf-8" + out.extend( + parse_qsl( + data.rstrip().decode(charset), + keep_blank_values=True, + encoding=charset, + ) + ) + + self._post = MultiDictProxy(out) + return self._post + + def get_extra_info(self, name: str, default: Any = None) -> Any: + """Extra info from protocol transport""" + protocol = self._protocol + if protocol is None: + return default + + transport = protocol.transport + if transport is None: + return default + + return transport.get_extra_info(name, default) + + def __repr__(self) -> str: + ascii_encodable_path = self.path.encode("ascii", "backslashreplace").decode( + "ascii" + ) + return "<{} {} {} >".format( + self.__class__.__name__, self._method, ascii_encodable_path + ) + + def __eq__(self, other: object) -> bool: + return id(self) == id(other) + + def __bool__(self) -> bool: + return True + + async def _prepare_hook(self, response: StreamResponse) -> None: + return + + def _cancel(self, exc: BaseException) -> None: + set_exception(self._payload, exc) + + def _finish(self) -> None: + if self._post is None or self.content_type != "multipart/form-data": + return + + # NOTE: Release file descriptors for the + # NOTE: `tempfile.Temporaryfile`-created `_io.BufferedRandom` + # NOTE: instances of files sent within multipart request body + # NOTE: via HTTP POST request. + for file_name, file_field_object in self._post.items(): + if isinstance(file_field_object, FileField): + file_field_object.file.close() + + +class Request(BaseRequest): + + ATTRS = BaseRequest.ATTRS | frozenset(["_match_info"]) + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + # matchdict, route_name, handler + # or information about traversal lookup + + # initialized after route resolving + self._match_info: Optional[UrlMappingMatchInfo] = None + + if DEBUG: + + def __setattr__(self, name: str, val: Any) -> None: + if name not in self.ATTRS: + warnings.warn( + "Setting custom {}.{} attribute " + "is discouraged".format(self.__class__.__name__, name), + DeprecationWarning, + stacklevel=2, + ) + super().__setattr__(name, val) + + def clone( + self, + *, + method: Union[str, _SENTINEL] = sentinel, + rel_url: Union[StrOrURL, _SENTINEL] = sentinel, + headers: Union[LooseHeaders, _SENTINEL] = sentinel, + scheme: Union[str, _SENTINEL] = sentinel, + host: Union[str, _SENTINEL] = sentinel, + remote: Union[str, _SENTINEL] = sentinel, + client_max_size: Union[int, _SENTINEL] = sentinel, + ) -> "Request": + ret = super().clone( + method=method, + rel_url=rel_url, + headers=headers, + scheme=scheme, + host=host, + remote=remote, + client_max_size=client_max_size, + ) + new_ret = cast(Request, ret) + new_ret._match_info = self._match_info + return new_ret + + @reify + def match_info(self) -> "UrlMappingMatchInfo": + """Result of route resolving.""" + match_info = self._match_info + assert match_info is not None + return match_info + + @property + def app(self) -> "Application": + """Application instance.""" + match_info = self._match_info + assert match_info is not None + return match_info.current_app + + @property + def config_dict(self) -> ChainMapProxy: + match_info = self._match_info + assert match_info is not None + lst = match_info.apps + app = self.app + idx = lst.index(app) + sublist = list(reversed(lst[: idx + 1])) + return ChainMapProxy(sublist) + + async def _prepare_hook(self, response: StreamResponse) -> None: + match_info = self._match_info + if match_info is None: + return + for app in match_info._apps: + await app.on_response_prepare.send(self, response) diff --git a/env/Lib/site-packages/aiohttp/web_response.py b/env/Lib/site-packages/aiohttp/web_response.py new file mode 100644 index 0000000..78d3fe3 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_response.py @@ -0,0 +1,820 @@ +import asyncio +import collections.abc +import datetime +import enum +import json +import math +import time +import warnings +from concurrent.futures import Executor +from http import HTTPStatus +from http.cookies import SimpleCookie +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterator, + MutableMapping, + Optional, + Union, + cast, +) + +from multidict import CIMultiDict, istr + +from . import hdrs, payload +from .abc import AbstractStreamWriter +from .compression_utils import ZLibCompressor +from .helpers import ( + ETAG_ANY, + QUOTED_ETAG_RE, + ETag, + HeadersMixin, + must_be_empty_body, + parse_http_date, + rfc822_formatted_time, + sentinel, + should_remove_content_length, + validate_etag_value, +) +from .http import SERVER_SOFTWARE, HttpVersion10, HttpVersion11 +from .payload import Payload +from .typedefs import JSONEncoder, LooseHeaders + +__all__ = ("ContentCoding", "StreamResponse", "Response", "json_response") + + +if TYPE_CHECKING: + from .web_request import BaseRequest + + BaseClass = MutableMapping[str, Any] +else: + BaseClass = collections.abc.MutableMapping + + +# TODO(py311): Convert to StrEnum for wider use +class ContentCoding(enum.Enum): + # The content codings that we have support for. + # + # Additional registered codings are listed at: + # https://www.iana.org/assignments/http-parameters/http-parameters.xhtml#content-coding + deflate = "deflate" + gzip = "gzip" + identity = "identity" + + +############################################################ +# HTTP Response classes +############################################################ + + +class StreamResponse(BaseClass, HeadersMixin): + + _length_check = True + + def __init__( + self, + *, + status: int = 200, + reason: Optional[str] = None, + headers: Optional[LooseHeaders] = None, + ) -> None: + self._body = None + self._keep_alive: Optional[bool] = None + self._chunked = False + self._compression = False + self._compression_force: Optional[ContentCoding] = None + self._cookies = SimpleCookie() + + self._req: Optional[BaseRequest] = None + self._payload_writer: Optional[AbstractStreamWriter] = None + self._eof_sent = False + self._must_be_empty_body: Optional[bool] = None + self._body_length = 0 + self._state: Dict[str, Any] = {} + + if headers is not None: + self._headers: CIMultiDict[str] = CIMultiDict(headers) + else: + self._headers = CIMultiDict() + + self.set_status(status, reason) + + @property + def prepared(self) -> bool: + return self._payload_writer is not None + + @property + def task(self) -> "Optional[asyncio.Task[None]]": + if self._req: + return self._req.task + else: + return None + + @property + def status(self) -> int: + return self._status + + @property + def chunked(self) -> bool: + return self._chunked + + @property + def compression(self) -> bool: + return self._compression + + @property + def reason(self) -> str: + return self._reason + + def set_status( + self, + status: int, + reason: Optional[str] = None, + ) -> None: + assert not self.prepared, ( + "Cannot change the response status code after " "the headers have been sent" + ) + self._status = int(status) + if reason is None: + try: + reason = HTTPStatus(self._status).phrase + except ValueError: + reason = "" + self._reason = reason + + @property + def keep_alive(self) -> Optional[bool]: + return self._keep_alive + + def force_close(self) -> None: + self._keep_alive = False + + @property + def body_length(self) -> int: + return self._body_length + + @property + def output_length(self) -> int: + warnings.warn("output_length is deprecated", DeprecationWarning) + assert self._payload_writer + return self._payload_writer.buffer_size + + def enable_chunked_encoding(self, chunk_size: Optional[int] = None) -> None: + """Enables automatic chunked transfer encoding.""" + self._chunked = True + + if hdrs.CONTENT_LENGTH in self._headers: + raise RuntimeError( + "You can't enable chunked encoding when " "a content length is set" + ) + if chunk_size is not None: + warnings.warn("Chunk size is deprecated #1615", DeprecationWarning) + + def enable_compression( + self, force: Optional[Union[bool, ContentCoding]] = None + ) -> None: + """Enables response compression encoding.""" + # Backwards compatibility for when force was a bool <0.17. + if isinstance(force, bool): + force = ContentCoding.deflate if force else ContentCoding.identity + warnings.warn( + "Using boolean for force is deprecated #3318", DeprecationWarning + ) + elif force is not None: + assert isinstance(force, ContentCoding), ( + "force should one of " "None, bool or " "ContentEncoding" + ) + + self._compression = True + self._compression_force = force + + @property + def headers(self) -> "CIMultiDict[str]": + return self._headers + + @property + def cookies(self) -> SimpleCookie: + return self._cookies + + def set_cookie( + self, + name: str, + value: str, + *, + expires: Optional[str] = None, + domain: Optional[str] = None, + max_age: Optional[Union[int, str]] = None, + path: str = "/", + secure: Optional[bool] = None, + httponly: Optional[bool] = None, + version: Optional[str] = None, + samesite: Optional[str] = None, + ) -> None: + """Set or update response cookie. + + Sets new cookie or updates existent with new value. + Also updates only those params which are not None. + """ + old = self._cookies.get(name) + if old is not None and old.coded_value == "": + # deleted cookie + self._cookies.pop(name, None) + + self._cookies[name] = value + c = self._cookies[name] + + if expires is not None: + c["expires"] = expires + elif c.get("expires") == "Thu, 01 Jan 1970 00:00:00 GMT": + del c["expires"] + + if domain is not None: + c["domain"] = domain + + if max_age is not None: + c["max-age"] = str(max_age) + elif "max-age" in c: + del c["max-age"] + + c["path"] = path + + if secure is not None: + c["secure"] = secure + if httponly is not None: + c["httponly"] = httponly + if version is not None: + c["version"] = version + if samesite is not None: + c["samesite"] = samesite + + def del_cookie( + self, name: str, *, domain: Optional[str] = None, path: str = "/" + ) -> None: + """Delete cookie. + + Creates new empty expired cookie. + """ + # TODO: do we need domain/path here? + self._cookies.pop(name, None) + self.set_cookie( + name, + "", + max_age=0, + expires="Thu, 01 Jan 1970 00:00:00 GMT", + domain=domain, + path=path, + ) + + @property + def content_length(self) -> Optional[int]: + # Just a placeholder for adding setter + return super().content_length + + @content_length.setter + def content_length(self, value: Optional[int]) -> None: + if value is not None: + value = int(value) + if self._chunked: + raise RuntimeError( + "You can't set content length when " "chunked encoding is enable" + ) + self._headers[hdrs.CONTENT_LENGTH] = str(value) + else: + self._headers.pop(hdrs.CONTENT_LENGTH, None) + + @property + def content_type(self) -> str: + # Just a placeholder for adding setter + return super().content_type + + @content_type.setter + def content_type(self, value: str) -> None: + self.content_type # read header values if needed + self._content_type = str(value) + self._generate_content_type_header() + + @property + def charset(self) -> Optional[str]: + # Just a placeholder for adding setter + return super().charset + + @charset.setter + def charset(self, value: Optional[str]) -> None: + ctype = self.content_type # read header values if needed + if ctype == "application/octet-stream": + raise RuntimeError( + "Setting charset for application/octet-stream " + "doesn't make sense, setup content_type first" + ) + assert self._content_dict is not None + if value is None: + self._content_dict.pop("charset", None) + else: + self._content_dict["charset"] = str(value).lower() + self._generate_content_type_header() + + @property + def last_modified(self) -> Optional[datetime.datetime]: + """The value of Last-Modified HTTP header, or None. + + This header is represented as a `datetime` object. + """ + return parse_http_date(self._headers.get(hdrs.LAST_MODIFIED)) + + @last_modified.setter + def last_modified( + self, value: Optional[Union[int, float, datetime.datetime, str]] + ) -> None: + if value is None: + self._headers.pop(hdrs.LAST_MODIFIED, None) + elif isinstance(value, (int, float)): + self._headers[hdrs.LAST_MODIFIED] = time.strftime( + "%a, %d %b %Y %H:%M:%S GMT", time.gmtime(math.ceil(value)) + ) + elif isinstance(value, datetime.datetime): + self._headers[hdrs.LAST_MODIFIED] = time.strftime( + "%a, %d %b %Y %H:%M:%S GMT", value.utctimetuple() + ) + elif isinstance(value, str): + self._headers[hdrs.LAST_MODIFIED] = value + + @property + def etag(self) -> Optional[ETag]: + quoted_value = self._headers.get(hdrs.ETAG) + if not quoted_value: + return None + elif quoted_value == ETAG_ANY: + return ETag(value=ETAG_ANY) + match = QUOTED_ETAG_RE.fullmatch(quoted_value) + if not match: + return None + is_weak, value = match.group(1, 2) + return ETag( + is_weak=bool(is_weak), + value=value, + ) + + @etag.setter + def etag(self, value: Optional[Union[ETag, str]]) -> None: + if value is None: + self._headers.pop(hdrs.ETAG, None) + elif (isinstance(value, str) and value == ETAG_ANY) or ( + isinstance(value, ETag) and value.value == ETAG_ANY + ): + self._headers[hdrs.ETAG] = ETAG_ANY + elif isinstance(value, str): + validate_etag_value(value) + self._headers[hdrs.ETAG] = f'"{value}"' + elif isinstance(value, ETag) and isinstance(value.value, str): + validate_etag_value(value.value) + hdr_value = f'W/"{value.value}"' if value.is_weak else f'"{value.value}"' + self._headers[hdrs.ETAG] = hdr_value + else: + raise ValueError( + f"Unsupported etag type: {type(value)}. " + f"etag must be str, ETag or None" + ) + + def _generate_content_type_header( + self, CONTENT_TYPE: istr = hdrs.CONTENT_TYPE + ) -> None: + assert self._content_dict is not None + assert self._content_type is not None + params = "; ".join(f"{k}={v}" for k, v in self._content_dict.items()) + if params: + ctype = self._content_type + "; " + params + else: + ctype = self._content_type + self._headers[CONTENT_TYPE] = ctype + + async def _do_start_compression(self, coding: ContentCoding) -> None: + if coding != ContentCoding.identity: + assert self._payload_writer is not None + self._headers[hdrs.CONTENT_ENCODING] = coding.value + self._payload_writer.enable_compression(coding.value) + # Compressed payload may have different content length, + # remove the header + self._headers.popall(hdrs.CONTENT_LENGTH, None) + + async def _start_compression(self, request: "BaseRequest") -> None: + if self._compression_force: + await self._do_start_compression(self._compression_force) + else: + # Encoding comparisons should be case-insensitive + # https://www.rfc-editor.org/rfc/rfc9110#section-8.4.1 + accept_encoding = request.headers.get(hdrs.ACCEPT_ENCODING, "").lower() + for coding in ContentCoding: + if coding.value in accept_encoding: + await self._do_start_compression(coding) + return + + async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]: + if self._eof_sent: + return None + if self._payload_writer is not None: + return self._payload_writer + self._must_be_empty_body = must_be_empty_body(request.method, self.status) + return await self._start(request) + + async def _start(self, request: "BaseRequest") -> AbstractStreamWriter: + self._req = request + writer = self._payload_writer = request._payload_writer + + await self._prepare_headers() + await request._prepare_hook(self) + await self._write_headers() + + return writer + + async def _prepare_headers(self) -> None: + request = self._req + assert request is not None + writer = self._payload_writer + assert writer is not None + keep_alive = self._keep_alive + if keep_alive is None: + keep_alive = request.keep_alive + self._keep_alive = keep_alive + + version = request.version + + headers = self._headers + for cookie in self._cookies.values(): + value = cookie.output(header="")[1:] + headers.add(hdrs.SET_COOKIE, value) + + if self._compression: + await self._start_compression(request) + + if self._chunked: + if version != HttpVersion11: + raise RuntimeError( + "Using chunked encoding is forbidden " + "for HTTP/{0.major}.{0.minor}".format(request.version) + ) + if not self._must_be_empty_body: + writer.enable_chunking() + headers[hdrs.TRANSFER_ENCODING] = "chunked" + if hdrs.CONTENT_LENGTH in headers: + del headers[hdrs.CONTENT_LENGTH] + elif self._length_check: + writer.length = self.content_length + if writer.length is None: + if version >= HttpVersion11: + if not self._must_be_empty_body: + writer.enable_chunking() + headers[hdrs.TRANSFER_ENCODING] = "chunked" + elif not self._must_be_empty_body: + keep_alive = False + + # HTTP 1.1: https://tools.ietf.org/html/rfc7230#section-3.3.2 + # HTTP 1.0: https://tools.ietf.org/html/rfc1945#section-10.4 + if self._must_be_empty_body: + if hdrs.CONTENT_LENGTH in headers and should_remove_content_length( + request.method, self.status + ): + del headers[hdrs.CONTENT_LENGTH] + # https://datatracker.ietf.org/doc/html/rfc9112#section-6.1-10 + # https://datatracker.ietf.org/doc/html/rfc9112#section-6.1-13 + if hdrs.TRANSFER_ENCODING in headers: + del headers[hdrs.TRANSFER_ENCODING] + else: + headers.setdefault(hdrs.CONTENT_TYPE, "application/octet-stream") + headers.setdefault(hdrs.DATE, rfc822_formatted_time()) + headers.setdefault(hdrs.SERVER, SERVER_SOFTWARE) + + # connection header + if hdrs.CONNECTION not in headers: + if keep_alive: + if version == HttpVersion10: + headers[hdrs.CONNECTION] = "keep-alive" + else: + if version == HttpVersion11: + headers[hdrs.CONNECTION] = "close" + + async def _write_headers(self) -> None: + request = self._req + assert request is not None + writer = self._payload_writer + assert writer is not None + # status line + version = request.version + status_line = "HTTP/{}.{} {} {}".format( + version[0], version[1], self._status, self._reason + ) + await writer.write_headers(status_line, self._headers) + + async def write(self, data: bytes) -> None: + assert isinstance( + data, (bytes, bytearray, memoryview) + ), "data argument must be byte-ish (%r)" % type(data) + + if self._eof_sent: + raise RuntimeError("Cannot call write() after write_eof()") + if self._payload_writer is None: + raise RuntimeError("Cannot call write() before prepare()") + + await self._payload_writer.write(data) + + async def drain(self) -> None: + assert not self._eof_sent, "EOF has already been sent" + assert self._payload_writer is not None, "Response has not been started" + warnings.warn( + "drain method is deprecated, use await resp.write()", + DeprecationWarning, + stacklevel=2, + ) + await self._payload_writer.drain() + + async def write_eof(self, data: bytes = b"") -> None: + assert isinstance( + data, (bytes, bytearray, memoryview) + ), "data argument must be byte-ish (%r)" % type(data) + + if self._eof_sent: + return + + assert self._payload_writer is not None, "Response has not been started" + + await self._payload_writer.write_eof(data) + self._eof_sent = True + self._req = None + self._body_length = self._payload_writer.output_size + self._payload_writer = None + + def __repr__(self) -> str: + if self._eof_sent: + info = "eof" + elif self.prepared: + assert self._req is not None + info = f"{self._req.method} {self._req.path} " + else: + info = "not prepared" + return f"<{self.__class__.__name__} {self.reason} {info}>" + + def __getitem__(self, key: str) -> Any: + return self._state[key] + + def __setitem__(self, key: str, value: Any) -> None: + self._state[key] = value + + def __delitem__(self, key: str) -> None: + del self._state[key] + + def __len__(self) -> int: + return len(self._state) + + def __iter__(self) -> Iterator[str]: + return iter(self._state) + + def __hash__(self) -> int: + return hash(id(self)) + + def __eq__(self, other: object) -> bool: + return self is other + + +class Response(StreamResponse): + def __init__( + self, + *, + body: Any = None, + status: int = 200, + reason: Optional[str] = None, + text: Optional[str] = None, + headers: Optional[LooseHeaders] = None, + content_type: Optional[str] = None, + charset: Optional[str] = None, + zlib_executor_size: Optional[int] = None, + zlib_executor: Optional[Executor] = None, + ) -> None: + if body is not None and text is not None: + raise ValueError("body and text are not allowed together") + + if headers is None: + real_headers: CIMultiDict[str] = CIMultiDict() + elif not isinstance(headers, CIMultiDict): + real_headers = CIMultiDict(headers) + else: + real_headers = headers # = cast('CIMultiDict[str]', headers) + + if content_type is not None and "charset" in content_type: + raise ValueError("charset must not be in content_type " "argument") + + if text is not None: + if hdrs.CONTENT_TYPE in real_headers: + if content_type or charset: + raise ValueError( + "passing both Content-Type header and " + "content_type or charset params " + "is forbidden" + ) + else: + # fast path for filling headers + if not isinstance(text, str): + raise TypeError("text argument must be str (%r)" % type(text)) + if content_type is None: + content_type = "text/plain" + if charset is None: + charset = "utf-8" + real_headers[hdrs.CONTENT_TYPE] = content_type + "; charset=" + charset + body = text.encode(charset) + text = None + else: + if hdrs.CONTENT_TYPE in real_headers: + if content_type is not None or charset is not None: + raise ValueError( + "passing both Content-Type header and " + "content_type or charset params " + "is forbidden" + ) + else: + if content_type is not None: + if charset is not None: + content_type += "; charset=" + charset + real_headers[hdrs.CONTENT_TYPE] = content_type + + super().__init__(status=status, reason=reason, headers=real_headers) + + if text is not None: + self.text = text + else: + self.body = body + + self._compressed_body: Optional[bytes] = None + self._zlib_executor_size = zlib_executor_size + self._zlib_executor = zlib_executor + + @property + def body(self) -> Optional[Union[bytes, Payload]]: + return self._body + + @body.setter + def body(self, body: bytes) -> None: + if body is None: + self._body: Optional[bytes] = None + self._body_payload: bool = False + elif isinstance(body, (bytes, bytearray)): + self._body = body + self._body_payload = False + else: + try: + self._body = body = payload.PAYLOAD_REGISTRY.get(body) + except payload.LookupError: + raise ValueError("Unsupported body type %r" % type(body)) + + self._body_payload = True + + headers = self._headers + + # set content-type + if hdrs.CONTENT_TYPE not in headers: + headers[hdrs.CONTENT_TYPE] = body.content_type + + # copy payload headers + if body.headers: + for key, value in body.headers.items(): + if key not in headers: + headers[key] = value + + self._compressed_body = None + + @property + def text(self) -> Optional[str]: + if self._body is None: + return None + return self._body.decode(self.charset or "utf-8") + + @text.setter + def text(self, text: str) -> None: + assert text is None or isinstance( + text, str + ), "text argument must be str (%r)" % type(text) + + if self.content_type == "application/octet-stream": + self.content_type = "text/plain" + if self.charset is None: + self.charset = "utf-8" + + self._body = text.encode(self.charset) + self._body_payload = False + self._compressed_body = None + + @property + def content_length(self) -> Optional[int]: + if self._chunked: + return None + + if hdrs.CONTENT_LENGTH in self._headers: + return super().content_length + + if self._compressed_body is not None: + # Return length of the compressed body + return len(self._compressed_body) + elif self._body_payload: + # A payload without content length, or a compressed payload + return None + elif self._body is not None: + return len(self._body) + else: + return 0 + + @content_length.setter + def content_length(self, value: Optional[int]) -> None: + raise RuntimeError("Content length is set automatically") + + async def write_eof(self, data: bytes = b"") -> None: + if self._eof_sent: + return + if self._compressed_body is None: + body: Optional[Union[bytes, Payload]] = self._body + else: + body = self._compressed_body + assert not data, f"data arg is not supported, got {data!r}" + assert self._req is not None + assert self._payload_writer is not None + if body is not None: + if self._must_be_empty_body: + await super().write_eof() + elif self._body_payload: + payload = cast(Payload, body) + await payload.write(self._payload_writer) + await super().write_eof() + else: + await super().write_eof(cast(bytes, body)) + else: + await super().write_eof() + + async def _start(self, request: "BaseRequest") -> AbstractStreamWriter: + if should_remove_content_length(request.method, self.status): + if hdrs.CONTENT_LENGTH in self._headers: + del self._headers[hdrs.CONTENT_LENGTH] + elif not self._chunked and hdrs.CONTENT_LENGTH not in self._headers: + if self._body_payload: + size = cast(Payload, self._body).size + if size is not None: + self._headers[hdrs.CONTENT_LENGTH] = str(size) + else: + body_len = len(self._body) if self._body else "0" + # https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6-7 + if body_len != "0" or ( + self.status != 304 and request.method.upper() != hdrs.METH_HEAD + ): + self._headers[hdrs.CONTENT_LENGTH] = str(body_len) + + return await super()._start(request) + + async def _do_start_compression(self, coding: ContentCoding) -> None: + if self._body_payload or self._chunked: + return await super()._do_start_compression(coding) + + if coding != ContentCoding.identity: + # Instead of using _payload_writer.enable_compression, + # compress the whole body + compressor = ZLibCompressor( + encoding=str(coding.value), + max_sync_chunk_size=self._zlib_executor_size, + executor=self._zlib_executor, + ) + assert self._body is not None + if self._zlib_executor_size is None and len(self._body) > 1024 * 1024: + warnings.warn( + "Synchronous compression of large response bodies " + f"({len(self._body)} bytes) might block the async event loop. " + "Consider providing a custom value to zlib_executor_size/" + "zlib_executor response properties or disabling compression on it." + ) + self._compressed_body = ( + await compressor.compress(self._body) + compressor.flush() + ) + assert self._compressed_body is not None + + self._headers[hdrs.CONTENT_ENCODING] = coding.value + self._headers[hdrs.CONTENT_LENGTH] = str(len(self._compressed_body)) + + +def json_response( + data: Any = sentinel, + *, + text: Optional[str] = None, + body: Optional[bytes] = None, + status: int = 200, + reason: Optional[str] = None, + headers: Optional[LooseHeaders] = None, + content_type: str = "application/json", + dumps: JSONEncoder = json.dumps, +) -> Response: + if data is not sentinel: + if text or body: + raise ValueError("only one of data, text, or body should be specified") + else: + text = dumps(data) + return Response( + text=text, + body=body, + status=status, + reason=reason, + headers=headers, + content_type=content_type, + ) diff --git a/env/Lib/site-packages/aiohttp/web_routedef.py b/env/Lib/site-packages/aiohttp/web_routedef.py new file mode 100644 index 0000000..9380214 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_routedef.py @@ -0,0 +1,214 @@ +import abc +import os # noqa +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterator, + List, + Optional, + Sequence, + Type, + Union, + overload, +) + +import attr + +from . import hdrs +from .abc import AbstractView +from .typedefs import Handler, PathLike + +if TYPE_CHECKING: + from .web_request import Request + from .web_response import StreamResponse + from .web_urldispatcher import AbstractRoute, UrlDispatcher +else: + Request = StreamResponse = UrlDispatcher = AbstractRoute = None + + +__all__ = ( + "AbstractRouteDef", + "RouteDef", + "StaticDef", + "RouteTableDef", + "head", + "options", + "get", + "post", + "patch", + "put", + "delete", + "route", + "view", + "static", +) + + +class AbstractRouteDef(abc.ABC): + @abc.abstractmethod + def register(self, router: UrlDispatcher) -> List[AbstractRoute]: + pass # pragma: no cover + + +_HandlerType = Union[Type[AbstractView], Handler] + + +@attr.s(auto_attribs=True, frozen=True, repr=False, slots=True) +class RouteDef(AbstractRouteDef): + method: str + path: str + handler: _HandlerType + kwargs: Dict[str, Any] + + def __repr__(self) -> str: + info = [] + for name, value in sorted(self.kwargs.items()): + info.append(f", {name}={value!r}") + return " {handler.__name__!r}" "{info}>".format( + method=self.method, path=self.path, handler=self.handler, info="".join(info) + ) + + def register(self, router: UrlDispatcher) -> List[AbstractRoute]: + if self.method in hdrs.METH_ALL: + reg = getattr(router, "add_" + self.method.lower()) + return [reg(self.path, self.handler, **self.kwargs)] + else: + return [ + router.add_route(self.method, self.path, self.handler, **self.kwargs) + ] + + +@attr.s(auto_attribs=True, frozen=True, repr=False, slots=True) +class StaticDef(AbstractRouteDef): + prefix: str + path: PathLike + kwargs: Dict[str, Any] + + def __repr__(self) -> str: + info = [] + for name, value in sorted(self.kwargs.items()): + info.append(f", {name}={value!r}") + return " {path}" "{info}>".format( + prefix=self.prefix, path=self.path, info="".join(info) + ) + + def register(self, router: UrlDispatcher) -> List[AbstractRoute]: + resource = router.add_static(self.prefix, self.path, **self.kwargs) + routes = resource.get_info().get("routes", {}) + return list(routes.values()) + + +def route(method: str, path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return RouteDef(method, path, handler, kwargs) + + +def head(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_HEAD, path, handler, **kwargs) + + +def options(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_OPTIONS, path, handler, **kwargs) + + +def get( + path: str, + handler: _HandlerType, + *, + name: Optional[str] = None, + allow_head: bool = True, + **kwargs: Any, +) -> RouteDef: + return route( + hdrs.METH_GET, path, handler, name=name, allow_head=allow_head, **kwargs + ) + + +def post(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_POST, path, handler, **kwargs) + + +def put(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_PUT, path, handler, **kwargs) + + +def patch(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_PATCH, path, handler, **kwargs) + + +def delete(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_DELETE, path, handler, **kwargs) + + +def view(path: str, handler: Type[AbstractView], **kwargs: Any) -> RouteDef: + return route(hdrs.METH_ANY, path, handler, **kwargs) + + +def static(prefix: str, path: PathLike, **kwargs: Any) -> StaticDef: + return StaticDef(prefix, path, kwargs) + + +_Deco = Callable[[_HandlerType], _HandlerType] + + +class RouteTableDef(Sequence[AbstractRouteDef]): + """Route definition table""" + + def __init__(self) -> None: + self._items: List[AbstractRouteDef] = [] + + def __repr__(self) -> str: + return f"" + + @overload + def __getitem__(self, index: int) -> AbstractRouteDef: ... + + @overload + def __getitem__(self, index: slice) -> List[AbstractRouteDef]: ... + + def __getitem__(self, index): # type: ignore[no-untyped-def] + return self._items[index] + + def __iter__(self) -> Iterator[AbstractRouteDef]: + return iter(self._items) + + def __len__(self) -> int: + return len(self._items) + + def __contains__(self, item: object) -> bool: + return item in self._items + + def route(self, method: str, path: str, **kwargs: Any) -> _Deco: + def inner(handler: _HandlerType) -> _HandlerType: + self._items.append(RouteDef(method, path, handler, kwargs)) + return handler + + return inner + + def head(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_HEAD, path, **kwargs) + + def get(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_GET, path, **kwargs) + + def post(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_POST, path, **kwargs) + + def put(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_PUT, path, **kwargs) + + def patch(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_PATCH, path, **kwargs) + + def delete(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_DELETE, path, **kwargs) + + def options(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_OPTIONS, path, **kwargs) + + def view(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_ANY, path, **kwargs) + + def static(self, prefix: str, path: PathLike, **kwargs: Any) -> None: + self._items.append(StaticDef(prefix, path, kwargs)) diff --git a/env/Lib/site-packages/aiohttp/web_runner.py b/env/Lib/site-packages/aiohttp/web_runner.py new file mode 100644 index 0000000..2fe229c --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_runner.py @@ -0,0 +1,397 @@ +import asyncio +import signal +import socket +import warnings +from abc import ABC, abstractmethod +from typing import Any, List, Optional, Set + +from yarl import URL + +from .typedefs import PathLike +from .web_app import Application +from .web_server import Server + +try: + from ssl import SSLContext +except ImportError: + SSLContext = object # type: ignore[misc,assignment] + + +__all__ = ( + "BaseSite", + "TCPSite", + "UnixSite", + "NamedPipeSite", + "SockSite", + "BaseRunner", + "AppRunner", + "ServerRunner", + "GracefulExit", +) + + +class GracefulExit(SystemExit): + code = 1 + + +def _raise_graceful_exit() -> None: + raise GracefulExit() + + +class BaseSite(ABC): + __slots__ = ("_runner", "_ssl_context", "_backlog", "_server") + + def __init__( + self, + runner: "BaseRunner", + *, + shutdown_timeout: float = 60.0, + ssl_context: Optional[SSLContext] = None, + backlog: int = 128, + ) -> None: + if runner.server is None: + raise RuntimeError("Call runner.setup() before making a site") + if shutdown_timeout != 60.0: + msg = "shutdown_timeout should be set on BaseRunner" + warnings.warn(msg, DeprecationWarning, stacklevel=2) + runner._shutdown_timeout = shutdown_timeout + self._runner = runner + self._ssl_context = ssl_context + self._backlog = backlog + self._server: Optional[asyncio.AbstractServer] = None + + @property + @abstractmethod + def name(self) -> str: + pass # pragma: no cover + + @abstractmethod + async def start(self) -> None: + self._runner._reg_site(self) + + async def stop(self) -> None: + self._runner._check_site(self) + if self._server is not None: # Maybe not started yet + self._server.close() + + self._runner._unreg_site(self) + + +class TCPSite(BaseSite): + __slots__ = ("_host", "_port", "_reuse_address", "_reuse_port") + + def __init__( + self, + runner: "BaseRunner", + host: Optional[str] = None, + port: Optional[int] = None, + *, + shutdown_timeout: float = 60.0, + ssl_context: Optional[SSLContext] = None, + backlog: int = 128, + reuse_address: Optional[bool] = None, + reuse_port: Optional[bool] = None, + ) -> None: + super().__init__( + runner, + shutdown_timeout=shutdown_timeout, + ssl_context=ssl_context, + backlog=backlog, + ) + self._host = host + if port is None: + port = 8443 if self._ssl_context else 8080 + self._port = port + self._reuse_address = reuse_address + self._reuse_port = reuse_port + + @property + def name(self) -> str: + scheme = "https" if self._ssl_context else "http" + host = "0.0.0.0" if self._host is None else self._host + return str(URL.build(scheme=scheme, host=host, port=self._port)) + + async def start(self) -> None: + await super().start() + loop = asyncio.get_event_loop() + server = self._runner.server + assert server is not None + self._server = await loop.create_server( + server, + self._host, + self._port, + ssl=self._ssl_context, + backlog=self._backlog, + reuse_address=self._reuse_address, + reuse_port=self._reuse_port, + ) + + +class UnixSite(BaseSite): + __slots__ = ("_path",) + + def __init__( + self, + runner: "BaseRunner", + path: PathLike, + *, + shutdown_timeout: float = 60.0, + ssl_context: Optional[SSLContext] = None, + backlog: int = 128, + ) -> None: + super().__init__( + runner, + shutdown_timeout=shutdown_timeout, + ssl_context=ssl_context, + backlog=backlog, + ) + self._path = path + + @property + def name(self) -> str: + scheme = "https" if self._ssl_context else "http" + return f"{scheme}://unix:{self._path}:" + + async def start(self) -> None: + await super().start() + loop = asyncio.get_event_loop() + server = self._runner.server + assert server is not None + self._server = await loop.create_unix_server( + server, + self._path, + ssl=self._ssl_context, + backlog=self._backlog, + ) + + +class NamedPipeSite(BaseSite): + __slots__ = ("_path",) + + def __init__( + self, runner: "BaseRunner", path: str, *, shutdown_timeout: float = 60.0 + ) -> None: + loop = asyncio.get_event_loop() + if not isinstance( + loop, asyncio.ProactorEventLoop # type: ignore[attr-defined] + ): + raise RuntimeError( + "Named Pipes only available in proactor" "loop under windows" + ) + super().__init__(runner, shutdown_timeout=shutdown_timeout) + self._path = path + + @property + def name(self) -> str: + return self._path + + async def start(self) -> None: + await super().start() + loop = asyncio.get_event_loop() + server = self._runner.server + assert server is not None + _server = await loop.start_serving_pipe( # type: ignore[attr-defined] + server, self._path + ) + self._server = _server[0] + + +class SockSite(BaseSite): + __slots__ = ("_sock", "_name") + + def __init__( + self, + runner: "BaseRunner", + sock: socket.socket, + *, + shutdown_timeout: float = 60.0, + ssl_context: Optional[SSLContext] = None, + backlog: int = 128, + ) -> None: + super().__init__( + runner, + shutdown_timeout=shutdown_timeout, + ssl_context=ssl_context, + backlog=backlog, + ) + self._sock = sock + scheme = "https" if self._ssl_context else "http" + if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: + name = f"{scheme}://unix:{sock.getsockname()}:" + else: + host, port = sock.getsockname()[:2] + name = str(URL.build(scheme=scheme, host=host, port=port)) + self._name = name + + @property + def name(self) -> str: + return self._name + + async def start(self) -> None: + await super().start() + loop = asyncio.get_event_loop() + server = self._runner.server + assert server is not None + self._server = await loop.create_server( + server, sock=self._sock, ssl=self._ssl_context, backlog=self._backlog + ) + + +class BaseRunner(ABC): + __slots__ = ("_handle_signals", "_kwargs", "_server", "_sites", "_shutdown_timeout") + + def __init__( + self, + *, + handle_signals: bool = False, + shutdown_timeout: float = 60.0, + **kwargs: Any, + ) -> None: + self._handle_signals = handle_signals + self._kwargs = kwargs + self._server: Optional[Server] = None + self._sites: List[BaseSite] = [] + self._shutdown_timeout = shutdown_timeout + + @property + def server(self) -> Optional[Server]: + return self._server + + @property + def addresses(self) -> List[Any]: + ret: List[Any] = [] + for site in self._sites: + server = site._server + if server is not None: + sockets = server.sockets # type: ignore[attr-defined] + if sockets is not None: + for sock in sockets: + ret.append(sock.getsockname()) + return ret + + @property + def sites(self) -> Set[BaseSite]: + return set(self._sites) + + async def setup(self) -> None: + loop = asyncio.get_event_loop() + + if self._handle_signals: + try: + loop.add_signal_handler(signal.SIGINT, _raise_graceful_exit) + loop.add_signal_handler(signal.SIGTERM, _raise_graceful_exit) + except NotImplementedError: # pragma: no cover + # add_signal_handler is not implemented on Windows + pass + + self._server = await self._make_server() + + @abstractmethod + async def shutdown(self) -> None: + """Call any shutdown hooks to help server close gracefully.""" + + async def cleanup(self) -> None: + # The loop over sites is intentional, an exception on gather() + # leaves self._sites in unpredictable state. + # The loop guaranties that a site is either deleted on success or + # still present on failure + for site in list(self._sites): + await site.stop() + + if self._server: # If setup succeeded + # Yield to event loop to ensure incoming requests prior to stopping the sites + # have all started to be handled before we proceed to close idle connections. + await asyncio.sleep(0) + self._server.pre_shutdown() + await self.shutdown() + await self._server.shutdown(self._shutdown_timeout) + await self._cleanup_server() + + self._server = None + if self._handle_signals: + loop = asyncio.get_running_loop() + try: + loop.remove_signal_handler(signal.SIGINT) + loop.remove_signal_handler(signal.SIGTERM) + except NotImplementedError: # pragma: no cover + # remove_signal_handler is not implemented on Windows + pass + + @abstractmethod + async def _make_server(self) -> Server: + pass # pragma: no cover + + @abstractmethod + async def _cleanup_server(self) -> None: + pass # pragma: no cover + + def _reg_site(self, site: BaseSite) -> None: + if site in self._sites: + raise RuntimeError(f"Site {site} is already registered in runner {self}") + self._sites.append(site) + + def _check_site(self, site: BaseSite) -> None: + if site not in self._sites: + raise RuntimeError(f"Site {site} is not registered in runner {self}") + + def _unreg_site(self, site: BaseSite) -> None: + if site not in self._sites: + raise RuntimeError(f"Site {site} is not registered in runner {self}") + self._sites.remove(site) + + +class ServerRunner(BaseRunner): + """Low-level web server runner""" + + __slots__ = ("_web_server",) + + def __init__( + self, web_server: Server, *, handle_signals: bool = False, **kwargs: Any + ) -> None: + super().__init__(handle_signals=handle_signals, **kwargs) + self._web_server = web_server + + async def shutdown(self) -> None: + pass + + async def _make_server(self) -> Server: + return self._web_server + + async def _cleanup_server(self) -> None: + pass + + +class AppRunner(BaseRunner): + """Web Application runner""" + + __slots__ = ("_app",) + + def __init__( + self, app: Application, *, handle_signals: bool = False, **kwargs: Any + ) -> None: + super().__init__(handle_signals=handle_signals, **kwargs) + if not isinstance(app, Application): + raise TypeError( + "The first argument should be web.Application " + "instance, got {!r}".format(app) + ) + self._app = app + + @property + def app(self) -> Application: + return self._app + + async def shutdown(self) -> None: + await self._app.shutdown() + + async def _make_server(self) -> Server: + loop = asyncio.get_event_loop() + self._app._set_loop(loop) + self._app.on_startup.freeze() + await self._app.startup() + self._app.freeze() + + return self._app._make_handler(loop=loop, **self._kwargs) + + async def _cleanup_server(self) -> None: + await self._app.cleanup() diff --git a/env/Lib/site-packages/aiohttp/web_server.py b/env/Lib/site-packages/aiohttp/web_server.py new file mode 100644 index 0000000..ffc198d --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_server.py @@ -0,0 +1,82 @@ +"""Low level HTTP server.""" + +import asyncio +from typing import Any, Awaitable, Callable, Dict, List, Optional # noqa + +from .abc import AbstractStreamWriter +from .http_parser import RawRequestMessage +from .streams import StreamReader +from .web_protocol import RequestHandler, _RequestFactory, _RequestHandler +from .web_request import BaseRequest + +__all__ = ("Server",) + + +class Server: + def __init__( + self, + handler: _RequestHandler, + *, + request_factory: Optional[_RequestFactory] = None, + handler_cancellation: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, + **kwargs: Any + ) -> None: + self._loop = loop or asyncio.get_running_loop() + self._connections: Dict[RequestHandler, asyncio.Transport] = {} + self._kwargs = kwargs + self.requests_count = 0 + self.request_handler = handler + self.request_factory = request_factory or self._make_request + self.handler_cancellation = handler_cancellation + + @property + def connections(self) -> List[RequestHandler]: + return list(self._connections.keys()) + + def connection_made( + self, handler: RequestHandler, transport: asyncio.Transport + ) -> None: + self._connections[handler] = transport + + def connection_lost( + self, handler: RequestHandler, exc: Optional[BaseException] = None + ) -> None: + if handler in self._connections: + if handler._task_handler: + handler._task_handler.add_done_callback( + lambda f: self._connections.pop(handler, None) + ) + else: + del self._connections[handler] + + def _make_request( + self, + message: RawRequestMessage, + payload: StreamReader, + protocol: RequestHandler, + writer: AbstractStreamWriter, + task: "asyncio.Task[None]", + ) -> BaseRequest: + return BaseRequest(message, payload, protocol, writer, task, self._loop) + + def pre_shutdown(self) -> None: + for conn in self._connections: + conn.close() + + async def shutdown(self, timeout: Optional[float] = None) -> None: + coros = (conn.shutdown(timeout) for conn in self._connections) + await asyncio.gather(*coros) + self._connections.clear() + + def __call__(self) -> RequestHandler: + try: + return RequestHandler(self, loop=self._loop, **self._kwargs) + except TypeError: + # Failsafe creation: remove all custom handler_args + kwargs = { + k: v + for k, v in self._kwargs.items() + if k in ["debug", "access_log_class"] + } + return RequestHandler(self, loop=self._loop, **kwargs) diff --git a/env/Lib/site-packages/aiohttp/web_urldispatcher.py b/env/Lib/site-packages/aiohttp/web_urldispatcher.py new file mode 100644 index 0000000..558fb7d --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_urldispatcher.py @@ -0,0 +1,1302 @@ +import abc +import asyncio +import base64 +import functools +import hashlib +import html +import inspect +import keyword +import os +import re +import sys +import warnings +from contextlib import contextmanager +from functools import wraps +from pathlib import Path +from types import MappingProxyType +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Container, + Dict, + Final, + Generator, + Iterable, + Iterator, + List, + Mapping, + NoReturn, + Optional, + Pattern, + Set, + Sized, + Tuple, + Type, + TypedDict, + Union, + cast, +) + +from yarl import URL, __version__ as yarl_version # type: ignore[attr-defined] + +from . import hdrs +from .abc import AbstractMatchInfo, AbstractRouter, AbstractView +from .helpers import DEBUG +from .http import HttpVersion11 +from .typedefs import Handler, PathLike +from .web_exceptions import ( + HTTPException, + HTTPExpectationFailed, + HTTPForbidden, + HTTPMethodNotAllowed, + HTTPNotFound, +) +from .web_fileresponse import FileResponse +from .web_request import Request +from .web_response import Response, StreamResponse +from .web_routedef import AbstractRouteDef + +__all__ = ( + "UrlDispatcher", + "UrlMappingMatchInfo", + "AbstractResource", + "Resource", + "PlainResource", + "DynamicResource", + "AbstractRoute", + "ResourceRoute", + "StaticResource", + "View", +) + + +if TYPE_CHECKING: + from .web_app import Application + + BaseDict = Dict[str, str] +else: + BaseDict = dict + +CIRCULAR_SYMLINK_ERROR = ( + (OSError,) + if sys.version_info < (3, 10) and sys.platform.startswith("win32") + else (RuntimeError,) if sys.version_info < (3, 13) else () +) + +YARL_VERSION: Final[Tuple[int, ...]] = tuple(map(int, yarl_version.split(".")[:2])) + +HTTP_METHOD_RE: Final[Pattern[str]] = re.compile( + r"^[0-9A-Za-z!#\$%&'\*\+\-\.\^_`\|~]+$" +) +ROUTE_RE: Final[Pattern[str]] = re.compile( + r"(\{[_a-zA-Z][^{}]*(?:\{[^{}]*\}[^{}]*)*\})" +) +PATH_SEP: Final[str] = re.escape("/") + + +_ExpectHandler = Callable[[Request], Awaitable[Optional[StreamResponse]]] +_Resolve = Tuple[Optional["UrlMappingMatchInfo"], Set[str]] + +html_escape = functools.partial(html.escape, quote=True) + + +class _InfoDict(TypedDict, total=False): + path: str + + formatter: str + pattern: Pattern[str] + + directory: Path + prefix: str + routes: Mapping[str, "AbstractRoute"] + + app: "Application" + + domain: str + + rule: "AbstractRuleMatching" + + http_exception: HTTPException + + +class AbstractResource(Sized, Iterable["AbstractRoute"]): + def __init__(self, *, name: Optional[str] = None) -> None: + self._name = name + + @property + def name(self) -> Optional[str]: + return self._name + + @property + @abc.abstractmethod + def canonical(self) -> str: + """Exposes the resource's canonical path. + + For example '/foo/bar/{name}' + + """ + + @abc.abstractmethod # pragma: no branch + def url_for(self, **kwargs: str) -> URL: + """Construct url for resource with additional params.""" + + @abc.abstractmethod # pragma: no branch + async def resolve(self, request: Request) -> _Resolve: + """Resolve resource. + + Return (UrlMappingMatchInfo, allowed_methods) pair. + """ + + @abc.abstractmethod + def add_prefix(self, prefix: str) -> None: + """Add a prefix to processed URLs. + + Required for subapplications support. + """ + + @abc.abstractmethod + def get_info(self) -> _InfoDict: + """Return a dict with additional info useful for introspection""" + + def freeze(self) -> None: + pass + + @abc.abstractmethod + def raw_match(self, path: str) -> bool: + """Perform a raw match against path""" + + +class AbstractRoute(abc.ABC): + def __init__( + self, + method: str, + handler: Union[Handler, Type[AbstractView]], + *, + expect_handler: Optional[_ExpectHandler] = None, + resource: Optional[AbstractResource] = None, + ) -> None: + + if expect_handler is None: + expect_handler = _default_expect_handler + + assert asyncio.iscoroutinefunction( + expect_handler + ), f"Coroutine is expected, got {expect_handler!r}" + + method = method.upper() + if not HTTP_METHOD_RE.match(method): + raise ValueError(f"{method} is not allowed HTTP method") + + assert callable(handler), handler + if asyncio.iscoroutinefunction(handler): + pass + elif inspect.isgeneratorfunction(handler): + warnings.warn( + "Bare generators are deprecated, " "use @coroutine wrapper", + DeprecationWarning, + ) + elif isinstance(handler, type) and issubclass(handler, AbstractView): + pass + else: + warnings.warn( + "Bare functions are deprecated, " "use async ones", DeprecationWarning + ) + + @wraps(handler) + async def handler_wrapper(request: Request) -> StreamResponse: + result = old_handler(request) # type: ignore[call-arg] + if asyncio.iscoroutine(result): + result = await result + assert isinstance(result, StreamResponse) + return result + + old_handler = handler + handler = handler_wrapper + + self._method = method + self._handler = handler + self._expect_handler = expect_handler + self._resource = resource + + @property + def method(self) -> str: + return self._method + + @property + def handler(self) -> Handler: + return self._handler + + @property + @abc.abstractmethod + def name(self) -> Optional[str]: + """Optional route's name, always equals to resource's name.""" + + @property + def resource(self) -> Optional[AbstractResource]: + return self._resource + + @abc.abstractmethod + def get_info(self) -> _InfoDict: + """Return a dict with additional info useful for introspection""" + + @abc.abstractmethod # pragma: no branch + def url_for(self, *args: str, **kwargs: str) -> URL: + """Construct url for route with additional params.""" + + async def handle_expect_header(self, request: Request) -> Optional[StreamResponse]: + return await self._expect_handler(request) + + +class UrlMappingMatchInfo(BaseDict, AbstractMatchInfo): + def __init__(self, match_dict: Dict[str, str], route: AbstractRoute): + super().__init__(match_dict) + self._route = route + self._apps: List[Application] = [] + self._current_app: Optional[Application] = None + self._frozen = False + + @property + def handler(self) -> Handler: + return self._route.handler + + @property + def route(self) -> AbstractRoute: + return self._route + + @property + def expect_handler(self) -> _ExpectHandler: + return self._route.handle_expect_header + + @property + def http_exception(self) -> Optional[HTTPException]: + return None + + def get_info(self) -> _InfoDict: # type: ignore[override] + return self._route.get_info() + + @property + def apps(self) -> Tuple["Application", ...]: + return tuple(self._apps) + + def add_app(self, app: "Application") -> None: + if self._frozen: + raise RuntimeError("Cannot change apps stack after .freeze() call") + if self._current_app is None: + self._current_app = app + self._apps.insert(0, app) + + @property + def current_app(self) -> "Application": + app = self._current_app + assert app is not None + return app + + @contextmanager + def set_current_app(self, app: "Application") -> Generator[None, None, None]: + if DEBUG: # pragma: no cover + if app not in self._apps: + raise RuntimeError( + "Expected one of the following apps {!r}, got {!r}".format( + self._apps, app + ) + ) + prev = self._current_app + self._current_app = app + try: + yield + finally: + self._current_app = prev + + def freeze(self) -> None: + self._frozen = True + + def __repr__(self) -> str: + return f"" + + +class MatchInfoError(UrlMappingMatchInfo): + def __init__(self, http_exception: HTTPException) -> None: + self._exception = http_exception + super().__init__({}, SystemRoute(self._exception)) + + @property + def http_exception(self) -> HTTPException: + return self._exception + + def __repr__(self) -> str: + return "".format( + self._exception.status, self._exception.reason + ) + + +async def _default_expect_handler(request: Request) -> None: + """Default handler for Expect header. + + Just send "100 Continue" to client. + raise HTTPExpectationFailed if value of header is not "100-continue" + """ + expect = request.headers.get(hdrs.EXPECT, "") + if request.version == HttpVersion11: + if expect.lower() == "100-continue": + await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n") + else: + raise HTTPExpectationFailed(text="Unknown Expect: %s" % expect) + + +class Resource(AbstractResource): + def __init__(self, *, name: Optional[str] = None) -> None: + super().__init__(name=name) + self._routes: List[ResourceRoute] = [] + + def add_route( + self, + method: str, + handler: Union[Type[AbstractView], Handler], + *, + expect_handler: Optional[_ExpectHandler] = None, + ) -> "ResourceRoute": + + for route_obj in self._routes: + if route_obj.method == method or route_obj.method == hdrs.METH_ANY: + raise RuntimeError( + "Added route will never be executed, " + "method {route.method} is already " + "registered".format(route=route_obj) + ) + + route_obj = ResourceRoute(method, handler, self, expect_handler=expect_handler) + self.register_route(route_obj) + return route_obj + + def register_route(self, route: "ResourceRoute") -> None: + assert isinstance( + route, ResourceRoute + ), f"Instance of Route class is required, got {route!r}" + self._routes.append(route) + + async def resolve(self, request: Request) -> _Resolve: + allowed_methods: Set[str] = set() + + match_dict = self._match(request.rel_url.raw_path) + if match_dict is None: + return None, allowed_methods + + for route_obj in self._routes: + route_method = route_obj.method + allowed_methods.add(route_method) + + if route_method == request.method or route_method == hdrs.METH_ANY: + return (UrlMappingMatchInfo(match_dict, route_obj), allowed_methods) + else: + return None, allowed_methods + + @abc.abstractmethod + def _match(self, path: str) -> Optional[Dict[str, str]]: + pass # pragma: no cover + + def __len__(self) -> int: + return len(self._routes) + + def __iter__(self) -> Iterator["ResourceRoute"]: + return iter(self._routes) + + # TODO: implement all abstract methods + + +class PlainResource(Resource): + def __init__(self, path: str, *, name: Optional[str] = None) -> None: + super().__init__(name=name) + assert not path or path.startswith("/") + self._path = path + + @property + def canonical(self) -> str: + return self._path + + def freeze(self) -> None: + if not self._path: + self._path = "/" + + def add_prefix(self, prefix: str) -> None: + assert prefix.startswith("/") + assert not prefix.endswith("/") + assert len(prefix) > 1 + self._path = prefix + self._path + + def _match(self, path: str) -> Optional[Dict[str, str]]: + # string comparison is about 10 times faster than regexp matching + if self._path == path: + return {} + else: + return None + + def raw_match(self, path: str) -> bool: + return self._path == path + + def get_info(self) -> _InfoDict: + return {"path": self._path} + + def url_for(self) -> URL: # type: ignore[override] + return URL.build(path=self._path, encoded=True) + + def __repr__(self) -> str: + name = "'" + self.name + "' " if self.name is not None else "" + return f"" + + +class DynamicResource(Resource): + + DYN = re.compile(r"\{(?P[_a-zA-Z][_a-zA-Z0-9]*)\}") + DYN_WITH_RE = re.compile(r"\{(?P[_a-zA-Z][_a-zA-Z0-9]*):(?P.+)\}") + GOOD = r"[^{}/]+" + + def __init__(self, path: str, *, name: Optional[str] = None) -> None: + super().__init__(name=name) + pattern = "" + formatter = "" + for part in ROUTE_RE.split(path): + match = self.DYN.fullmatch(part) + if match: + pattern += "(?P<{}>{})".format(match.group("var"), self.GOOD) + formatter += "{" + match.group("var") + "}" + continue + + match = self.DYN_WITH_RE.fullmatch(part) + if match: + pattern += "(?P<{var}>{re})".format(**match.groupdict()) + formatter += "{" + match.group("var") + "}" + continue + + if "{" in part or "}" in part: + raise ValueError(f"Invalid path '{path}'['{part}']") + + part = _requote_path(part) + formatter += part + pattern += re.escape(part) + + try: + compiled = re.compile(pattern) + except re.error as exc: + raise ValueError(f"Bad pattern '{pattern}': {exc}") from None + assert compiled.pattern.startswith(PATH_SEP) + assert formatter.startswith("/") + self._pattern = compiled + self._formatter = formatter + + @property + def canonical(self) -> str: + return self._formatter + + def add_prefix(self, prefix: str) -> None: + assert prefix.startswith("/") + assert not prefix.endswith("/") + assert len(prefix) > 1 + self._pattern = re.compile(re.escape(prefix) + self._pattern.pattern) + self._formatter = prefix + self._formatter + + def _match(self, path: str) -> Optional[Dict[str, str]]: + match = self._pattern.fullmatch(path) + if match is None: + return None + else: + return { + key: _unquote_path(value) for key, value in match.groupdict().items() + } + + def raw_match(self, path: str) -> bool: + return self._formatter == path + + def get_info(self) -> _InfoDict: + return {"formatter": self._formatter, "pattern": self._pattern} + + def url_for(self, **parts: str) -> URL: + url = self._formatter.format_map({k: _quote_path(v) for k, v in parts.items()}) + return URL.build(path=url, encoded=True) + + def __repr__(self) -> str: + name = "'" + self.name + "' " if self.name is not None else "" + return "".format( + name=name, formatter=self._formatter + ) + + +class PrefixResource(AbstractResource): + def __init__(self, prefix: str, *, name: Optional[str] = None) -> None: + assert not prefix or prefix.startswith("/"), prefix + assert prefix in ("", "/") or not prefix.endswith("/"), prefix + super().__init__(name=name) + self._prefix = _requote_path(prefix) + self._prefix2 = self._prefix + "/" + + @property + def canonical(self) -> str: + return self._prefix + + def add_prefix(self, prefix: str) -> None: + assert prefix.startswith("/") + assert not prefix.endswith("/") + assert len(prefix) > 1 + self._prefix = prefix + self._prefix + self._prefix2 = self._prefix + "/" + + def raw_match(self, prefix: str) -> bool: + return False + + # TODO: impl missing abstract methods + + +class StaticResource(PrefixResource): + VERSION_KEY = "v" + + def __init__( + self, + prefix: str, + directory: PathLike, + *, + name: Optional[str] = None, + expect_handler: Optional[_ExpectHandler] = None, + chunk_size: int = 256 * 1024, + show_index: bool = False, + follow_symlinks: bool = False, + append_version: bool = False, + ) -> None: + super().__init__(prefix, name=name) + try: + directory = Path(directory).expanduser().resolve(strict=True) + except FileNotFoundError as error: + raise ValueError(f"'{directory}' does not exist") from error + if not directory.is_dir(): + raise ValueError(f"'{directory}' is not a directory") + self._directory = directory + self._show_index = show_index + self._chunk_size = chunk_size + self._follow_symlinks = follow_symlinks + self._expect_handler = expect_handler + self._append_version = append_version + + self._routes = { + "GET": ResourceRoute( + "GET", self._handle, self, expect_handler=expect_handler + ), + "HEAD": ResourceRoute( + "HEAD", self._handle, self, expect_handler=expect_handler + ), + } + + def url_for( # type: ignore[override] + self, + *, + filename: PathLike, + append_version: Optional[bool] = None, + ) -> URL: + if append_version is None: + append_version = self._append_version + filename = str(filename).lstrip("/") + + url = URL.build(path=self._prefix, encoded=True) + # filename is not encoded + if YARL_VERSION < (1, 6): + url = url / filename.replace("%", "%25") + else: + url = url / filename + + if append_version: + unresolved_path = self._directory.joinpath(filename) + try: + if self._follow_symlinks: + normalized_path = Path(os.path.normpath(unresolved_path)) + normalized_path.relative_to(self._directory) + filepath = normalized_path.resolve() + else: + filepath = unresolved_path.resolve() + filepath.relative_to(self._directory) + except (ValueError, FileNotFoundError): + # ValueError for case when path point to symlink + # with follow_symlinks is False + return url # relatively safe + if filepath.is_file(): + # TODO cache file content + # with file watcher for cache invalidation + with filepath.open("rb") as f: + file_bytes = f.read() + h = self._get_file_hash(file_bytes) + url = url.with_query({self.VERSION_KEY: h}) + return url + return url + + @staticmethod + def _get_file_hash(byte_array: bytes) -> str: + m = hashlib.sha256() # todo sha256 can be configurable param + m.update(byte_array) + b64 = base64.urlsafe_b64encode(m.digest()) + return b64.decode("ascii") + + def get_info(self) -> _InfoDict: + return { + "directory": self._directory, + "prefix": self._prefix, + "routes": self._routes, + } + + def set_options_route(self, handler: Handler) -> None: + if "OPTIONS" in self._routes: + raise RuntimeError("OPTIONS route was set already") + self._routes["OPTIONS"] = ResourceRoute( + "OPTIONS", handler, self, expect_handler=self._expect_handler + ) + + async def resolve(self, request: Request) -> _Resolve: + path = request.rel_url.raw_path + method = request.method + allowed_methods = set(self._routes) + if not path.startswith(self._prefix2) and path != self._prefix: + return None, set() + + if method not in allowed_methods: + return None, allowed_methods + + match_dict = {"filename": _unquote_path(path[len(self._prefix) + 1 :])} + return (UrlMappingMatchInfo(match_dict, self._routes[method]), allowed_methods) + + def __len__(self) -> int: + return len(self._routes) + + def __iter__(self) -> Iterator[AbstractRoute]: + return iter(self._routes.values()) + + async def _handle(self, request: Request) -> StreamResponse: + rel_url = request.match_info["filename"] + filename = Path(rel_url) + if filename.anchor: + # rel_url is an absolute name like + # /static/\\machine_name\c$ or /static/D:\path + # where the static dir is totally different + raise HTTPForbidden() + + unresolved_path = self._directory.joinpath(filename) + loop = asyncio.get_running_loop() + return await loop.run_in_executor( + None, self._resolve_path_to_response, unresolved_path + ) + + def _resolve_path_to_response(self, unresolved_path: Path) -> StreamResponse: + """Take the unresolved path and query the file system to form a response.""" + # Check for access outside the root directory. For follow symlinks, URI + # cannot traverse out, but symlinks can. Otherwise, no access outside + # root is permitted. + try: + if self._follow_symlinks: + normalized_path = Path(os.path.normpath(unresolved_path)) + normalized_path.relative_to(self._directory) + file_path = normalized_path.resolve() + else: + file_path = unresolved_path.resolve() + file_path.relative_to(self._directory) + except (ValueError, *CIRCULAR_SYMLINK_ERROR) as error: + # ValueError is raised for the relative check. Circular symlinks + # raise here on resolving for python < 3.13. + raise HTTPNotFound() from error + + # if path is a directory, return the contents if permitted. Note the + # directory check will raise if a segment is not readable. + try: + if file_path.is_dir(): + if self._show_index: + return Response( + text=self._directory_as_html(file_path), + content_type="text/html", + ) + else: + raise HTTPForbidden() + except PermissionError as error: + raise HTTPForbidden() from error + + # Return the file response, which handles all other checks. + return FileResponse(file_path, chunk_size=self._chunk_size) + + def _directory_as_html(self, dir_path: Path) -> str: + """returns directory's index as html.""" + assert dir_path.is_dir() + + relative_path_to_dir = dir_path.relative_to(self._directory).as_posix() + index_of = f"Index of /{html_escape(relative_path_to_dir)}" + h1 = f"

{index_of}

" + + index_list = [] + dir_index = dir_path.iterdir() + for _file in sorted(dir_index): + # show file url as relative to static path + rel_path = _file.relative_to(self._directory).as_posix() + quoted_file_url = _quote_path(f"{self._prefix}/{rel_path}") + + # if file is a directory, add '/' to the end of the name + if _file.is_dir(): + file_name = f"{_file.name}/" + else: + file_name = _file.name + + index_list.append( + f'
  • {html_escape(file_name)}
  • ' + ) + ul = "
      \n{}\n
    ".format("\n".join(index_list)) + body = f"\n{h1}\n{ul}\n" + + head_str = f"\n{index_of}\n" + html = f"\n{head_str}\n{body}\n" + + return html + + def __repr__(self) -> str: + name = "'" + self.name + "'" if self.name is not None else "" + return " {directory!r}>".format( + name=name, path=self._prefix, directory=self._directory + ) + + +class PrefixedSubAppResource(PrefixResource): + def __init__(self, prefix: str, app: "Application") -> None: + super().__init__(prefix) + self._app = app + self._add_prefix_to_resources(prefix) + + def add_prefix(self, prefix: str) -> None: + super().add_prefix(prefix) + self._add_prefix_to_resources(prefix) + + def _add_prefix_to_resources(self, prefix: str) -> None: + router = self._app.router + for resource in router.resources(): + # Since the canonical path of a resource is about + # to change, we need to unindex it and then reindex + router.unindex_resource(resource) + resource.add_prefix(prefix) + router.index_resource(resource) + + def url_for(self, *args: str, **kwargs: str) -> URL: + raise RuntimeError(".url_for() is not supported " "by sub-application root") + + def get_info(self) -> _InfoDict: + return {"app": self._app, "prefix": self._prefix} + + async def resolve(self, request: Request) -> _Resolve: + match_info = await self._app.router.resolve(request) + match_info.add_app(self._app) + if isinstance(match_info.http_exception, HTTPMethodNotAllowed): + methods = match_info.http_exception.allowed_methods + else: + methods = set() + return match_info, methods + + def __len__(self) -> int: + return len(self._app.router.routes()) + + def __iter__(self) -> Iterator[AbstractRoute]: + return iter(self._app.router.routes()) + + def __repr__(self) -> str: + return " {app!r}>".format( + prefix=self._prefix, app=self._app + ) + + +class AbstractRuleMatching(abc.ABC): + @abc.abstractmethod # pragma: no branch + async def match(self, request: Request) -> bool: + """Return bool if the request satisfies the criteria""" + + @abc.abstractmethod # pragma: no branch + def get_info(self) -> _InfoDict: + """Return a dict with additional info useful for introspection""" + + @property + @abc.abstractmethod # pragma: no branch + def canonical(self) -> str: + """Return a str""" + + +class Domain(AbstractRuleMatching): + re_part = re.compile(r"(?!-)[a-z\d-]{1,63}(? None: + super().__init__() + self._domain = self.validation(domain) + + @property + def canonical(self) -> str: + return self._domain + + def validation(self, domain: str) -> str: + if not isinstance(domain, str): + raise TypeError("Domain must be str") + domain = domain.rstrip(".").lower() + if not domain: + raise ValueError("Domain cannot be empty") + elif "://" in domain: + raise ValueError("Scheme not supported") + url = URL("http://" + domain) + assert url.raw_host is not None + if not all(self.re_part.fullmatch(x) for x in url.raw_host.split(".")): + raise ValueError("Domain not valid") + if url.port == 80: + return url.raw_host + return f"{url.raw_host}:{url.port}" + + async def match(self, request: Request) -> bool: + host = request.headers.get(hdrs.HOST) + if not host: + return False + return self.match_domain(host) + + def match_domain(self, host: str) -> bool: + return host.lower() == self._domain + + def get_info(self) -> _InfoDict: + return {"domain": self._domain} + + +class MaskDomain(Domain): + re_part = re.compile(r"(?!-)[a-z\d\*-]{1,63}(? None: + super().__init__(domain) + mask = self._domain.replace(".", r"\.").replace("*", ".*") + self._mask = re.compile(mask) + + @property + def canonical(self) -> str: + return self._mask.pattern + + def match_domain(self, host: str) -> bool: + return self._mask.fullmatch(host) is not None + + +class MatchedSubAppResource(PrefixedSubAppResource): + def __init__(self, rule: AbstractRuleMatching, app: "Application") -> None: + AbstractResource.__init__(self) + self._prefix = "" + self._app = app + self._rule = rule + + @property + def canonical(self) -> str: + return self._rule.canonical + + def get_info(self) -> _InfoDict: + return {"app": self._app, "rule": self._rule} + + async def resolve(self, request: Request) -> _Resolve: + if not await self._rule.match(request): + return None, set() + match_info = await self._app.router.resolve(request) + match_info.add_app(self._app) + if isinstance(match_info.http_exception, HTTPMethodNotAllowed): + methods = match_info.http_exception.allowed_methods + else: + methods = set() + return match_info, methods + + def __repr__(self) -> str: + return " {app!r}>" "".format(app=self._app) + + +class ResourceRoute(AbstractRoute): + """A route with resource""" + + def __init__( + self, + method: str, + handler: Union[Handler, Type[AbstractView]], + resource: AbstractResource, + *, + expect_handler: Optional[_ExpectHandler] = None, + ) -> None: + super().__init__( + method, handler, expect_handler=expect_handler, resource=resource + ) + + def __repr__(self) -> str: + return " {handler!r}".format( + method=self.method, resource=self._resource, handler=self.handler + ) + + @property + def name(self) -> Optional[str]: + if self._resource is None: + return None + return self._resource.name + + def url_for(self, *args: str, **kwargs: str) -> URL: + """Construct url for route with additional params.""" + assert self._resource is not None + return self._resource.url_for(*args, **kwargs) + + def get_info(self) -> _InfoDict: + assert self._resource is not None + return self._resource.get_info() + + +class SystemRoute(AbstractRoute): + def __init__(self, http_exception: HTTPException) -> None: + super().__init__(hdrs.METH_ANY, self._handle) + self._http_exception = http_exception + + def url_for(self, *args: str, **kwargs: str) -> URL: + raise RuntimeError(".url_for() is not allowed for SystemRoute") + + @property + def name(self) -> Optional[str]: + return None + + def get_info(self) -> _InfoDict: + return {"http_exception": self._http_exception} + + async def _handle(self, request: Request) -> StreamResponse: + raise self._http_exception + + @property + def status(self) -> int: + return self._http_exception.status + + @property + def reason(self) -> str: + return self._http_exception.reason + + def __repr__(self) -> str: + return "".format(self=self) + + +class View(AbstractView): + async def _iter(self) -> StreamResponse: + if self.request.method not in hdrs.METH_ALL: + self._raise_allowed_methods() + method: Optional[Callable[[], Awaitable[StreamResponse]]] + method = getattr(self, self.request.method.lower(), None) + if method is None: + self._raise_allowed_methods() + ret = await method() + assert isinstance(ret, StreamResponse) + return ret + + def __await__(self) -> Generator[Any, None, StreamResponse]: + return self._iter().__await__() + + def _raise_allowed_methods(self) -> NoReturn: + allowed_methods = {m for m in hdrs.METH_ALL if hasattr(self, m.lower())} + raise HTTPMethodNotAllowed(self.request.method, allowed_methods) + + +class ResourcesView(Sized, Iterable[AbstractResource], Container[AbstractResource]): + def __init__(self, resources: List[AbstractResource]) -> None: + self._resources = resources + + def __len__(self) -> int: + return len(self._resources) + + def __iter__(self) -> Iterator[AbstractResource]: + yield from self._resources + + def __contains__(self, resource: object) -> bool: + return resource in self._resources + + +class RoutesView(Sized, Iterable[AbstractRoute], Container[AbstractRoute]): + def __init__(self, resources: List[AbstractResource]): + self._routes: List[AbstractRoute] = [] + for resource in resources: + for route in resource: + self._routes.append(route) + + def __len__(self) -> int: + return len(self._routes) + + def __iter__(self) -> Iterator[AbstractRoute]: + yield from self._routes + + def __contains__(self, route: object) -> bool: + return route in self._routes + + +class UrlDispatcher(AbstractRouter, Mapping[str, AbstractResource]): + + NAME_SPLIT_RE = re.compile(r"[.:-]") + + def __init__(self) -> None: + super().__init__() + self._resources: List[AbstractResource] = [] + self._named_resources: Dict[str, AbstractResource] = {} + self._resource_index: dict[str, list[AbstractResource]] = {} + self._matched_sub_app_resources: List[MatchedSubAppResource] = [] + + async def resolve(self, request: Request) -> UrlMappingMatchInfo: + resource_index = self._resource_index + allowed_methods: Set[str] = set() + + # Walk the url parts looking for candidates. We walk the url backwards + # to ensure the most explicit match is found first. If there are multiple + # candidates for a given url part because there are multiple resources + # registered for the same canonical path, we resolve them in a linear + # fashion to ensure registration order is respected. + url_part = request.rel_url.raw_path + while url_part: + for candidate in resource_index.get(url_part, ()): + match_dict, allowed = await candidate.resolve(request) + if match_dict is not None: + return match_dict + else: + allowed_methods |= allowed + if url_part == "/": + break + url_part = url_part.rpartition("/")[0] or "/" + + # + # We didn't find any candidates, so we'll try the matched sub-app + # resources which we have to walk in a linear fashion because they + # have regex/wildcard match rules and we cannot index them. + # + # For most cases we do not expect there to be many of these since + # currently they are only added by `add_domain` + # + for resource in self._matched_sub_app_resources: + match_dict, allowed = await resource.resolve(request) + if match_dict is not None: + return match_dict + else: + allowed_methods |= allowed + + if allowed_methods: + return MatchInfoError(HTTPMethodNotAllowed(request.method, allowed_methods)) + + return MatchInfoError(HTTPNotFound()) + + def __iter__(self) -> Iterator[str]: + return iter(self._named_resources) + + def __len__(self) -> int: + return len(self._named_resources) + + def __contains__(self, resource: object) -> bool: + return resource in self._named_resources + + def __getitem__(self, name: str) -> AbstractResource: + return self._named_resources[name] + + def resources(self) -> ResourcesView: + return ResourcesView(self._resources) + + def routes(self) -> RoutesView: + return RoutesView(self._resources) + + def named_resources(self) -> Mapping[str, AbstractResource]: + return MappingProxyType(self._named_resources) + + def register_resource(self, resource: AbstractResource) -> None: + assert isinstance( + resource, AbstractResource + ), f"Instance of AbstractResource class is required, got {resource!r}" + if self.frozen: + raise RuntimeError("Cannot register a resource into frozen router.") + + name = resource.name + + if name is not None: + parts = self.NAME_SPLIT_RE.split(name) + for part in parts: + if keyword.iskeyword(part): + raise ValueError( + f"Incorrect route name {name!r}, " + "python keywords cannot be used " + "for route name" + ) + if not part.isidentifier(): + raise ValueError( + "Incorrect route name {!r}, " + "the name should be a sequence of " + "python identifiers separated " + "by dash, dot or column".format(name) + ) + if name in self._named_resources: + raise ValueError( + "Duplicate {!r}, " + "already handled by {!r}".format(name, self._named_resources[name]) + ) + self._named_resources[name] = resource + self._resources.append(resource) + + if isinstance(resource, MatchedSubAppResource): + # We cannot index match sub-app resources because they have match rules + self._matched_sub_app_resources.append(resource) + else: + self.index_resource(resource) + + def _get_resource_index_key(self, resource: AbstractResource) -> str: + """Return a key to index the resource in the resource index.""" + if "{" in (index_key := resource.canonical): + # strip at the first { to allow for variables, and than + # rpartition at / to allow for variable parts in the path + # For example if the canonical path is `/core/locations{tail:.*}` + # the index key will be `/core` since index is based on the + # url parts split by `/` + index_key = index_key.partition("{")[0].rpartition("/")[0] + return index_key.rstrip("/") or "/" + + def index_resource(self, resource: AbstractResource) -> None: + """Add a resource to the resource index.""" + resource_key = self._get_resource_index_key(resource) + # There may be multiple resources for a canonical path + # so we keep them in a list to ensure that registration + # order is respected. + self._resource_index.setdefault(resource_key, []).append(resource) + + def unindex_resource(self, resource: AbstractResource) -> None: + """Remove a resource from the resource index.""" + resource_key = self._get_resource_index_key(resource) + self._resource_index[resource_key].remove(resource) + + def add_resource(self, path: str, *, name: Optional[str] = None) -> Resource: + if path and not path.startswith("/"): + raise ValueError("path should be started with / or be empty") + # Reuse last added resource if path and name are the same + if self._resources: + resource = self._resources[-1] + if resource.name == name and resource.raw_match(path): + return cast(Resource, resource) + if not ("{" in path or "}" in path or ROUTE_RE.search(path)): + resource = PlainResource(_requote_path(path), name=name) + self.register_resource(resource) + return resource + resource = DynamicResource(path, name=name) + self.register_resource(resource) + return resource + + def add_route( + self, + method: str, + path: str, + handler: Union[Handler, Type[AbstractView]], + *, + name: Optional[str] = None, + expect_handler: Optional[_ExpectHandler] = None, + ) -> AbstractRoute: + resource = self.add_resource(path, name=name) + return resource.add_route(method, handler, expect_handler=expect_handler) + + def add_static( + self, + prefix: str, + path: PathLike, + *, + name: Optional[str] = None, + expect_handler: Optional[_ExpectHandler] = None, + chunk_size: int = 256 * 1024, + show_index: bool = False, + follow_symlinks: bool = False, + append_version: bool = False, + ) -> AbstractResource: + """Add static files view. + + prefix - url prefix + path - folder with files + + """ + assert prefix.startswith("/") + if prefix.endswith("/"): + prefix = prefix[:-1] + resource = StaticResource( + prefix, + path, + name=name, + expect_handler=expect_handler, + chunk_size=chunk_size, + show_index=show_index, + follow_symlinks=follow_symlinks, + append_version=append_version, + ) + self.register_resource(resource) + return resource + + def add_head(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method HEAD.""" + return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs) + + def add_options(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method OPTIONS.""" + return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs) + + def add_get( + self, + path: str, + handler: Handler, + *, + name: Optional[str] = None, + allow_head: bool = True, + **kwargs: Any, + ) -> AbstractRoute: + """Shortcut for add_route with method GET. + + If allow_head is true, another + route is added allowing head requests to the same endpoint. + """ + resource = self.add_resource(path, name=name) + if allow_head: + resource.add_route(hdrs.METH_HEAD, handler, **kwargs) + return resource.add_route(hdrs.METH_GET, handler, **kwargs) + + def add_post(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method POST.""" + return self.add_route(hdrs.METH_POST, path, handler, **kwargs) + + def add_put(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method PUT.""" + return self.add_route(hdrs.METH_PUT, path, handler, **kwargs) + + def add_patch(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method PATCH.""" + return self.add_route(hdrs.METH_PATCH, path, handler, **kwargs) + + def add_delete(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method DELETE.""" + return self.add_route(hdrs.METH_DELETE, path, handler, **kwargs) + + def add_view( + self, path: str, handler: Type[AbstractView], **kwargs: Any + ) -> AbstractRoute: + """Shortcut for add_route with ANY methods for a class-based view.""" + return self.add_route(hdrs.METH_ANY, path, handler, **kwargs) + + def freeze(self) -> None: + super().freeze() + for resource in self._resources: + resource.freeze() + + def add_routes(self, routes: Iterable[AbstractRouteDef]) -> List[AbstractRoute]: + """Append routes to route table. + + Parameter should be a sequence of RouteDef objects. + + Returns a list of registered AbstractRoute instances. + """ + registered_routes = [] + for route_def in routes: + registered_routes.extend(route_def.register(self)) + return registered_routes + + +def _quote_path(value: str) -> str: + if YARL_VERSION < (1, 6): + value = value.replace("%", "%25") + return URL.build(path=value, encoded=False).raw_path + + +def _unquote_path(value: str) -> str: + return URL.build(path=value, encoded=True).path + + +def _requote_path(value: str) -> str: + # Quote non-ascii characters and other characters which must be quoted, + # but preserve existing %-sequences. + result = _quote_path(value) + if "%" in value: + result = result.replace("%25", "%") + return result diff --git a/env/Lib/site-packages/aiohttp/web_ws.py b/env/Lib/site-packages/aiohttp/web_ws.py new file mode 100644 index 0000000..3822230 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/web_ws.py @@ -0,0 +1,600 @@ +import asyncio +import base64 +import binascii +import hashlib +import json +import sys +from typing import Any, Final, Iterable, Optional, Tuple, cast + +import attr +from multidict import CIMultiDict + +from . import hdrs +from .abc import AbstractStreamWriter +from .helpers import calculate_timeout_when, set_exception, set_result +from .http import ( + WS_CLOSED_MESSAGE, + WS_CLOSING_MESSAGE, + WS_KEY, + WebSocketError, + WebSocketReader, + WebSocketWriter, + WSCloseCode, + WSMessage, + WSMsgType as WSMsgType, + ws_ext_gen, + ws_ext_parse, +) +from .log import ws_logger +from .streams import EofStream, FlowControlDataQueue +from .typedefs import JSONDecoder, JSONEncoder +from .web_exceptions import HTTPBadRequest, HTTPException +from .web_request import BaseRequest +from .web_response import StreamResponse + +if sys.version_info >= (3, 11): + import asyncio as async_timeout +else: + import async_timeout + +__all__ = ( + "WebSocketResponse", + "WebSocketReady", + "WSMsgType", +) + +THRESHOLD_CONNLOST_ACCESS: Final[int] = 5 + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class WebSocketReady: + ok: bool + protocol: Optional[str] + + def __bool__(self) -> bool: + return self.ok + + +class WebSocketResponse(StreamResponse): + + _length_check = False + + def __init__( + self, + *, + timeout: float = 10.0, + receive_timeout: Optional[float] = None, + autoclose: bool = True, + autoping: bool = True, + heartbeat: Optional[float] = None, + protocols: Iterable[str] = (), + compress: bool = True, + max_msg_size: int = 4 * 1024 * 1024, + ) -> None: + super().__init__(status=101) + self._protocols = protocols + self._ws_protocol: Optional[str] = None + self._writer: Optional[WebSocketWriter] = None + self._reader: Optional[FlowControlDataQueue[WSMessage]] = None + self._closed = False + self._closing = False + self._conn_lost = 0 + self._close_code: Optional[int] = None + self._loop: Optional[asyncio.AbstractEventLoop] = None + self._waiting: bool = False + self._close_wait: Optional[asyncio.Future[None]] = None + self._exception: Optional[BaseException] = None + self._timeout = timeout + self._receive_timeout = receive_timeout + self._autoclose = autoclose + self._autoping = autoping + self._heartbeat = heartbeat + self._heartbeat_when = 0.0 + self._heartbeat_cb: Optional[asyncio.TimerHandle] = None + if heartbeat is not None: + self._pong_heartbeat = heartbeat / 2.0 + self._pong_response_cb: Optional[asyncio.TimerHandle] = None + self._compress = compress + self._max_msg_size = max_msg_size + self._ping_task: Optional[asyncio.Task[None]] = None + + def _cancel_heartbeat(self) -> None: + self._cancel_pong_response_cb() + if self._heartbeat_cb is not None: + self._heartbeat_cb.cancel() + self._heartbeat_cb = None + if self._ping_task is not None: + self._ping_task.cancel() + self._ping_task = None + + def _cancel_pong_response_cb(self) -> None: + if self._pong_response_cb is not None: + self._pong_response_cb.cancel() + self._pong_response_cb = None + + def _reset_heartbeat(self) -> None: + if self._heartbeat is None: + return + self._cancel_pong_response_cb() + req = self._req + timeout_ceil_threshold = ( + req._protocol._timeout_ceil_threshold if req is not None else 5 + ) + loop = self._loop + assert loop is not None + now = loop.time() + when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold) + self._heartbeat_when = when + if self._heartbeat_cb is None: + # We do not cancel the previous heartbeat_cb here because + # it generates a significant amount of TimerHandle churn + # which causes asyncio to rebuild the heap frequently. + # Instead _send_heartbeat() will reschedule the next + # heartbeat if it fires too early. + self._heartbeat_cb = loop.call_at(when, self._send_heartbeat) + + def _send_heartbeat(self) -> None: + self._heartbeat_cb = None + loop = self._loop + assert loop is not None and self._writer is not None + now = loop.time() + if now < self._heartbeat_when: + # Heartbeat fired too early, reschedule + self._heartbeat_cb = loop.call_at( + self._heartbeat_when, self._send_heartbeat + ) + return + + req = self._req + timeout_ceil_threshold = ( + req._protocol._timeout_ceil_threshold if req is not None else 5 + ) + when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold) + self._cancel_pong_response_cb() + self._pong_response_cb = loop.call_at(when, self._pong_not_received) + + if sys.version_info >= (3, 12): + # Optimization for Python 3.12, try to send the ping + # immediately to avoid having to schedule + # the task on the event loop. + ping_task = asyncio.Task(self._writer.ping(), loop=loop, eager_start=True) + else: + ping_task = loop.create_task(self._writer.ping()) + + if not ping_task.done(): + self._ping_task = ping_task + ping_task.add_done_callback(self._ping_task_done) + else: + self._ping_task_done(ping_task) + + def _ping_task_done(self, task: "asyncio.Task[None]") -> None: + """Callback for when the ping task completes.""" + if not task.cancelled() and (exc := task.exception()): + self._handle_ping_pong_exception(exc) + self._ping_task = None + + def _pong_not_received(self) -> None: + if self._req is not None and self._req.transport is not None: + self._handle_ping_pong_exception(asyncio.TimeoutError()) + + def _handle_ping_pong_exception(self, exc: BaseException) -> None: + """Handle exceptions raised during ping/pong processing.""" + if self._closed: + return + self._set_closed() + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + self._exception = exc + if self._waiting and not self._closing and self._reader is not None: + self._reader.feed_data(WSMessage(WSMsgType.ERROR, exc, None)) + + def _set_closed(self) -> None: + """Set the connection to closed. + + Cancel any heartbeat timers and set the closed flag. + """ + self._closed = True + self._cancel_heartbeat() + + async def prepare(self, request: BaseRequest) -> AbstractStreamWriter: + # make pre-check to don't hide it by do_handshake() exceptions + if self._payload_writer is not None: + return self._payload_writer + + protocol, writer = self._pre_start(request) + payload_writer = await super().prepare(request) + assert payload_writer is not None + self._post_start(request, protocol, writer) + await payload_writer.drain() + return payload_writer + + def _handshake( + self, request: BaseRequest + ) -> Tuple["CIMultiDict[str]", str, bool, bool]: + headers = request.headers + if "websocket" != headers.get(hdrs.UPGRADE, "").lower().strip(): + raise HTTPBadRequest( + text=( + "No WebSocket UPGRADE hdr: {}\n Can " + '"Upgrade" only to "WebSocket".' + ).format(headers.get(hdrs.UPGRADE)) + ) + + if "upgrade" not in headers.get(hdrs.CONNECTION, "").lower(): + raise HTTPBadRequest( + text="No CONNECTION upgrade hdr: {}".format( + headers.get(hdrs.CONNECTION) + ) + ) + + # find common sub-protocol between client and server + protocol = None + if hdrs.SEC_WEBSOCKET_PROTOCOL in headers: + req_protocols = [ + str(proto.strip()) + for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",") + ] + + for proto in req_protocols: + if proto in self._protocols: + protocol = proto + break + else: + # No overlap found: Return no protocol as per spec + ws_logger.warning( + "Client protocols %r don’t overlap server-known ones %r", + req_protocols, + self._protocols, + ) + + # check supported version + version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, "") + if version not in ("13", "8", "7"): + raise HTTPBadRequest(text=f"Unsupported version: {version}") + + # check client handshake for validity + key = headers.get(hdrs.SEC_WEBSOCKET_KEY) + try: + if not key or len(base64.b64decode(key)) != 16: + raise HTTPBadRequest(text=f"Handshake error: {key!r}") + except binascii.Error: + raise HTTPBadRequest(text=f"Handshake error: {key!r}") from None + + accept_val = base64.b64encode( + hashlib.sha1(key.encode() + WS_KEY).digest() + ).decode() + response_headers = CIMultiDict( + { + hdrs.UPGRADE: "websocket", + hdrs.CONNECTION: "upgrade", + hdrs.SEC_WEBSOCKET_ACCEPT: accept_val, + } + ) + + notakeover = False + compress = 0 + if self._compress: + extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS) + # Server side always get return with no exception. + # If something happened, just drop compress extension + compress, notakeover = ws_ext_parse(extensions, isserver=True) + if compress: + enabledext = ws_ext_gen( + compress=compress, isserver=True, server_notakeover=notakeover + ) + response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext + + if protocol: + response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol + return ( + response_headers, + protocol, + compress, + notakeover, + ) # type: ignore[return-value] + + def _pre_start(self, request: BaseRequest) -> Tuple[str, WebSocketWriter]: + self._loop = request._loop + + headers, protocol, compress, notakeover = self._handshake(request) + + self.set_status(101) + self.headers.update(headers) + self.force_close() + self._compress = compress + transport = request._protocol.transport + assert transport is not None + writer = WebSocketWriter( + request._protocol, transport, compress=compress, notakeover=notakeover + ) + + return protocol, writer + + def _post_start( + self, request: BaseRequest, protocol: str, writer: WebSocketWriter + ) -> None: + self._ws_protocol = protocol + self._writer = writer + + self._reset_heartbeat() + + loop = self._loop + assert loop is not None + self._reader = FlowControlDataQueue(request._protocol, 2**16, loop=loop) + request.protocol.set_parser( + WebSocketReader(self._reader, self._max_msg_size, compress=self._compress) + ) + # disable HTTP keepalive for WebSocket + request.protocol.keep_alive(False) + + def can_prepare(self, request: BaseRequest) -> WebSocketReady: + if self._writer is not None: + raise RuntimeError("Already started") + try: + _, protocol, _, _ = self._handshake(request) + except HTTPException: + return WebSocketReady(False, None) + else: + return WebSocketReady(True, protocol) + + @property + def closed(self) -> bool: + return self._closed + + @property + def close_code(self) -> Optional[int]: + return self._close_code + + @property + def ws_protocol(self) -> Optional[str]: + return self._ws_protocol + + @property + def compress(self) -> bool: + return self._compress + + def get_extra_info(self, name: str, default: Any = None) -> Any: + """Get optional transport information. + + If no value associated with ``name`` is found, ``default`` is returned. + """ + writer = self._writer + if writer is None: + return default + transport = writer.transport + if transport is None: + return default + return transport.get_extra_info(name, default) + + def exception(self) -> Optional[BaseException]: + return self._exception + + async def ping(self, message: bytes = b"") -> None: + if self._writer is None: + raise RuntimeError("Call .prepare() first") + await self._writer.ping(message) + + async def pong(self, message: bytes = b"") -> None: + # unsolicited pong + if self._writer is None: + raise RuntimeError("Call .prepare() first") + await self._writer.pong(message) + + async def send_str(self, data: str, compress: Optional[bool] = None) -> None: + if self._writer is None: + raise RuntimeError("Call .prepare() first") + if not isinstance(data, str): + raise TypeError("data argument must be str (%r)" % type(data)) + await self._writer.send(data, binary=False, compress=compress) + + async def send_bytes(self, data: bytes, compress: Optional[bool] = None) -> None: + if self._writer is None: + raise RuntimeError("Call .prepare() first") + if not isinstance(data, (bytes, bytearray, memoryview)): + raise TypeError("data argument must be byte-ish (%r)" % type(data)) + await self._writer.send(data, binary=True, compress=compress) + + async def send_json( + self, + data: Any, + compress: Optional[bool] = None, + *, + dumps: JSONEncoder = json.dumps, + ) -> None: + await self.send_str(dumps(data), compress=compress) + + async def write_eof(self) -> None: # type: ignore[override] + if self._eof_sent: + return + if self._payload_writer is None: + raise RuntimeError("Response has not been started") + + await self.close() + self._eof_sent = True + + async def close( + self, *, code: int = WSCloseCode.OK, message: bytes = b"", drain: bool = True + ) -> bool: + """Close websocket connection.""" + if self._writer is None: + raise RuntimeError("Call .prepare() first") + + if self._closed: + return False + self._set_closed() + + try: + await self._writer.close(code, message) + writer = self._payload_writer + assert writer is not None + if drain: + await writer.drain() + except (asyncio.CancelledError, asyncio.TimeoutError): + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + raise + except Exception as exc: + self._exception = exc + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + return True + + reader = self._reader + assert reader is not None + # we need to break `receive()` cycle before we can call + # `reader.read()` as `close()` may be called from different task + if self._waiting: + assert self._loop is not None + assert self._close_wait is None + self._close_wait = self._loop.create_future() + reader.feed_data(WS_CLOSING_MESSAGE) + await self._close_wait + + if self._closing: + self._close_transport() + return True + + try: + async with async_timeout.timeout(self._timeout): + msg = await reader.read() + except asyncio.CancelledError: + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + raise + except Exception as exc: + self._exception = exc + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + return True + + if msg.type is WSMsgType.CLOSE: + self._set_code_close_transport(msg.data) + return True + + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + self._exception = asyncio.TimeoutError() + return True + + def _set_closing(self, code: WSCloseCode) -> None: + """Set the close code and mark the connection as closing.""" + self._closing = True + self._close_code = code + self._cancel_heartbeat() + + def _set_code_close_transport(self, code: WSCloseCode) -> None: + """Set the close code and close the transport.""" + self._close_code = code + self._close_transport() + + def _close_transport(self) -> None: + """Close the transport.""" + if self._req is not None and self._req.transport is not None: + self._req.transport.close() + + async def receive(self, timeout: Optional[float] = None) -> WSMessage: + if self._reader is None: + raise RuntimeError("Call .prepare() first") + + loop = self._loop + assert loop is not None + receive_timeout = timeout or self._receive_timeout + while True: + if self._waiting: + raise RuntimeError("Concurrent call to receive() is not allowed") + + if self._closed: + self._conn_lost += 1 + if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS: + raise RuntimeError("WebSocket connection is closed.") + return WS_CLOSED_MESSAGE + elif self._closing: + return WS_CLOSING_MESSAGE + + try: + self._waiting = True + try: + if receive_timeout: + # Entering the context manager and creating + # Timeout() object can take almost 50% of the + # run time in this loop so we avoid it if + # there is no read timeout. + async with async_timeout.timeout(receive_timeout): + msg = await self._reader.read() + else: + msg = await self._reader.read() + self._reset_heartbeat() + finally: + self._waiting = False + if self._close_wait: + set_result(self._close_wait, None) + except asyncio.TimeoutError: + raise + except EofStream: + self._close_code = WSCloseCode.OK + await self.close() + return WSMessage(WSMsgType.CLOSED, None, None) + except WebSocketError as exc: + self._close_code = exc.code + await self.close(code=exc.code) + return WSMessage(WSMsgType.ERROR, exc, None) + except Exception as exc: + self._exception = exc + self._set_closing(WSCloseCode.ABNORMAL_CLOSURE) + await self.close() + return WSMessage(WSMsgType.ERROR, exc, None) + + if msg.type is WSMsgType.CLOSE: + self._set_closing(msg.data) + # Could be closed while awaiting reader. + if not self._closed and self._autoclose: + # The client is likely going to close the + # connection out from under us so we do not + # want to drain any pending writes as it will + # likely result writing to a broken pipe. + await self.close(drain=False) + elif msg.type is WSMsgType.CLOSING: + self._set_closing(WSCloseCode.OK) + elif msg.type is WSMsgType.PING and self._autoping: + await self.pong(msg.data) + continue + elif msg.type is WSMsgType.PONG and self._autoping: + continue + + return msg + + async def receive_str(self, *, timeout: Optional[float] = None) -> str: + msg = await self.receive(timeout) + if msg.type is not WSMsgType.TEXT: + raise TypeError( + "Received message {}:{!r} is not WSMsgType.TEXT".format( + msg.type, msg.data + ) + ) + return cast(str, msg.data) + + async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes: + msg = await self.receive(timeout) + if msg.type is not WSMsgType.BINARY: + raise TypeError(f"Received message {msg.type}:{msg.data!r} is not bytes") + return cast(bytes, msg.data) + + async def receive_json( + self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None + ) -> Any: + data = await self.receive_str(timeout=timeout) + return loads(data) + + async def write(self, data: bytes) -> None: + raise RuntimeError("Cannot call .write() for websocket") + + def __aiter__(self) -> "WebSocketResponse": + return self + + async def __anext__(self) -> WSMessage: + msg = await self.receive() + if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED): + raise StopAsyncIteration + return msg + + def _cancel(self, exc: BaseException) -> None: + # web_protocol calls this from connection_lost + # or when the server is shutting down. + self._closing = True + self._cancel_heartbeat() + if self._reader is not None: + set_exception(self._reader, exc) diff --git a/env/Lib/site-packages/aiohttp/worker.py b/env/Lib/site-packages/aiohttp/worker.py new file mode 100644 index 0000000..9b30769 --- /dev/null +++ b/env/Lib/site-packages/aiohttp/worker.py @@ -0,0 +1,247 @@ +"""Async gunicorn worker for aiohttp.web""" + +import asyncio +import os +import re +import signal +import sys +from types import FrameType +from typing import Any, Awaitable, Callable, Optional, Union # noqa + +from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat +from gunicorn.workers import base + +from aiohttp import web + +from .helpers import set_result +from .web_app import Application +from .web_log import AccessLogger + +try: + import ssl + + SSLContext = ssl.SSLContext +except ImportError: # pragma: no cover + ssl = None # type: ignore[assignment] + SSLContext = object # type: ignore[misc,assignment] + + +__all__ = ("GunicornWebWorker", "GunicornUVLoopWebWorker") + + +class GunicornWebWorker(base.Worker): # type: ignore[misc,no-any-unimported] + + DEFAULT_AIOHTTP_LOG_FORMAT = AccessLogger.LOG_FORMAT + DEFAULT_GUNICORN_LOG_FORMAT = GunicornAccessLogFormat.default + + def __init__(self, *args: Any, **kw: Any) -> None: # pragma: no cover + super().__init__(*args, **kw) + + self._task: Optional[asyncio.Task[None]] = None + self.exit_code = 0 + self._notify_waiter: Optional[asyncio.Future[bool]] = None + + def init_process(self) -> None: + # create new event_loop after fork + asyncio.get_event_loop().close() + + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(self.loop) + + super().init_process() + + def run(self) -> None: + self._task = self.loop.create_task(self._run()) + + try: # ignore all finalization problems + self.loop.run_until_complete(self._task) + except Exception: + self.log.exception("Exception in gunicorn worker") + self.loop.run_until_complete(self.loop.shutdown_asyncgens()) + self.loop.close() + + sys.exit(self.exit_code) + + async def _run(self) -> None: + runner = None + if isinstance(self.wsgi, Application): + app = self.wsgi + elif asyncio.iscoroutinefunction(self.wsgi): + wsgi = await self.wsgi() + if isinstance(wsgi, web.AppRunner): + runner = wsgi + app = runner.app + else: + app = wsgi + else: + raise RuntimeError( + "wsgi app should be either Application or " + "async function returning Application, got {}".format(self.wsgi) + ) + + if runner is None: + access_log = self.log.access_log if self.cfg.accesslog else None + runner = web.AppRunner( + app, + logger=self.log, + keepalive_timeout=self.cfg.keepalive, + access_log=access_log, + access_log_format=self._get_valid_log_format( + self.cfg.access_log_format + ), + shutdown_timeout=self.cfg.graceful_timeout / 100 * 95, + ) + await runner.setup() + + ctx = self._create_ssl_context(self.cfg) if self.cfg.is_ssl else None + + runner = runner + assert runner is not None + server = runner.server + assert server is not None + for sock in self.sockets: + site = web.SockSite( + runner, + sock, + ssl_context=ctx, + ) + await site.start() + + # If our parent changed then we shut down. + pid = os.getpid() + try: + while self.alive: # type: ignore[has-type] + self.notify() + + cnt = server.requests_count + if self.max_requests and cnt > self.max_requests: + self.alive = False + self.log.info("Max requests, shutting down: %s", self) + + elif pid == os.getpid() and self.ppid != os.getppid(): + self.alive = False + self.log.info("Parent changed, shutting down: %s", self) + else: + await self._wait_next_notify() + except BaseException: + pass + + await runner.cleanup() + + def _wait_next_notify(self) -> "asyncio.Future[bool]": + self._notify_waiter_done() + + loop = self.loop + assert loop is not None + self._notify_waiter = waiter = loop.create_future() + self.loop.call_later(1.0, self._notify_waiter_done, waiter) + + return waiter + + def _notify_waiter_done( + self, waiter: Optional["asyncio.Future[bool]"] = None + ) -> None: + if waiter is None: + waiter = self._notify_waiter + if waiter is not None: + set_result(waiter, True) + + if waiter is self._notify_waiter: + self._notify_waiter = None + + def init_signals(self) -> None: + # Set up signals through the event loop API. + + self.loop.add_signal_handler( + signal.SIGQUIT, self.handle_quit, signal.SIGQUIT, None + ) + + self.loop.add_signal_handler( + signal.SIGTERM, self.handle_exit, signal.SIGTERM, None + ) + + self.loop.add_signal_handler( + signal.SIGINT, self.handle_quit, signal.SIGINT, None + ) + + self.loop.add_signal_handler( + signal.SIGWINCH, self.handle_winch, signal.SIGWINCH, None + ) + + self.loop.add_signal_handler( + signal.SIGUSR1, self.handle_usr1, signal.SIGUSR1, None + ) + + self.loop.add_signal_handler( + signal.SIGABRT, self.handle_abort, signal.SIGABRT, None + ) + + # Don't let SIGTERM and SIGUSR1 disturb active requests + # by interrupting system calls + signal.siginterrupt(signal.SIGTERM, False) + signal.siginterrupt(signal.SIGUSR1, False) + # Reset signals so Gunicorn doesn't swallow subprocess return codes + # See: https://github.com/aio-libs/aiohttp/issues/6130 + + def handle_quit(self, sig: int, frame: Optional[FrameType]) -> None: + self.alive = False + + # worker_int callback + self.cfg.worker_int(self) + + # wakeup closing process + self._notify_waiter_done() + + def handle_abort(self, sig: int, frame: Optional[FrameType]) -> None: + self.alive = False + self.exit_code = 1 + self.cfg.worker_abort(self) + sys.exit(1) + + @staticmethod + def _create_ssl_context(cfg: Any) -> "SSLContext": + """Creates SSLContext instance for usage in asyncio.create_server. + + See ssl.SSLSocket.__init__ for more details. + """ + if ssl is None: # pragma: no cover + raise RuntimeError("SSL is not supported.") + + ctx = ssl.SSLContext(cfg.ssl_version) + ctx.load_cert_chain(cfg.certfile, cfg.keyfile) + ctx.verify_mode = cfg.cert_reqs + if cfg.ca_certs: + ctx.load_verify_locations(cfg.ca_certs) + if cfg.ciphers: + ctx.set_ciphers(cfg.ciphers) + return ctx + + def _get_valid_log_format(self, source_format: str) -> str: + if source_format == self.DEFAULT_GUNICORN_LOG_FORMAT: + return self.DEFAULT_AIOHTTP_LOG_FORMAT + elif re.search(r"%\([^\)]+\)", source_format): + raise ValueError( + "Gunicorn's style options in form of `%(name)s` are not " + "supported for the log formatting. Please use aiohttp's " + "format specification to configure access log formatting: " + "http://docs.aiohttp.org/en/stable/logging.html" + "#format-specification" + ) + else: + return source_format + + +class GunicornUVLoopWebWorker(GunicornWebWorker): + def init_process(self) -> None: + import uvloop + + # Close any existing event loop before setting a + # new policy. + asyncio.get_event_loop().close() + + # Setup uvloop policy, so that every + # asyncio.get_event_loop() will create an instance + # of uvloop event loop. + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + + super().init_process() diff --git a/env/Lib/site-packages/aiosignal-1.3.1.dist-info/INSTALLER b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/aiosignal-1.3.1.dist-info/LICENSE b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/LICENSE new file mode 100644 index 0000000..7082a2d --- /dev/null +++ b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2013-2019 Nikolay Kim and Andrew Svetlov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/env/Lib/site-packages/aiosignal-1.3.1.dist-info/METADATA b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/METADATA new file mode 100644 index 0000000..fc96452 --- /dev/null +++ b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/METADATA @@ -0,0 +1,128 @@ +Metadata-Version: 2.1 +Name: aiosignal +Version: 1.3.1 +Summary: aiosignal: a list of registered asynchronous callbacks +Home-page: https://github.com/aio-libs/aiosignal +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache 2.0 +Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby +Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiosignal/actions +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiosignal +Project-URL: Docs: RTD, https://docs.aiosignal.org +Project-URL: GitHub: issues, https://github.com/aio-libs/aiosignal/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/aiosignal +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Framework :: AsyncIO +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: frozenlist (>=1.1.0) + +========= +aiosignal +========= + +.. image:: https://github.com/aio-libs/aiosignal/workflows/CI/badge.svg + :target: https://github.com/aio-libs/aiosignal/actions?query=workflow%3ACI + :alt: GitHub status for master branch + +.. image:: https://codecov.io/gh/aio-libs/aiosignal/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/aiosignal + :alt: codecov.io status for master branch + +.. image:: https://badge.fury.io/py/aiosignal.svg + :target: https://pypi.org/project/aiosignal + :alt: Latest PyPI package version + +.. image:: https://readthedocs.org/projects/aiosignal/badge/?version=latest + :target: https://aiosignal.readthedocs.io/ + :alt: Latest Read The Docs + +.. image:: https://img.shields.io/discourse/topics?server=https%3A%2F%2Faio-libs.discourse.group%2F + :target: https://aio-libs.discourse.group/ + :alt: Discourse group for io-libs + +.. image:: https://badges.gitter.im/Join%20Chat.svg + :target: https://gitter.im/aio-libs/Lobby + :alt: Chat on Gitter + +Introduction +============ + +A project to manage callbacks in `asyncio` projects. + +``Signal`` is a list of registered asynchronous callbacks. + +The signal's life-cycle has two stages: after creation its content +could be filled by using standard list operations: ``sig.append()`` +etc. + +After you call ``sig.freeze()`` the signal is *frozen*: adding, removing +and dropping callbacks is forbidden. + +The only available operation is calling the previously registered +callbacks by using ``await sig.send(data)``. + +For concrete usage examples see the `Signals + +section of the `Web Server Advanced +` chapter of the `aiohttp +documentation`_. + + +Installation +------------ + +:: + + $ pip install aiosignal + +The library requires Python 3.6 or newer. + + +Documentation +============= + +https://aiosignal.readthedocs.io/ + +Communication channels +====================== + +*gitter chat* https://gitter.im/aio-libs/Lobby + +Requirements +============ + +- Python >= 3.6 +- frozenlist >= 1.0.0 + +License +======= + +``aiosignal`` is offered under the Apache 2 license. + +Source code +=========== + +The project is hosted on GitHub_ + +Please file an issue in the `bug tracker +`_ if you have found a bug +or have some suggestions to improve the library. + +.. _GitHub: https://github.com/aio-libs/aiosignal +.. _aiohttp documentation: https://docs.aiohttp.org/ diff --git a/env/Lib/site-packages/aiosignal-1.3.1.dist-info/RECORD b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/RECORD new file mode 100644 index 0000000..59be23b --- /dev/null +++ b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/RECORD @@ -0,0 +1,10 @@ +aiosignal-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiosignal-1.3.1.dist-info/LICENSE,sha256=b9UkPpLdf5jsacesN3co50kFcJ_1J6W_mNbQJjwE9bY,11332 +aiosignal-1.3.1.dist-info/METADATA,sha256=c0HRnlYzfXKztZPTFDlPfygizTherhG5WdwXlvco0Ug,4008 +aiosignal-1.3.1.dist-info/RECORD,, +aiosignal-1.3.1.dist-info/WHEEL,sha256=ZL1lC_LiPDNRgDnOl2taCMc83aPEUZgHHv2h-LDgdiM,92 +aiosignal-1.3.1.dist-info/top_level.txt,sha256=z45aNOKGDdrI1roqZY3BGXQ22kJFPHBmVdwtLYLtXC0,10 +aiosignal/__init__.py,sha256=zQNfFYRSd84bswvpFv8ZWjEr5DeYwV3LXbMSyo2222s,867 +aiosignal/__init__.pyi,sha256=xeCddYSS8fZAkz8S4HuKSR2IDe3N7RW_LKcXDPPA1Xk,311 +aiosignal/__pycache__/__init__.cpython-311.pyc,, +aiosignal/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/env/Lib/site-packages/aiosignal-1.3.1.dist-info/WHEEL b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/WHEEL new file mode 100644 index 0000000..5e1f087 --- /dev/null +++ b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.38.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/env/Lib/site-packages/aiosignal-1.3.1.dist-info/top_level.txt b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/top_level.txt new file mode 100644 index 0000000..ac6df3a --- /dev/null +++ b/env/Lib/site-packages/aiosignal-1.3.1.dist-info/top_level.txt @@ -0,0 +1 @@ +aiosignal diff --git a/env/Lib/site-packages/aiosignal/__init__.py b/env/Lib/site-packages/aiosignal/__init__.py new file mode 100644 index 0000000..3d288e6 --- /dev/null +++ b/env/Lib/site-packages/aiosignal/__init__.py @@ -0,0 +1,36 @@ +from frozenlist import FrozenList + +__version__ = "1.3.1" + +__all__ = ("Signal",) + + +class Signal(FrozenList): + """Coroutine-based signal implementation. + + To connect a callback to a signal, use any list method. + + Signals are fired using the send() coroutine, which takes named + arguments. + """ + + __slots__ = ("_owner",) + + def __init__(self, owner): + super().__init__() + self._owner = owner + + def __repr__(self): + return "".format( + self._owner, self.frozen, list(self) + ) + + async def send(self, *args, **kwargs): + """ + Sends data to all registered receivers. + """ + if not self.frozen: + raise RuntimeError("Cannot send non-frozen signal.") + + for receiver in self: + await receiver(*args, **kwargs) # type: ignore diff --git a/env/Lib/site-packages/aiosignal/__init__.pyi b/env/Lib/site-packages/aiosignal/__init__.pyi new file mode 100644 index 0000000..d4e3416 --- /dev/null +++ b/env/Lib/site-packages/aiosignal/__init__.pyi @@ -0,0 +1,12 @@ +from typing import Any, Generic, TypeVar + +from frozenlist import FrozenList + +__all__ = ("Signal",) + +_T = TypeVar("_T") + +class Signal(FrozenList[_T], Generic[_T]): + def __init__(self, owner: Any) -> None: ... + def __repr__(self) -> str: ... + async def send(self, *args: Any, **kwargs: Any) -> None: ... diff --git a/env/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..b332142 Binary files /dev/null and b/env/Lib/site-packages/aiosignal/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/aiosignal/py.typed b/env/Lib/site-packages/aiosignal/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/annotated_types-0.7.0.dist-info/INSTALLER b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/annotated_types-0.7.0.dist-info/METADATA b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/METADATA new file mode 100644 index 0000000..3ac05cf --- /dev/null +++ b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/METADATA @@ -0,0 +1,295 @@ +Metadata-Version: 2.3 +Name: annotated-types +Version: 0.7.0 +Summary: Reusable constraint types to use with typing.Annotated +Project-URL: Homepage, https://github.com/annotated-types/annotated-types +Project-URL: Source, https://github.com/annotated-types/annotated-types +Project-URL: Changelog, https://github.com/annotated-types/annotated-types/releases +Author-email: Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Samuel Colvin , Zac Hatfield-Dodds +License-File: LICENSE +Classifier: Development Status :: 4 - Beta +Classifier: Environment :: Console +Classifier: Environment :: MacOS X +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Typing :: Typed +Requires-Python: >=3.8 +Requires-Dist: typing-extensions>=4.0.0; python_version < '3.9' +Description-Content-Type: text/markdown + +# annotated-types + +[![CI](https://github.com/annotated-types/annotated-types/workflows/CI/badge.svg?event=push)](https://github.com/annotated-types/annotated-types/actions?query=event%3Apush+branch%3Amain+workflow%3ACI) +[![pypi](https://img.shields.io/pypi/v/annotated-types.svg)](https://pypi.python.org/pypi/annotated-types) +[![versions](https://img.shields.io/pypi/pyversions/annotated-types.svg)](https://github.com/annotated-types/annotated-types) +[![license](https://img.shields.io/github/license/annotated-types/annotated-types.svg)](https://github.com/annotated-types/annotated-types/blob/main/LICENSE) + +[PEP-593](https://peps.python.org/pep-0593/) added `typing.Annotated` as a way of +adding context-specific metadata to existing types, and specifies that +`Annotated[T, x]` _should_ be treated as `T` by any tool or library without special +logic for `x`. + +This package provides metadata objects which can be used to represent common +constraints such as upper and lower bounds on scalar values and collection sizes, +a `Predicate` marker for runtime checks, and +descriptions of how we intend these metadata to be interpreted. In some cases, +we also note alternative representations which do not require this package. + +## Install + +```bash +pip install annotated-types +``` + +## Examples + +```python +from typing import Annotated +from annotated_types import Gt, Len, Predicate + +class MyClass: + age: Annotated[int, Gt(18)] # Valid: 19, 20, ... + # Invalid: 17, 18, "19", 19.0, ... + factors: list[Annotated[int, Predicate(is_prime)]] # Valid: 2, 3, 5, 7, 11, ... + # Invalid: 4, 8, -2, 5.0, "prime", ... + + my_list: Annotated[list[int], Len(0, 10)] # Valid: [], [10, 20, 30, 40, 50] + # Invalid: (1, 2), ["abc"], [0] * 20 +``` + +## Documentation + +_While `annotated-types` avoids runtime checks for performance, users should not +construct invalid combinations such as `MultipleOf("non-numeric")` or `Annotated[int, Len(3)]`. +Downstream implementors may choose to raise an error, emit a warning, silently ignore +a metadata item, etc., if the metadata objects described below are used with an +incompatible type - or for any other reason!_ + +### Gt, Ge, Lt, Le + +Express inclusive and/or exclusive bounds on orderable values - which may be numbers, +dates, times, strings, sets, etc. Note that the boundary value need not be of the +same type that was annotated, so long as they can be compared: `Annotated[int, Gt(1.5)]` +is fine, for example, and implies that the value is an integer x such that `x > 1.5`. + +We suggest that implementors may also interpret `functools.partial(operator.le, 1.5)` +as being equivalent to `Gt(1.5)`, for users who wish to avoid a runtime dependency on +the `annotated-types` package. + +To be explicit, these types have the following meanings: + +* `Gt(x)` - value must be "Greater Than" `x` - equivalent to exclusive minimum +* `Ge(x)` - value must be "Greater than or Equal" to `x` - equivalent to inclusive minimum +* `Lt(x)` - value must be "Less Than" `x` - equivalent to exclusive maximum +* `Le(x)` - value must be "Less than or Equal" to `x` - equivalent to inclusive maximum + +### Interval + +`Interval(gt, ge, lt, le)` allows you to specify an upper and lower bound with a single +metadata object. `None` attributes should be ignored, and non-`None` attributes +treated as per the single bounds above. + +### MultipleOf + +`MultipleOf(multiple_of=x)` might be interpreted in two ways: + +1. Python semantics, implying `value % multiple_of == 0`, or +2. [JSONschema semantics](https://json-schema.org/draft/2020-12/json-schema-validation.html#rfc.section.6.2.1), + where `int(value / multiple_of) == value / multiple_of`. + +We encourage users to be aware of these two common interpretations and their +distinct behaviours, especially since very large or non-integer numbers make +it easy to cause silent data corruption due to floating-point imprecision. + +We encourage libraries to carefully document which interpretation they implement. + +### MinLen, MaxLen, Len + +`Len()` implies that `min_length <= len(value) <= max_length` - lower and upper bounds are inclusive. + +As well as `Len()` which can optionally include upper and lower bounds, we also +provide `MinLen(x)` and `MaxLen(y)` which are equivalent to `Len(min_length=x)` +and `Len(max_length=y)` respectively. + +`Len`, `MinLen`, and `MaxLen` may be used with any type which supports `len(value)`. + +Examples of usage: + +* `Annotated[list, MaxLen(10)]` (or `Annotated[list, Len(max_length=10))`) - list must have a length of 10 or less +* `Annotated[str, MaxLen(10)]` - string must have a length of 10 or less +* `Annotated[list, MinLen(3))` (or `Annotated[list, Len(min_length=3))`) - list must have a length of 3 or more +* `Annotated[list, Len(4, 6)]` - list must have a length of 4, 5, or 6 +* `Annotated[list, Len(8, 8)]` - list must have a length of exactly 8 + +#### Changed in v0.4.0 + +* `min_inclusive` has been renamed to `min_length`, no change in meaning +* `max_exclusive` has been renamed to `max_length`, upper bound is now **inclusive** instead of **exclusive** +* The recommendation that slices are interpreted as `Len` has been removed due to ambiguity and different semantic + meaning of the upper bound in slices vs. `Len` + +See [issue #23](https://github.com/annotated-types/annotated-types/issues/23) for discussion. + +### Timezone + +`Timezone` can be used with a `datetime` or a `time` to express which timezones +are allowed. `Annotated[datetime, Timezone(None)]` must be a naive datetime. +`Timezone[...]` ([literal ellipsis](https://docs.python.org/3/library/constants.html#Ellipsis)) +expresses that any timezone-aware datetime is allowed. You may also pass a specific +timezone string or [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) +object such as `Timezone(timezone.utc)` or `Timezone("Africa/Abidjan")` to express that you only +allow a specific timezone, though we note that this is often a symptom of fragile design. + +#### Changed in v0.x.x + +* `Timezone` accepts [`tzinfo`](https://docs.python.org/3/library/datetime.html#tzinfo-objects) objects instead of + `timezone`, extending compatibility to [`zoneinfo`](https://docs.python.org/3/library/zoneinfo.html) and third party libraries. + +### Unit + +`Unit(unit: str)` expresses that the annotated numeric value is the magnitude of +a quantity with the specified unit. For example, `Annotated[float, Unit("m/s")]` +would be a float representing a velocity in meters per second. + +Please note that `annotated_types` itself makes no attempt to parse or validate +the unit string in any way. That is left entirely to downstream libraries, +such as [`pint`](https://pint.readthedocs.io) or +[`astropy.units`](https://docs.astropy.org/en/stable/units/). + +An example of how a library might use this metadata: + +```python +from annotated_types import Unit +from typing import Annotated, TypeVar, Callable, Any, get_origin, get_args + +# given a type annotated with a unit: +Meters = Annotated[float, Unit("m")] + + +# you can cast the annotation to a specific unit type with any +# callable that accepts a string and returns the desired type +T = TypeVar("T") +def cast_unit(tp: Any, unit_cls: Callable[[str], T]) -> T | None: + if get_origin(tp) is Annotated: + for arg in get_args(tp): + if isinstance(arg, Unit): + return unit_cls(arg.unit) + return None + + +# using `pint` +import pint +pint_unit = cast_unit(Meters, pint.Unit) + + +# using `astropy.units` +import astropy.units as u +astropy_unit = cast_unit(Meters, u.Unit) +``` + +### Predicate + +`Predicate(func: Callable)` expresses that `func(value)` is truthy for valid values. +Users should prefer the statically inspectable metadata above, but if you need +the full power and flexibility of arbitrary runtime predicates... here it is. + +For some common constraints, we provide generic types: + +* `IsLower = Annotated[T, Predicate(str.islower)]` +* `IsUpper = Annotated[T, Predicate(str.isupper)]` +* `IsDigit = Annotated[T, Predicate(str.isdigit)]` +* `IsFinite = Annotated[T, Predicate(math.isfinite)]` +* `IsNotFinite = Annotated[T, Predicate(Not(math.isfinite))]` +* `IsNan = Annotated[T, Predicate(math.isnan)]` +* `IsNotNan = Annotated[T, Predicate(Not(math.isnan))]` +* `IsInfinite = Annotated[T, Predicate(math.isinf)]` +* `IsNotInfinite = Annotated[T, Predicate(Not(math.isinf))]` + +so that you can write e.g. `x: IsFinite[float] = 2.0` instead of the longer +(but exactly equivalent) `x: Annotated[float, Predicate(math.isfinite)] = 2.0`. + +Some libraries might have special logic to handle known or understandable predicates, +for example by checking for `str.isdigit` and using its presence to both call custom +logic to enforce digit-only strings, and customise some generated external schema. +Users are therefore encouraged to avoid indirection like `lambda s: s.lower()`, in +favor of introspectable methods such as `str.lower` or `re.compile("pattern").search`. + +To enable basic negation of commonly used predicates like `math.isnan` without introducing introspection that makes it impossible for implementers to introspect the predicate we provide a `Not` wrapper that simply negates the predicate in an introspectable manner. Several of the predicates listed above are created in this manner. + +We do not specify what behaviour should be expected for predicates that raise +an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently +skip invalid constraints, or statically raise an error; or it might try calling it +and then propagate or discard the resulting +`TypeError: descriptor 'isdigit' for 'str' objects doesn't apply to a 'int' object` +exception. We encourage libraries to document the behaviour they choose. + +### Doc + +`doc()` can be used to add documentation information in `Annotated`, for function and method parameters, variables, class attributes, return types, and any place where `Annotated` can be used. + +It expects a value that can be statically analyzed, as the main use case is for static analysis, editors, documentation generators, and similar tools. + +It returns a `DocInfo` class with a single attribute `documentation` containing the value passed to `doc()`. + +This is the early adopter's alternative form of the [`typing-doc` proposal](https://github.com/tiangolo/fastapi/blob/typing-doc/typing_doc.md). + +### Integrating downstream types with `GroupedMetadata` + +Implementers may choose to provide a convenience wrapper that groups multiple pieces of metadata. +This can help reduce verbosity and cognitive overhead for users. +For example, an implementer like Pydantic might provide a `Field` or `Meta` type that accepts keyword arguments and transforms these into low-level metadata: + +```python +from dataclasses import dataclass +from typing import Iterator +from annotated_types import GroupedMetadata, Ge + +@dataclass +class Field(GroupedMetadata): + ge: int | None = None + description: str | None = None + + def __iter__(self) -> Iterator[object]: + # Iterating over a GroupedMetadata object should yield annotated-types + # constraint metadata objects which describe it as fully as possible, + # and may include other unknown objects too. + if self.ge is not None: + yield Ge(self.ge) + if self.description is not None: + yield Description(self.description) +``` + +Libraries consuming annotated-types constraints should check for `GroupedMetadata` and unpack it by iterating over the object and treating the results as if they had been "unpacked" in the `Annotated` type. The same logic should be applied to the [PEP 646 `Unpack` type](https://peps.python.org/pep-0646/), so that `Annotated[T, Field(...)]`, `Annotated[T, Unpack[Field(...)]]` and `Annotated[T, *Field(...)]` are all treated consistently. + +Libraries consuming annotated-types should also ignore any metadata they do not recongize that came from unpacking a `GroupedMetadata`, just like they ignore unrecognized metadata in `Annotated` itself. + +Our own `annotated_types.Interval` class is a `GroupedMetadata` which unpacks itself into `Gt`, `Lt`, etc., so this is not an abstract concern. Similarly, `annotated_types.Len` is a `GroupedMetadata` which unpacks itself into `MinLen` (optionally) and `MaxLen`. + +### Consuming metadata + +We intend to not be prescriptive as to _how_ the metadata and constraints are used, but as an example of how one might parse constraints from types annotations see our [implementation in `test_main.py`](https://github.com/annotated-types/annotated-types/blob/f59cf6d1b5255a0fe359b93896759a180bec30ae/tests/test_main.py#L94-L103). + +It is up to the implementer to determine how this metadata is used. +You could use the metadata for runtime type checking, for generating schemas or to generate example data, amongst other use cases. + +## Design & History + +This package was designed at the PyCon 2022 sprints by the maintainers of Pydantic +and Hypothesis, with the goal of making it as easy as possible for end-users to +provide more informative annotations for use by runtime libraries. + +It is deliberately minimal, and following PEP-593 allows considerable downstream +discretion in what (if anything!) they choose to support. Nonetheless, we expect +that staying simple and covering _only_ the most common use-cases will give users +and maintainers the best experience we can. If you'd like more constraints for your +types - follow our lead, by defining them and documenting them downstream! diff --git a/env/Lib/site-packages/annotated_types-0.7.0.dist-info/RECORD b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/RECORD new file mode 100644 index 0000000..568bd52 --- /dev/null +++ b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/RECORD @@ -0,0 +1,10 @@ +annotated_types-0.7.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +annotated_types-0.7.0.dist-info/METADATA,sha256=7ltqxksJJ0wCYFGBNIQCWTlWQGeAH0hRFdnK3CB895E,15046 +annotated_types-0.7.0.dist-info/RECORD,, +annotated_types-0.7.0.dist-info/WHEEL,sha256=zEMcRr9Kr03x1ozGwg5v9NQBKn3kndp6LSoSlVg-jhU,87 +annotated_types-0.7.0.dist-info/licenses/LICENSE,sha256=_hBJiEsaDZNCkB6I4H8ykl0ksxIdmXK2poBfuYJLCV0,1083 +annotated_types/__init__.py,sha256=RynLsRKUEGI0KimXydlD1fZEfEzWwDo0Uon3zOKhG1Q,13819 +annotated_types/__pycache__/__init__.cpython-311.pyc,, +annotated_types/__pycache__/test_cases.cpython-311.pyc,, +annotated_types/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +annotated_types/test_cases.py,sha256=zHFX6EpcMbGJ8FzBYDbO56bPwx_DYIVSKbZM-4B3_lg,6421 diff --git a/env/Lib/site-packages/annotated_types-0.7.0.dist-info/WHEEL b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/WHEEL new file mode 100644 index 0000000..516596c --- /dev/null +++ b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.24.2 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/env/Lib/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000..d99323a --- /dev/null +++ b/env/Lib/site-packages/annotated_types-0.7.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 the contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/env/Lib/site-packages/annotated_types/__init__.py b/env/Lib/site-packages/annotated_types/__init__.py new file mode 100644 index 0000000..74e0dee --- /dev/null +++ b/env/Lib/site-packages/annotated_types/__init__.py @@ -0,0 +1,432 @@ +import math +import sys +import types +from dataclasses import dataclass +from datetime import tzinfo +from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional, SupportsFloat, SupportsIndex, TypeVar, Union + +if sys.version_info < (3, 8): + from typing_extensions import Protocol, runtime_checkable +else: + from typing import Protocol, runtime_checkable + +if sys.version_info < (3, 9): + from typing_extensions import Annotated, Literal +else: + from typing import Annotated, Literal + +if sys.version_info < (3, 10): + EllipsisType = type(Ellipsis) + KW_ONLY = {} + SLOTS = {} +else: + from types import EllipsisType + + KW_ONLY = {"kw_only": True} + SLOTS = {"slots": True} + + +__all__ = ( + 'BaseMetadata', + 'GroupedMetadata', + 'Gt', + 'Ge', + 'Lt', + 'Le', + 'Interval', + 'MultipleOf', + 'MinLen', + 'MaxLen', + 'Len', + 'Timezone', + 'Predicate', + 'LowerCase', + 'UpperCase', + 'IsDigits', + 'IsFinite', + 'IsNotFinite', + 'IsNan', + 'IsNotNan', + 'IsInfinite', + 'IsNotInfinite', + 'doc', + 'DocInfo', + '__version__', +) + +__version__ = '0.7.0' + + +T = TypeVar('T') + + +# arguments that start with __ are considered +# positional only +# see https://peps.python.org/pep-0484/#positional-only-arguments + + +class SupportsGt(Protocol): + def __gt__(self: T, __other: T) -> bool: + ... + + +class SupportsGe(Protocol): + def __ge__(self: T, __other: T) -> bool: + ... + + +class SupportsLt(Protocol): + def __lt__(self: T, __other: T) -> bool: + ... + + +class SupportsLe(Protocol): + def __le__(self: T, __other: T) -> bool: + ... + + +class SupportsMod(Protocol): + def __mod__(self: T, __other: T) -> T: + ... + + +class SupportsDiv(Protocol): + def __div__(self: T, __other: T) -> T: + ... + + +class BaseMetadata: + """Base class for all metadata. + + This exists mainly so that implementers + can do `isinstance(..., BaseMetadata)` while traversing field annotations. + """ + + __slots__ = () + + +@dataclass(frozen=True, **SLOTS) +class Gt(BaseMetadata): + """Gt(gt=x) implies that the value must be greater than x. + + It can be used with any type that supports the ``>`` operator, + including numbers, dates and times, strings, sets, and so on. + """ + + gt: SupportsGt + + +@dataclass(frozen=True, **SLOTS) +class Ge(BaseMetadata): + """Ge(ge=x) implies that the value must be greater than or equal to x. + + It can be used with any type that supports the ``>=`` operator, + including numbers, dates and times, strings, sets, and so on. + """ + + ge: SupportsGe + + +@dataclass(frozen=True, **SLOTS) +class Lt(BaseMetadata): + """Lt(lt=x) implies that the value must be less than x. + + It can be used with any type that supports the ``<`` operator, + including numbers, dates and times, strings, sets, and so on. + """ + + lt: SupportsLt + + +@dataclass(frozen=True, **SLOTS) +class Le(BaseMetadata): + """Le(le=x) implies that the value must be less than or equal to x. + + It can be used with any type that supports the ``<=`` operator, + including numbers, dates and times, strings, sets, and so on. + """ + + le: SupportsLe + + +@runtime_checkable +class GroupedMetadata(Protocol): + """A grouping of multiple objects, like typing.Unpack. + + `GroupedMetadata` on its own is not metadata and has no meaning. + All of the constraints and metadata should be fully expressable + in terms of the `BaseMetadata`'s returned by `GroupedMetadata.__iter__()`. + + Concrete implementations should override `GroupedMetadata.__iter__()` + to add their own metadata. + For example: + + >>> @dataclass + >>> class Field(GroupedMetadata): + >>> gt: float | None = None + >>> description: str | None = None + ... + >>> def __iter__(self) -> Iterable[object]: + >>> if self.gt is not None: + >>> yield Gt(self.gt) + >>> if self.description is not None: + >>> yield Description(self.gt) + + Also see the implementation of `Interval` below for an example. + + Parsers should recognize this and unpack it so that it can be used + both with and without unpacking: + + - `Annotated[int, Field(...)]` (parser must unpack Field) + - `Annotated[int, *Field(...)]` (PEP-646) + """ # noqa: trailing-whitespace + + @property + def __is_annotated_types_grouped_metadata__(self) -> Literal[True]: + return True + + def __iter__(self) -> Iterator[object]: + ... + + if not TYPE_CHECKING: + __slots__ = () # allow subclasses to use slots + + def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: + # Basic ABC like functionality without the complexity of an ABC + super().__init_subclass__(*args, **kwargs) + if cls.__iter__ is GroupedMetadata.__iter__: + raise TypeError("Can't subclass GroupedMetadata without implementing __iter__") + + def __iter__(self) -> Iterator[object]: # noqa: F811 + raise NotImplementedError # more helpful than "None has no attribute..." type errors + + +@dataclass(frozen=True, **KW_ONLY, **SLOTS) +class Interval(GroupedMetadata): + """Interval can express inclusive or exclusive bounds with a single object. + + It accepts keyword arguments ``gt``, ``ge``, ``lt``, and/or ``le``, which + are interpreted the same way as the single-bound constraints. + """ + + gt: Union[SupportsGt, None] = None + ge: Union[SupportsGe, None] = None + lt: Union[SupportsLt, None] = None + le: Union[SupportsLe, None] = None + + def __iter__(self) -> Iterator[BaseMetadata]: + """Unpack an Interval into zero or more single-bounds.""" + if self.gt is not None: + yield Gt(self.gt) + if self.ge is not None: + yield Ge(self.ge) + if self.lt is not None: + yield Lt(self.lt) + if self.le is not None: + yield Le(self.le) + + +@dataclass(frozen=True, **SLOTS) +class MultipleOf(BaseMetadata): + """MultipleOf(multiple_of=x) might be interpreted in two ways: + + 1. Python semantics, implying ``value % multiple_of == 0``, or + 2. JSONschema semantics, where ``int(value / multiple_of) == value / multiple_of`` + + We encourage users to be aware of these two common interpretations, + and libraries to carefully document which they implement. + """ + + multiple_of: Union[SupportsDiv, SupportsMod] + + +@dataclass(frozen=True, **SLOTS) +class MinLen(BaseMetadata): + """ + MinLen() implies minimum inclusive length, + e.g. ``len(value) >= min_length``. + """ + + min_length: Annotated[int, Ge(0)] + + +@dataclass(frozen=True, **SLOTS) +class MaxLen(BaseMetadata): + """ + MaxLen() implies maximum inclusive length, + e.g. ``len(value) <= max_length``. + """ + + max_length: Annotated[int, Ge(0)] + + +@dataclass(frozen=True, **SLOTS) +class Len(GroupedMetadata): + """ + Len() implies that ``min_length <= len(value) <= max_length``. + + Upper bound may be omitted or ``None`` to indicate no upper length bound. + """ + + min_length: Annotated[int, Ge(0)] = 0 + max_length: Optional[Annotated[int, Ge(0)]] = None + + def __iter__(self) -> Iterator[BaseMetadata]: + """Unpack a Len into zone or more single-bounds.""" + if self.min_length > 0: + yield MinLen(self.min_length) + if self.max_length is not None: + yield MaxLen(self.max_length) + + +@dataclass(frozen=True, **SLOTS) +class Timezone(BaseMetadata): + """Timezone(tz=...) requires a datetime to be aware (or ``tz=None``, naive). + + ``Annotated[datetime, Timezone(None)]`` must be a naive datetime. + ``Timezone[...]`` (the ellipsis literal) expresses that the datetime must be + tz-aware but any timezone is allowed. + + You may also pass a specific timezone string or tzinfo object such as + ``Timezone(timezone.utc)`` or ``Timezone("Africa/Abidjan")`` to express that + you only allow a specific timezone, though we note that this is often + a symptom of poor design. + """ + + tz: Union[str, tzinfo, EllipsisType, None] + + +@dataclass(frozen=True, **SLOTS) +class Unit(BaseMetadata): + """Indicates that the value is a physical quantity with the specified unit. + + It is intended for usage with numeric types, where the value represents the + magnitude of the quantity. For example, ``distance: Annotated[float, Unit('m')]`` + or ``speed: Annotated[float, Unit('m/s')]``. + + Interpretation of the unit string is left to the discretion of the consumer. + It is suggested to follow conventions established by python libraries that work + with physical quantities, such as + + - ``pint`` : + - ``astropy.units``: + + For indicating a quantity with a certain dimensionality but without a specific unit + it is recommended to use square brackets, e.g. `Annotated[float, Unit('[time]')]`. + Note, however, ``annotated_types`` itself makes no use of the unit string. + """ + + unit: str + + +@dataclass(frozen=True, **SLOTS) +class Predicate(BaseMetadata): + """``Predicate(func: Callable)`` implies `func(value)` is truthy for valid values. + + Users should prefer statically inspectable metadata, but if you need the full + power and flexibility of arbitrary runtime predicates... here it is. + + We provide a few predefined predicates for common string constraints: + ``IsLower = Predicate(str.islower)``, ``IsUpper = Predicate(str.isupper)``, and + ``IsDigits = Predicate(str.isdigit)``. Users are encouraged to use methods which + can be given special handling, and avoid indirection like ``lambda s: s.lower()``. + + Some libraries might have special logic to handle certain predicates, e.g. by + checking for `str.isdigit` and using its presence to both call custom logic to + enforce digit-only strings, and customise some generated external schema. + + We do not specify what behaviour should be expected for predicates that raise + an exception. For example `Annotated[int, Predicate(str.isdigit)]` might silently + skip invalid constraints, or statically raise an error; or it might try calling it + and then propagate or discard the resulting exception. + """ + + func: Callable[[Any], bool] + + def __repr__(self) -> str: + if getattr(self.func, "__name__", "") == "": + return f"{self.__class__.__name__}({self.func!r})" + if isinstance(self.func, (types.MethodType, types.BuiltinMethodType)) and ( + namespace := getattr(self.func.__self__, "__name__", None) + ): + return f"{self.__class__.__name__}({namespace}.{self.func.__name__})" + if isinstance(self.func, type(str.isascii)): # method descriptor + return f"{self.__class__.__name__}({self.func.__qualname__})" + return f"{self.__class__.__name__}({self.func.__name__})" + + +@dataclass +class Not: + func: Callable[[Any], bool] + + def __call__(self, __v: Any) -> bool: + return not self.func(__v) + + +_StrType = TypeVar("_StrType", bound=str) + +LowerCase = Annotated[_StrType, Predicate(str.islower)] +""" +Return True if the string is a lowercase string, False otherwise. + +A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string. +""" # noqa: E501 +UpperCase = Annotated[_StrType, Predicate(str.isupper)] +""" +Return True if the string is an uppercase string, False otherwise. + +A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string. +""" # noqa: E501 +IsDigit = Annotated[_StrType, Predicate(str.isdigit)] +IsDigits = IsDigit # type: ignore # plural for backwards compatibility, see #63 +""" +Return True if the string is a digit string, False otherwise. + +A string is a digit string if all characters in the string are digits and there is at least one character in the string. +""" # noqa: E501 +IsAscii = Annotated[_StrType, Predicate(str.isascii)] +""" +Return True if all characters in the string are ASCII, False otherwise. + +ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too. +""" + +_NumericType = TypeVar('_NumericType', bound=Union[SupportsFloat, SupportsIndex]) +IsFinite = Annotated[_NumericType, Predicate(math.isfinite)] +"""Return True if x is neither an infinity nor a NaN, and False otherwise.""" +IsNotFinite = Annotated[_NumericType, Predicate(Not(math.isfinite))] +"""Return True if x is one of infinity or NaN, and False otherwise""" +IsNan = Annotated[_NumericType, Predicate(math.isnan)] +"""Return True if x is a NaN (not a number), and False otherwise.""" +IsNotNan = Annotated[_NumericType, Predicate(Not(math.isnan))] +"""Return True if x is anything but NaN (not a number), and False otherwise.""" +IsInfinite = Annotated[_NumericType, Predicate(math.isinf)] +"""Return True if x is a positive or negative infinity, and False otherwise.""" +IsNotInfinite = Annotated[_NumericType, Predicate(Not(math.isinf))] +"""Return True if x is neither a positive or negative infinity, and False otherwise.""" + +try: + from typing_extensions import DocInfo, doc # type: ignore [attr-defined] +except ImportError: + + @dataclass(frozen=True, **SLOTS) + class DocInfo: # type: ignore [no-redef] + """ " + The return value of doc(), mainly to be used by tools that want to extract the + Annotated documentation at runtime. + """ + + documentation: str + """The documentation string passed to doc().""" + + def doc( + documentation: str, + ) -> DocInfo: + """ + Add documentation to a type annotation inside of Annotated. + + For example: + + >>> def hi(name: Annotated[int, doc("The name of the user")]) -> None: ... + """ + return DocInfo(documentation) diff --git a/env/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..06c406d Binary files /dev/null and b/env/Lib/site-packages/annotated_types/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/annotated_types/__pycache__/test_cases.cpython-311.pyc b/env/Lib/site-packages/annotated_types/__pycache__/test_cases.cpython-311.pyc new file mode 100644 index 0000000..416125f Binary files /dev/null and b/env/Lib/site-packages/annotated_types/__pycache__/test_cases.cpython-311.pyc differ diff --git a/env/Lib/site-packages/annotated_types/py.typed b/env/Lib/site-packages/annotated_types/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/annotated_types/test_cases.py b/env/Lib/site-packages/annotated_types/test_cases.py new file mode 100644 index 0000000..d9164d6 --- /dev/null +++ b/env/Lib/site-packages/annotated_types/test_cases.py @@ -0,0 +1,151 @@ +import math +import sys +from datetime import date, datetime, timedelta, timezone +from decimal import Decimal +from typing import Any, Dict, Iterable, Iterator, List, NamedTuple, Set, Tuple + +if sys.version_info < (3, 9): + from typing_extensions import Annotated +else: + from typing import Annotated + +import annotated_types as at + + +class Case(NamedTuple): + """ + A test case for `annotated_types`. + """ + + annotation: Any + valid_cases: Iterable[Any] + invalid_cases: Iterable[Any] + + +def cases() -> Iterable[Case]: + # Gt, Ge, Lt, Le + yield Case(Annotated[int, at.Gt(4)], (5, 6, 1000), (4, 0, -1)) + yield Case(Annotated[float, at.Gt(0.5)], (0.6, 0.7, 0.8, 0.9), (0.5, 0.0, -0.1)) + yield Case( + Annotated[datetime, at.Gt(datetime(2000, 1, 1))], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + [datetime(2000, 1, 1), datetime(1999, 12, 31)], + ) + yield Case( + Annotated[datetime, at.Gt(date(2000, 1, 1))], + [date(2000, 1, 2), date(2000, 1, 3)], + [date(2000, 1, 1), date(1999, 12, 31)], + ) + yield Case( + Annotated[datetime, at.Gt(Decimal('1.123'))], + [Decimal('1.1231'), Decimal('123')], + [Decimal('1.123'), Decimal('0')], + ) + + yield Case(Annotated[int, at.Ge(4)], (4, 5, 6, 1000, 4), (0, -1)) + yield Case(Annotated[float, at.Ge(0.5)], (0.5, 0.6, 0.7, 0.8, 0.9), (0.4, 0.0, -0.1)) + yield Case( + Annotated[datetime, at.Ge(datetime(2000, 1, 1))], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + [datetime(1998, 1, 1), datetime(1999, 12, 31)], + ) + + yield Case(Annotated[int, at.Lt(4)], (0, -1), (4, 5, 6, 1000, 4)) + yield Case(Annotated[float, at.Lt(0.5)], (0.4, 0.0, -0.1), (0.5, 0.6, 0.7, 0.8, 0.9)) + yield Case( + Annotated[datetime, at.Lt(datetime(2000, 1, 1))], + [datetime(1999, 12, 31), datetime(1999, 12, 31)], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + ) + + yield Case(Annotated[int, at.Le(4)], (4, 0, -1), (5, 6, 1000)) + yield Case(Annotated[float, at.Le(0.5)], (0.5, 0.0, -0.1), (0.6, 0.7, 0.8, 0.9)) + yield Case( + Annotated[datetime, at.Le(datetime(2000, 1, 1))], + [datetime(2000, 1, 1), datetime(1999, 12, 31)], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + ) + + # Interval + yield Case(Annotated[int, at.Interval(gt=4)], (5, 6, 1000), (4, 0, -1)) + yield Case(Annotated[int, at.Interval(gt=4, lt=10)], (5, 6), (4, 10, 1000, 0, -1)) + yield Case(Annotated[float, at.Interval(ge=0.5, le=1)], (0.5, 0.9, 1), (0.49, 1.1)) + yield Case( + Annotated[datetime, at.Interval(gt=datetime(2000, 1, 1), le=datetime(2000, 1, 3))], + [datetime(2000, 1, 2), datetime(2000, 1, 3)], + [datetime(2000, 1, 1), datetime(2000, 1, 4)], + ) + + yield Case(Annotated[int, at.MultipleOf(multiple_of=3)], (0, 3, 9), (1, 2, 4)) + yield Case(Annotated[float, at.MultipleOf(multiple_of=0.5)], (0, 0.5, 1, 1.5), (0.4, 1.1)) + + # lengths + + yield Case(Annotated[str, at.MinLen(3)], ('123', '1234', 'x' * 10), ('', '1', '12')) + yield Case(Annotated[str, at.Len(3)], ('123', '1234', 'x' * 10), ('', '1', '12')) + yield Case(Annotated[List[int], at.MinLen(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2])) + yield Case(Annotated[List[int], at.Len(3)], ([1, 2, 3], [1, 2, 3, 4], [1] * 10), ([], [1], [1, 2])) + + yield Case(Annotated[str, at.MaxLen(4)], ('', '1234'), ('12345', 'x' * 10)) + yield Case(Annotated[str, at.Len(0, 4)], ('', '1234'), ('12345', 'x' * 10)) + yield Case(Annotated[List[str], at.MaxLen(4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10)) + yield Case(Annotated[List[str], at.Len(0, 4)], ([], ['a', 'bcdef'], ['a', 'b', 'c']), (['a'] * 5, ['b'] * 10)) + + yield Case(Annotated[str, at.Len(3, 5)], ('123', '12345'), ('', '1', '12', '123456', 'x' * 10)) + yield Case(Annotated[str, at.Len(3, 3)], ('123',), ('12', '1234')) + + yield Case(Annotated[Dict[int, int], at.Len(2, 3)], [{1: 1, 2: 2}], [{}, {1: 1}, {1: 1, 2: 2, 3: 3, 4: 4}]) + yield Case(Annotated[Set[int], at.Len(2, 3)], ({1, 2}, {1, 2, 3}), (set(), {1}, {1, 2, 3, 4})) + yield Case(Annotated[Tuple[int, ...], at.Len(2, 3)], ((1, 2), (1, 2, 3)), ((), (1,), (1, 2, 3, 4))) + + # Timezone + + yield Case( + Annotated[datetime, at.Timezone(None)], [datetime(2000, 1, 1)], [datetime(2000, 1, 1, tzinfo=timezone.utc)] + ) + yield Case( + Annotated[datetime, at.Timezone(...)], [datetime(2000, 1, 1, tzinfo=timezone.utc)], [datetime(2000, 1, 1)] + ) + yield Case( + Annotated[datetime, at.Timezone(timezone.utc)], + [datetime(2000, 1, 1, tzinfo=timezone.utc)], + [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))], + ) + yield Case( + Annotated[datetime, at.Timezone('Europe/London')], + [datetime(2000, 1, 1, tzinfo=timezone(timedelta(0), name='Europe/London'))], + [datetime(2000, 1, 1), datetime(2000, 1, 1, tzinfo=timezone(timedelta(hours=6)))], + ) + + # Quantity + + yield Case(Annotated[float, at.Unit(unit='m')], (5, 4.2), ('5m', '4.2m')) + + # predicate types + + yield Case(at.LowerCase[str], ['abc', 'foobar'], ['', 'A', 'Boom']) + yield Case(at.UpperCase[str], ['ABC', 'DEFO'], ['', 'a', 'abc', 'AbC']) + yield Case(at.IsDigit[str], ['123'], ['', 'ab', 'a1b2']) + yield Case(at.IsAscii[str], ['123', 'foo bar'], ['£100', '😊', 'whatever 👀']) + + yield Case(Annotated[int, at.Predicate(lambda x: x % 2 == 0)], [0, 2, 4], [1, 3, 5]) + + yield Case(at.IsFinite[float], [1.23], [math.nan, math.inf, -math.inf]) + yield Case(at.IsNotFinite[float], [math.nan, math.inf], [1.23]) + yield Case(at.IsNan[float], [math.nan], [1.23, math.inf]) + yield Case(at.IsNotNan[float], [1.23, math.inf], [math.nan]) + yield Case(at.IsInfinite[float], [math.inf], [math.nan, 1.23]) + yield Case(at.IsNotInfinite[float], [math.nan, 1.23], [math.inf]) + + # check stacked predicates + yield Case(at.IsInfinite[Annotated[float, at.Predicate(lambda x: x > 0)]], [math.inf], [-math.inf, 1.23, math.nan]) + + # doc + yield Case(Annotated[int, at.doc("A number")], [1, 2], []) + + # custom GroupedMetadata + class MyCustomGroupedMetadata(at.GroupedMetadata): + def __iter__(self) -> Iterator[at.Predicate]: + yield at.Predicate(lambda x: float(x).is_integer()) + + yield Case(Annotated[float, MyCustomGroupedMetadata()], [0, 2.0], [0.01, 1.5]) diff --git a/env/Lib/site-packages/async_timeout-4.0.3.dist-info/INSTALLER b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/async_timeout-4.0.3.dist-info/LICENSE b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/LICENSE new file mode 100644 index 0000000..033c86b --- /dev/null +++ b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/LICENSE @@ -0,0 +1,13 @@ +Copyright 2016-2020 aio-libs collaboration. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/env/Lib/site-packages/async_timeout-4.0.3.dist-info/METADATA b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/METADATA new file mode 100644 index 0000000..d8dd6d1 --- /dev/null +++ b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/METADATA @@ -0,0 +1,131 @@ +Metadata-Version: 2.1 +Name: async-timeout +Version: 4.0.3 +Summary: Timeout context manager for asyncio programs +Home-page: https://github.com/aio-libs/async-timeout +Author: Andrew Svetlov +Author-email: andrew.svetlov@gmail.com +License: Apache 2 +Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby +Project-URL: CI: GitHub Actions, https://github.com/aio-libs/async-timeout/actions +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/async-timeout +Project-URL: GitHub: issues, https://github.com/aio-libs/async-timeout/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/async-timeout +Classifier: Development Status :: 5 - Production/Stable +Classifier: Topic :: Software Development :: Libraries +Classifier: Framework :: AsyncIO +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: typing-extensions >=3.6.5 ; python_version < "3.8" + +async-timeout +============= +.. image:: https://travis-ci.com/aio-libs/async-timeout.svg?branch=master + :target: https://travis-ci.com/aio-libs/async-timeout +.. image:: https://codecov.io/gh/aio-libs/async-timeout/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/async-timeout +.. image:: https://img.shields.io/pypi/v/async-timeout.svg + :target: https://pypi.python.org/pypi/async-timeout +.. image:: https://badges.gitter.im/Join%20Chat.svg + :target: https://gitter.im/aio-libs/Lobby + :alt: Chat on Gitter + +asyncio-compatible timeout context manager. + + +Usage example +------------- + + +The context manager is useful in cases when you want to apply timeout +logic around block of code or in cases when ``asyncio.wait_for()`` is +not suitable. Also it's much faster than ``asyncio.wait_for()`` +because ``timeout`` doesn't create a new task. + +The ``timeout(delay, *, loop=None)`` call returns a context manager +that cancels a block on *timeout* expiring:: + + from async_timeout import timeout + async with timeout(1.5): + await inner() + +1. If ``inner()`` is executed faster than in ``1.5`` seconds nothing + happens. +2. Otherwise ``inner()`` is cancelled internally by sending + ``asyncio.CancelledError`` into but ``asyncio.TimeoutError`` is + raised outside of context manager scope. + +*timeout* parameter could be ``None`` for skipping timeout functionality. + + +Alternatively, ``timeout_at(when)`` can be used for scheduling +at the absolute time:: + + loop = asyncio.get_event_loop() + now = loop.time() + + async with timeout_at(now + 1.5): + await inner() + + +Please note: it is not POSIX time but a time with +undefined starting base, e.g. the time of the system power on. + + +Context manager has ``.expired`` property for check if timeout happens +exactly in context manager:: + + async with timeout(1.5) as cm: + await inner() + print(cm.expired) + +The property is ``True`` if ``inner()`` execution is cancelled by +timeout context manager. + +If ``inner()`` call explicitly raises ``TimeoutError`` ``cm.expired`` +is ``False``. + +The scheduled deadline time is available as ``.deadline`` property:: + + async with timeout(1.5) as cm: + cm.deadline + +Not finished yet timeout can be rescheduled by ``shift_by()`` +or ``shift_to()`` methods:: + + async with timeout(1.5) as cm: + cm.shift(1) # add another second on waiting + cm.update(loop.time() + 5) # reschedule to now+5 seconds + +Rescheduling is forbidden if the timeout is expired or after exit from ``async with`` +code block. + + +Installation +------------ + +:: + + $ pip install async-timeout + +The library is Python 3 only! + + + +Authors and License +------------------- + +The module is written by Andrew Svetlov. + +It's *Apache 2* licensed and freely available. diff --git a/env/Lib/site-packages/async_timeout-4.0.3.dist-info/RECORD b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/RECORD new file mode 100644 index 0000000..46abe88 --- /dev/null +++ b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/RECORD @@ -0,0 +1,10 @@ +async_timeout-4.0.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +async_timeout-4.0.3.dist-info/LICENSE,sha256=4Y17uPUT4sRrtYXJS1hb0wcg3TzLId2weG9y0WZY-Sw,568 +async_timeout-4.0.3.dist-info/METADATA,sha256=WQVcnDIXQ2ntebcm-vYjhNLg_VMeTWw13_ReT-U36J4,4209 +async_timeout-4.0.3.dist-info/RECORD,, +async_timeout-4.0.3.dist-info/WHEEL,sha256=5sUXSg9e4bi7lTLOHcm6QEYwO5TIF1TNbTSVFVjcJcc,92 +async_timeout-4.0.3.dist-info/top_level.txt,sha256=9oM4e7Twq8iD_7_Q3Mz0E6GPIB6vJvRFo-UBwUQtBDU,14 +async_timeout-4.0.3.dist-info/zip-safe,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +async_timeout/__init__.py,sha256=A0VOqDGQ3cCPFp0NZJKIbx_VRP1Y2xPtQOZebVIUB88,7242 +async_timeout/__pycache__/__init__.cpython-311.pyc,, +async_timeout/py.typed,sha256=tyozzRT1fziXETDxokmuyt6jhOmtjUbnVNJdZcG7ik0,12 diff --git a/env/Lib/site-packages/async_timeout-4.0.3.dist-info/WHEEL b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/WHEEL new file mode 100644 index 0000000..2c08da0 --- /dev/null +++ b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/env/Lib/site-packages/async_timeout-4.0.3.dist-info/top_level.txt b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/top_level.txt new file mode 100644 index 0000000..ad29955 --- /dev/null +++ b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/top_level.txt @@ -0,0 +1 @@ +async_timeout diff --git a/env/Lib/site-packages/async_timeout-4.0.3.dist-info/zip-safe b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/zip-safe new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/env/Lib/site-packages/async_timeout-4.0.3.dist-info/zip-safe @@ -0,0 +1 @@ + diff --git a/env/Lib/site-packages/async_timeout/__init__.py b/env/Lib/site-packages/async_timeout/__init__.py new file mode 100644 index 0000000..1ffb069 --- /dev/null +++ b/env/Lib/site-packages/async_timeout/__init__.py @@ -0,0 +1,239 @@ +import asyncio +import enum +import sys +import warnings +from types import TracebackType +from typing import Optional, Type + + +if sys.version_info >= (3, 8): + from typing import final +else: + from typing_extensions import final + + +if sys.version_info >= (3, 11): + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + task.uncancel() + +else: + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + pass + + +__version__ = "4.0.3" + + +__all__ = ("timeout", "timeout_at", "Timeout") + + +def timeout(delay: Optional[float]) -> "Timeout": + """timeout context manager. + + Useful in cases when you want to apply timeout logic around block + of code or in cases when asyncio.wait_for is not suitable. For example: + + >>> async with timeout(0.001): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + delay - value in seconds or None to disable timeout logic + """ + loop = asyncio.get_running_loop() + if delay is not None: + deadline = loop.time() + delay # type: Optional[float] + else: + deadline = None + return Timeout(deadline, loop) + + +def timeout_at(deadline: Optional[float]) -> "Timeout": + """Schedule the timeout at absolute time. + + deadline argument points on the time in the same clock system + as loop.time(). + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + + >>> async with timeout_at(loop.time() + 10): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + """ + loop = asyncio.get_running_loop() + return Timeout(deadline, loop) + + +class _State(enum.Enum): + INIT = "INIT" + ENTER = "ENTER" + TIMEOUT = "TIMEOUT" + EXIT = "EXIT" + + +@final +class Timeout: + # Internal class, please don't instantiate it directly + # Use timeout() and timeout_at() public factories instead. + # + # Implementation note: `async with timeout()` is preferred + # over `with timeout()`. + # While technically the Timeout class implementation + # doesn't need to be async at all, + # the `async with` statement explicitly points that + # the context manager should be used from async function context. + # + # This design allows to avoid many silly misusages. + # + # TimeoutError is raised immediately when scheduled + # if the deadline is passed. + # The purpose is to time out as soon as possible + # without waiting for the next await expression. + + __slots__ = ("_deadline", "_loop", "_state", "_timeout_handler", "_task") + + def __init__( + self, deadline: Optional[float], loop: asyncio.AbstractEventLoop + ) -> None: + self._loop = loop + self._state = _State.INIT + + self._task: Optional["asyncio.Task[object]"] = None + self._timeout_handler = None # type: Optional[asyncio.Handle] + if deadline is None: + self._deadline = None # type: Optional[float] + else: + self.update(deadline) + + def __enter__(self) -> "Timeout": + warnings.warn( + "with timeout() is deprecated, use async with timeout() instead", + DeprecationWarning, + stacklevel=2, + ) + self._do_enter() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + async def __aenter__(self) -> "Timeout": + self._do_enter() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + @property + def expired(self) -> bool: + """Is timeout expired during execution?""" + return self._state == _State.TIMEOUT + + @property + def deadline(self) -> Optional[float]: + return self._deadline + + def reject(self) -> None: + """Reject scheduled timeout if any.""" + # cancel is maybe better name but + # task.cancel() raises CancelledError in asyncio world. + if self._state not in (_State.INIT, _State.ENTER): + raise RuntimeError(f"invalid state {self._state.value}") + self._reject() + + def _reject(self) -> None: + self._task = None + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._timeout_handler = None + + def shift(self, delay: float) -> None: + """Advance timeout on delay seconds. + + The delay can be negative. + + Raise RuntimeError if shift is called when deadline is not scheduled + """ + deadline = self._deadline + if deadline is None: + raise RuntimeError("cannot shift timeout if deadline is not scheduled") + self.update(deadline + delay) + + def update(self, deadline: float) -> None: + """Set deadline to absolute value. + + deadline argument points on the time in the same clock system + as loop.time(). + + If new deadline is in the past the timeout is raised immediately. + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + """ + if self._state == _State.EXIT: + raise RuntimeError("cannot reschedule after exit from context manager") + if self._state == _State.TIMEOUT: + raise RuntimeError("cannot reschedule expired timeout") + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._deadline = deadline + if self._state != _State.INIT: + self._reschedule() + + def _reschedule(self) -> None: + assert self._state == _State.ENTER + deadline = self._deadline + if deadline is None: + return + + now = self._loop.time() + if self._timeout_handler is not None: + self._timeout_handler.cancel() + + self._task = asyncio.current_task() + if deadline <= now: + self._timeout_handler = self._loop.call_soon(self._on_timeout) + else: + self._timeout_handler = self._loop.call_at(deadline, self._on_timeout) + + def _do_enter(self) -> None: + if self._state != _State.INIT: + raise RuntimeError(f"invalid state {self._state.value}") + self._state = _State.ENTER + self._reschedule() + + def _do_exit(self, exc_type: Optional[Type[BaseException]]) -> None: + if exc_type is asyncio.CancelledError and self._state == _State.TIMEOUT: + assert self._task is not None + _uncancel_task(self._task) + self._timeout_handler = None + self._task = None + raise asyncio.TimeoutError + # timeout has not expired + self._state = _State.EXIT + self._reject() + return None + + def _on_timeout(self) -> None: + assert self._task is not None + self._task.cancel() + self._state = _State.TIMEOUT + # drop the reference early + self._timeout_handler = None diff --git a/env/Lib/site-packages/async_timeout/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/async_timeout/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..2548378 Binary files /dev/null and b/env/Lib/site-packages/async_timeout/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/async_timeout/py.typed b/env/Lib/site-packages/async_timeout/py.typed new file mode 100644 index 0000000..3b94f91 --- /dev/null +++ b/env/Lib/site-packages/async_timeout/py.typed @@ -0,0 +1 @@ +Placeholder diff --git a/env/Lib/site-packages/asyncpg-0.29.0.dist-info/AUTHORS b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/AUTHORS new file mode 100644 index 0000000..64bc938 --- /dev/null +++ b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/AUTHORS @@ -0,0 +1,6 @@ +Main contributors +================= + +MagicStack Inc.: + Elvis Pranskevichus + Yury Selivanov diff --git a/env/Lib/site-packages/asyncpg-0.29.0.dist-info/INSTALLER b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/asyncpg-0.29.0.dist-info/LICENSE b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/LICENSE new file mode 100644 index 0000000..d931386 --- /dev/null +++ b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/LICENSE @@ -0,0 +1,204 @@ +Copyright (C) 2016-present the asyncpg authors and contributors. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (C) 2016-present the asyncpg authors and contributors + + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/env/Lib/site-packages/asyncpg-0.29.0.dist-info/METADATA b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/METADATA new file mode 100644 index 0000000..08124ba --- /dev/null +++ b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/METADATA @@ -0,0 +1,127 @@ +Metadata-Version: 2.1 +Name: asyncpg +Version: 0.29.0 +Summary: An asyncio PostgreSQL driver +Author-email: MagicStack Inc +License: Apache License, Version 2.0 +Project-URL: github, https://github.com/MagicStack/asyncpg +Keywords: database,postgres +Classifier: Development Status :: 5 - Production/Stable +Classifier: Framework :: AsyncIO +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Database :: Front-Ends +Requires-Python: >=3.8.0 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: AUTHORS +Requires-Dist: async-timeout >=4.0.3 ; python_version < "3.12.0" +Provides-Extra: docs +Requires-Dist: Sphinx ~=5.3.0 ; extra == 'docs' +Requires-Dist: sphinxcontrib-asyncio ~=0.3.0 ; extra == 'docs' +Requires-Dist: sphinx-rtd-theme >=1.2.2 ; extra == 'docs' +Provides-Extra: test +Requires-Dist: flake8 ~=6.1 ; extra == 'test' +Requires-Dist: uvloop >=0.15.3 ; (platform_system != "Windows" and python_version < "3.12.0") and extra == 'test' + +asyncpg -- A fast PostgreSQL Database Client Library for Python/asyncio +======================================================================= + +.. image:: https://github.com/MagicStack/asyncpg/workflows/Tests/badge.svg + :target: https://github.com/MagicStack/asyncpg/actions?query=workflow%3ATests+branch%3Amaster + :alt: GitHub Actions status +.. image:: https://img.shields.io/pypi/v/asyncpg.svg + :target: https://pypi.python.org/pypi/asyncpg + +**asyncpg** is a database interface library designed specifically for +PostgreSQL and Python/asyncio. asyncpg is an efficient, clean implementation +of PostgreSQL server binary protocol for use with Python's ``asyncio`` +framework. You can read more about asyncpg in an introductory +`blog post `_. + +asyncpg requires Python 3.8 or later and is supported for PostgreSQL +versions 9.5 to 16. Older PostgreSQL versions or other databases implementing +the PostgreSQL protocol *may* work, but are not being actively tested. + + +Documentation +------------- + +The project documentation can be found +`here `_. + + +Performance +----------- + +In our testing asyncpg is, on average, **5x** faster than psycopg3. + +.. image:: https://raw.githubusercontent.com/MagicStack/asyncpg/master/performance.png?fddca40ab0 + :target: https://gistpreview.github.io/?0ed296e93523831ea0918d42dd1258c2 + +The above results are a geometric mean of benchmarks obtained with PostgreSQL +`client driver benchmarking toolbench `_ +in June 2023 (click on the chart to see full details). + + +Features +-------- + +asyncpg implements PostgreSQL server protocol natively and exposes its +features directly, as opposed to hiding them behind a generic facade +like DB-API. + +This enables asyncpg to have easy-to-use support for: + +* **prepared statements** +* **scrollable cursors** +* **partial iteration** on query results +* automatic encoding and decoding of composite types, arrays, + and any combination of those +* straightforward support for custom data types + + +Installation +------------ + +asyncpg is available on PyPI and has no dependencies. +Use pip to install:: + + $ pip install asyncpg + + +Basic Usage +----------- + +.. code-block:: python + + import asyncio + import asyncpg + + async def run(): + conn = await asyncpg.connect(user='user', password='password', + database='database', host='127.0.0.1') + values = await conn.fetch( + 'SELECT * FROM mytable WHERE id = $1', + 10, + ) + await conn.close() + + loop = asyncio.get_event_loop() + loop.run_until_complete(run()) + + +License +------- + +asyncpg is developed and distributed under the Apache 2.0 license. diff --git a/env/Lib/site-packages/asyncpg-0.29.0.dist-info/RECORD b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/RECORD new file mode 100644 index 0000000..15f385b --- /dev/null +++ b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/RECORD @@ -0,0 +1,111 @@ +asyncpg-0.29.0.dist-info/AUTHORS,sha256=eFUq_BnBQPCWi3PJTDNl8YCbrcNLfMIiN-b3x_1wTYk,136 +asyncpg-0.29.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +asyncpg-0.29.0.dist-info/LICENSE,sha256=CqxXCYIpatnpe8MnCEeeQM97YNV4fIrBh9hsFYPpLsA,11670 +asyncpg-0.29.0.dist-info/METADATA,sha256=_Vd2Lex_ABc_Zv1bjpfFzgdGrYecGl4sgSJdq1IriR4,4483 +asyncpg-0.29.0.dist-info/RECORD,, +asyncpg-0.29.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +asyncpg-0.29.0.dist-info/WHEEL,sha256=badvNS-y9fEq0X-qzdZYvql_JFjI7Xfw-wR8FsjoK0I,102 +asyncpg-0.29.0.dist-info/top_level.txt,sha256=DdhVhpzCq49mykkHNag6i9zuJx05_tx4CMZymM1F8dU,8 +asyncpg/__init__.py,sha256=EbywzGkj2v63N1p2vEs-K2GAuRvZnCesEDNrnl3u8sQ,582 +asyncpg/__pycache__/__init__.cpython-311.pyc,, +asyncpg/__pycache__/_asyncio_compat.cpython-311.pyc,, +asyncpg/__pycache__/_version.cpython-311.pyc,, +asyncpg/__pycache__/cluster.cpython-311.pyc,, +asyncpg/__pycache__/compat.cpython-311.pyc,, +asyncpg/__pycache__/connect_utils.cpython-311.pyc,, +asyncpg/__pycache__/connection.cpython-311.pyc,, +asyncpg/__pycache__/connresource.cpython-311.pyc,, +asyncpg/__pycache__/cursor.cpython-311.pyc,, +asyncpg/__pycache__/introspection.cpython-311.pyc,, +asyncpg/__pycache__/pool.cpython-311.pyc,, +asyncpg/__pycache__/prepared_stmt.cpython-311.pyc,, +asyncpg/__pycache__/serverversion.cpython-311.pyc,, +asyncpg/__pycache__/transaction.cpython-311.pyc,, +asyncpg/__pycache__/types.cpython-311.pyc,, +asyncpg/__pycache__/utils.cpython-311.pyc,, +asyncpg/_asyncio_compat.py,sha256=IDBWCPfxBOpSvvDE5SllI8qQLNHJxzxieTEi4ZsF6R0,2386 +asyncpg/_testbase/__init__.py,sha256=eFHWCy5DN4YtyJfsXivMyOmR1zMhTkJO-xlFfpf7kCQ,16593 +asyncpg/_testbase/__pycache__/__init__.cpython-311.pyc,, +asyncpg/_testbase/__pycache__/fuzzer.cpython-311.pyc,, +asyncpg/_testbase/fuzzer.py,sha256=nYsnhLXQEquuJtWjWx3feHoj5_Ctu9bH6VCQ2ZsphFc,10110 +asyncpg/_version.py,sha256=nqG2dBwjFrQZN2ThbMdhIgstJhmaMPUZTbgyOoTJRlA,589 +asyncpg/cluster.py,sha256=X8xil2DhPlYy8EE4mscsKjOHuFsVs1Hwpu71rhx-CUo,23971 +asyncpg/compat.py,sha256=Daw2GdDZT2lFXqrswcZxTLaWmPnhyeFkssL8YJJycSo,1830 +asyncpg/connect_utils.py,sha256=rdlSo1Ty2-HUYdcUib1jmRWlkmgs1faGnCTgk_EGpGM,36060 +asyncpg/connection.py,sha256=sYzIUIC7ski--9BiwUM6TrAPa4sQHTol78nc3wdHNPM,97882 +asyncpg/connresource.py,sha256=T0vpfsZuS96AkltQfpynAgPLLheVDy_hSj0ejcZkbAQ,1428 +asyncpg/cursor.py,sha256=noklB-NjAeYAhhI705QJuKuXoI7ZZ0hyMUKqMdDxTxw,9483 +asyncpg/exceptions/__init__.py,sha256=WQTAOBUrkIzIW12s78q-v-v06Uv8wRMgrmq_y69klSo,30024 +asyncpg/exceptions/__pycache__/__init__.cpython-311.pyc,, +asyncpg/exceptions/__pycache__/_base.cpython-311.pyc,, +asyncpg/exceptions/_base.py,sha256=CJy579cVjuf7JbIUY01MouaElHqg_obGC_cuT8nPtkQ,9559 +asyncpg/introspection.py,sha256=YiXPqQppb7713EKonWpw5nVdWE0Xa6IaG12HUpoBqQo,9249 +asyncpg/pgproto/__init__.pxd,sha256=d36iPoZbiEOs4JLdV2lApUgy664JJZVdAvZTznHs2Qc,218 +asyncpg/pgproto/__init__.py,sha256=d36iPoZbiEOs4JLdV2lApUgy664JJZVdAvZTznHs2Qc,218 +asyncpg/pgproto/__pycache__/__init__.cpython-311.pyc,, +asyncpg/pgproto/__pycache__/types.cpython-311.pyc,, +asyncpg/pgproto/buffer.pxd,sha256=meKBG5f1l2B5B71laYNnJxj7W2jO-S6lGzH0K6zIzXo,4518 +asyncpg/pgproto/buffer.pyx,sha256=0GRpd2zqAR3WcHOl8f2LtIGJrap_bFDiHvYZN6nWYGE,26127 +asyncpg/pgproto/codecs/__init__.pxd,sha256=MTQ7hYkJ2jdxsjGKquk6mNvfdepjFAhujOIcWA3vnkc,6170 +asyncpg/pgproto/codecs/bits.pyx,sha256=IBXVWM2NdWF--d54yvBfSdvFhxV_TQxB97d20dTFxRY,1522 +asyncpg/pgproto/codecs/bytea.pyx,sha256=4AVKSfhi25DR4N9XCm13O1ahWohGnd2wNwr-lW9jfsg,1031 +asyncpg/pgproto/codecs/context.pyx,sha256=gpE_ncSaAOi-sIC7ltC3K7E5yLokK_GP4Ekq9v4q2YM,649 +asyncpg/pgproto/codecs/datetime.pyx,sha256=aWVNKozk_YcsVAClaV6rc1eiuy3khx5lnwKnbZ-Bq3w,13254 +asyncpg/pgproto/codecs/float.pyx,sha256=XNUeYQKGBpyM6ySDD0L3W2Jg0cqvV5fh5Xf8y4r5ido,1065 +asyncpg/pgproto/codecs/geometry.pyx,sha256=A2raDcmGNftGi-EdsrB7CsZgk5BA3sp1RATh9bl0nwk,4829 +asyncpg/pgproto/codecs/hstore.pyx,sha256=Dx_IkFLLr9fN8cX8lThv-kXtC82itVzwZmwc-RgRKfw,2091 +asyncpg/pgproto/codecs/int.pyx,sha256=0lI3Elu--UmsZh5yzhkbAEQb3z0hnCAYb8M1llfI4gU,4670 +asyncpg/pgproto/codecs/json.pyx,sha256=q8OAGbUET_Mg8YEQXN08oOVp5ZgrPrIwl_5Up0rJMks,1511 +asyncpg/pgproto/codecs/jsonpath.pyx,sha256=z8OWN8Ls0S3-WoliBTGcE3OiLQFAAaIQ3fmFvH0Ut6I,862 +asyncpg/pgproto/codecs/misc.pyx,sha256=0v8FW97oI20zgvvricyatNsGHtNt86qy-RwDpZmWl4Q,500 +asyncpg/pgproto/codecs/network.pyx,sha256=144a6aVIDaVVk1hc0B0nSOUbt4c1pLkVDgrpGOI66fw,4056 +asyncpg/pgproto/codecs/numeric.pyx,sha256=MHDUUiUkZ6GS38snxQsPlkKGP2RcwyarWlhC72QAiwk,10729 +asyncpg/pgproto/codecs/pg_snapshot.pyx,sha256=xFPvsDqm2vmAu7LzWo3YpINZnK4qId9Bjw_EWZGx4go,1877 +asyncpg/pgproto/codecs/text.pyx,sha256=X28sw55ugCDuV81bE9A33rGNNNToUOI1mPnVViZbIcM,1564 +asyncpg/pgproto/codecs/tid.pyx,sha256=IJV_dQb0RZTIv16oXZLsZBG--9hP3yeIP2KyNzRw9Dg,1600 +asyncpg/pgproto/codecs/uuid.pyx,sha256=Qy-ctKASB6dEwxDeSjaKCtL7hBTWSPkjLh2SbesJDmI,882 +asyncpg/pgproto/consts.pxi,sha256=4znDppgjfgK1Jt-vrC-9ybK-wLhS2ZXHUu2iSanuAOI,387 +asyncpg/pgproto/cpythonx.pxd,sha256=Q0R3NqDfX3hMKYCv2EHRSAzBH2oQGQMCbJGivsPGHeQ,759 +asyncpg/pgproto/debug.pxd,sha256=8I8LhCtxx0ItNinKMUmC3TrwVpkuvYDDhP4OVse12ns,273 +asyncpg/pgproto/frb.pxd,sha256=qMMzdrR-_u9jZ42Jn5YBU1fKkczNtTbFGNLobi3lX7Y,1260 +asyncpg/pgproto/frb.pyx,sha256=7ARAMMP0nMQpkLCpKfAIl57vswVYNkRRQ3vEZ_f9xBA,421 +asyncpg/pgproto/hton.pxd,sha256=rt7WLZasAJplt3o1MYsIQlfTZGbecpgdLoQxOcJD-_Q,977 +asyncpg/pgproto/pgproto.cp311-win_amd64.pyd,sha256=o_mUBs4ryMsWy2f2SEYnKM76fCbXD5xrYohv8vMwyjY,239104 +asyncpg/pgproto/pgproto.pxd,sha256=vfSBam43bOQKliL0fGdt8608D_pBXXb-idnSuT6orUY,449 +asyncpg/pgproto/pgproto.pyx,sha256=bjCy8iIZj7IFj0BRegv87xpoYQkzrFvPFEyowko8nlg,1298 +asyncpg/pgproto/tohex.pxd,sha256=KhhZRaf-jl0jzOk_-XSBrd0asszmVFZ1CHaeCVE-unU,371 +asyncpg/pgproto/types.py,sha256=puk8hs92bhWBYxrdwWl_8p5y-e12bB4zoI8SlFoSkG4,13437 +asyncpg/pgproto/uuid.pyx,sha256=JtX2FXlWknQ1GbRIg0m8D7XVeISWK6dRFlCpe58QnIo,10296 +asyncpg/pool.py,sha256=wb_cIXYcbql1WyRrKf9wQppDACKypRHunntJ58Mp_i0,39298 +asyncpg/prepared_stmt.py,sha256=MkwHPt_uvNiLxpC3TJ7irGBaTcqRc7NdM3Mgme4JZv8,9251 +asyncpg/protocol/__init__.py,sha256=adVXDmUi0IYdAfRnqYXGP4o0Uyjv2DJfr8FrXRlT5eY,313 +asyncpg/protocol/__pycache__/__init__.cpython-311.pyc,, +asyncpg/protocol/codecs/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +asyncpg/protocol/codecs/__pycache__/__init__.cpython-311.pyc,, +asyncpg/protocol/codecs/array.pyx,sha256=OIkcbecdoh84ZPfT26nElg_yZp3EsCH8vkwuVMhycBg,30361 +asyncpg/protocol/codecs/base.pxd,sha256=FfPKRR1cKpJmTlm6kmjjcto8Zsdf2qb8r-0KbNNH_zs,6411 +asyncpg/protocol/codecs/base.pyx,sha256=qC6xr2IrW1IF5rBN0BwCV4gTtbbIIWpgWBXOeL0Rdpg,34370 +asyncpg/protocol/codecs/pgproto.pyx,sha256=vKWJ76Ht6bERXi-8gZAjiKOkZ29wJFpDcVt6or9SQO8,17659 +asyncpg/protocol/codecs/range.pyx,sha256=q7AprJMdRbF5R0hNLXQz42y1CSYiL2z51DHmPCX95Eo,6566 +asyncpg/protocol/codecs/record.pyx,sha256=RzE8ypCFSPiH4pJdEX6178UEd5TStpG3lwd0SEILhfI,2433 +asyncpg/protocol/codecs/textutils.pyx,sha256=O3QiS3R1_IDLT5U29cq3Nb_fLUoP-evX4ff93dW8Wrk,2110 +asyncpg/protocol/consts.pxi,sha256=wyf2ctwkBArBS20kiKZ9MuwEdHIORbjaWUmLAGT5grg,393 +asyncpg/protocol/coreproto.pxd,sha256=okdrg49H-NRRKMStnOkYWIHN3zGs48CvkWuOW9cEdbA,6344 +asyncpg/protocol/coreproto.pyx,sha256=HeyAdUbdED8j49rGTy-yT5v_if2FHKy_aRWGkMWXIRE,39168 +asyncpg/protocol/cpythonx.pxd,sha256=N0sNOn2zYq9LdVpCbk5l-UQEXZKJxlgTBEvuJRIia4E,632 +asyncpg/protocol/encodings.pyx,sha256=lq0YrGqKOS3S4bnfecDP4ReJwmpJFkoJDCWxdGa-QaM,1707 +asyncpg/protocol/pgtypes.pxi,sha256=WMJQUjwky0BRGoz1Uv-s55Sn9cn3fp_z-2s7ySErxCc,7190 +asyncpg/protocol/prepared_stmt.pxd,sha256=c1-Vj-6INV0c9EOjHn1H03dEah1lJ4zJWXa-G0WkGs8,1154 +asyncpg/protocol/prepared_stmt.pyx,sha256=glCnWmSowDGXqiM573IyHnw9X_LBAnMCp6ydPWkgqIw,13447 +asyncpg/protocol/protocol.cp311-win_amd64.pyd,sha256=MOse7WMZr15ZUe7jwNwQzbqKgNv9bblbz105XKi3KLc,639488 +asyncpg/protocol/protocol.pxd,sha256=ZCIKkZTttNMDbxjsu-M7Rw5P4hDV81fytK3i4AGvx10,2028 +asyncpg/protocol/protocol.pyx,sha256=4TDT0Ohedy4MHMpqCYSX4bGwJDKdvbX_j6D-hK3hnl8,35888 +asyncpg/protocol/record/__init__.pxd,sha256=CGH59K2pPrr6UG1ozslFIhC4NCzvxIOMzrVmkD-z21E,514 +asyncpg/protocol/scram.pxd,sha256=WHz6b-CFCPI3rePwxK096bZQR0mvI1iYprQ-ZuhrWdk,1330 +asyncpg/protocol/scram.pyx,sha256=PFqtLizBPPKKspPkI28djXT61mNmwbMSTCdPjweY3S8,14935 +asyncpg/protocol/settings.pxd,sha256=BPoU8ejCK8f6r0HoKnxNGRfN9zg6v2F46ZoxRpTUskw,1096 +asyncpg/protocol/settings.pyx,sha256=wZGBjkRir__BPFCwT-itJUmi2u6CgzShF3WKJog9Ovs,3901 +asyncpg/serverversion.py,sha256=WpWvDakphms881RaToOyHKAVS6wxaJMQfzetXJJsLnM,1850 +asyncpg/transaction.py,sha256=pXOb_B9gESb7M6jEumeSZvaQEoSF11_R9fNF820EtdQ,8743 +asyncpg/types.py,sha256=eVh6rdPWpcMWauLRMRUEuWniEVAMAbaniDucwcBwQkk,4830 +asyncpg/utils.py,sha256=38wIII-s9AOC-2cPFz6rX0hnEHNtSMSNdih-Mti2cyc,1412 diff --git a/env/Lib/site-packages/asyncpg-0.29.0.dist-info/REQUESTED b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/REQUESTED new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/asyncpg-0.29.0.dist-info/WHEEL b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/WHEEL new file mode 100644 index 0000000..6d16045 --- /dev/null +++ b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/env/Lib/site-packages/asyncpg-0.29.0.dist-info/top_level.txt b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/top_level.txt new file mode 100644 index 0000000..5789edd --- /dev/null +++ b/env/Lib/site-packages/asyncpg-0.29.0.dist-info/top_level.txt @@ -0,0 +1 @@ +asyncpg diff --git a/env/Lib/site-packages/asyncpg/__init__.py b/env/Lib/site-packages/asyncpg/__init__.py new file mode 100644 index 0000000..e8cd11e --- /dev/null +++ b/env/Lib/site-packages/asyncpg/__init__.py @@ -0,0 +1,19 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from .connection import connect, Connection # NOQA +from .exceptions import * # NOQA +from .pool import create_pool, Pool # NOQA +from .protocol import Record # NOQA +from .types import * # NOQA + + +from ._version import __version__ # NOQA + + +__all__ = ('connect', 'create_pool', 'Pool', 'Record', 'Connection') +__all__ += exceptions.__all__ # NOQA diff --git a/env/Lib/site-packages/asyncpg/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..66524bb Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/_asyncio_compat.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/_asyncio_compat.cpython-311.pyc new file mode 100644 index 0000000..7286cb9 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/_asyncio_compat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/_version.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/_version.cpython-311.pyc new file mode 100644 index 0000000..de1c1bd Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/_version.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/cluster.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/cluster.cpython-311.pyc new file mode 100644 index 0000000..4305821 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/cluster.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/compat.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/compat.cpython-311.pyc new file mode 100644 index 0000000..ed111d8 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/compat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/connect_utils.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/connect_utils.cpython-311.pyc new file mode 100644 index 0000000..c3d18d2 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/connect_utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/connection.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/connection.cpython-311.pyc new file mode 100644 index 0000000..107605d Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/connection.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/connresource.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/connresource.cpython-311.pyc new file mode 100644 index 0000000..ccccb4c Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/connresource.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/cursor.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/cursor.cpython-311.pyc new file mode 100644 index 0000000..d210915 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/cursor.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/introspection.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/introspection.cpython-311.pyc new file mode 100644 index 0000000..d1f763e Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/introspection.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/pool.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/pool.cpython-311.pyc new file mode 100644 index 0000000..46ee53c Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/pool.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/prepared_stmt.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/prepared_stmt.cpython-311.pyc new file mode 100644 index 0000000..24ec027 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/prepared_stmt.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/serverversion.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/serverversion.cpython-311.pyc new file mode 100644 index 0000000..cd7014b Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/serverversion.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/transaction.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/transaction.cpython-311.pyc new file mode 100644 index 0000000..f221e0f Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/transaction.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/types.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000..1b64a3e Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/types.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/__pycache__/utils.cpython-311.pyc b/env/Lib/site-packages/asyncpg/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000..31682ce Binary files /dev/null and b/env/Lib/site-packages/asyncpg/__pycache__/utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/_asyncio_compat.py b/env/Lib/site-packages/asyncpg/_asyncio_compat.py new file mode 100644 index 0000000..ad7dfd8 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/_asyncio_compat.py @@ -0,0 +1,87 @@ +# Backports from Python/Lib/asyncio for older Pythons +# +# Copyright (c) 2001-2023 Python Software Foundation; All Rights Reserved +# +# SPDX-License-Identifier: PSF-2.0 + + +import asyncio +import functools +import sys + +if sys.version_info < (3, 11): + from async_timeout import timeout as timeout_ctx +else: + from asyncio import timeout as timeout_ctx + + +async def wait_for(fut, timeout): + """Wait for the single Future or coroutine to complete, with timeout. + + Coroutine will be wrapped in Task. + + Returns result of the Future or coroutine. When a timeout occurs, + it cancels the task and raises TimeoutError. To avoid the task + cancellation, wrap it in shield(). + + If the wait is cancelled, the task is also cancelled. + + If the task supresses the cancellation and returns a value instead, + that value is returned. + + This function is a coroutine. + """ + # The special case for timeout <= 0 is for the following case: + # + # async def test_waitfor(): + # func_started = False + # + # async def func(): + # nonlocal func_started + # func_started = True + # + # try: + # await asyncio.wait_for(func(), 0) + # except asyncio.TimeoutError: + # assert not func_started + # else: + # assert False + # + # asyncio.run(test_waitfor()) + + if timeout is not None and timeout <= 0: + fut = asyncio.ensure_future(fut) + + if fut.done(): + return fut.result() + + await _cancel_and_wait(fut) + try: + return fut.result() + except asyncio.CancelledError as exc: + raise TimeoutError from exc + + async with timeout_ctx(timeout): + return await fut + + +async def _cancel_and_wait(fut): + """Cancel the *fut* future or task and wait until it completes.""" + + loop = asyncio.get_running_loop() + waiter = loop.create_future() + cb = functools.partial(_release_waiter, waiter) + fut.add_done_callback(cb) + + try: + fut.cancel() + # We cannot wait on *fut* directly to make + # sure _cancel_and_wait itself is reliably cancellable. + await waiter + finally: + fut.remove_done_callback(cb) + + +def _release_waiter(waiter, *args): + if not waiter.done(): + waiter.set_result(None) diff --git a/env/Lib/site-packages/asyncpg/_testbase/__init__.py b/env/Lib/site-packages/asyncpg/_testbase/__init__.py new file mode 100644 index 0000000..7aca834 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/_testbase/__init__.py @@ -0,0 +1,527 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import asyncio +import atexit +import contextlib +import functools +import inspect +import logging +import os +import re +import textwrap +import time +import traceback +import unittest + + +import asyncpg +from asyncpg import cluster as pg_cluster +from asyncpg import connection as pg_connection +from asyncpg import pool as pg_pool + +from . import fuzzer + + +@contextlib.contextmanager +def silence_asyncio_long_exec_warning(): + def flt(log_record): + msg = log_record.getMessage() + return not msg.startswith('Executing ') + + logger = logging.getLogger('asyncio') + logger.addFilter(flt) + try: + yield + finally: + logger.removeFilter(flt) + + +def with_timeout(timeout): + def wrap(func): + func.__timeout__ = timeout + return func + + return wrap + + +class TestCaseMeta(type(unittest.TestCase)): + TEST_TIMEOUT = None + + @staticmethod + def _iter_methods(bases, ns): + for base in bases: + for methname in dir(base): + if not methname.startswith('test_'): + continue + + meth = getattr(base, methname) + if not inspect.iscoroutinefunction(meth): + continue + + yield methname, meth + + for methname, meth in ns.items(): + if not methname.startswith('test_'): + continue + + if not inspect.iscoroutinefunction(meth): + continue + + yield methname, meth + + def __new__(mcls, name, bases, ns): + for methname, meth in mcls._iter_methods(bases, ns): + @functools.wraps(meth) + def wrapper(self, *args, __meth__=meth, **kwargs): + coro = __meth__(self, *args, **kwargs) + timeout = getattr(__meth__, '__timeout__', mcls.TEST_TIMEOUT) + if timeout: + coro = asyncio.wait_for(coro, timeout) + try: + self.loop.run_until_complete(coro) + except asyncio.TimeoutError: + raise self.failureException( + 'test timed out after {} seconds'.format( + timeout)) from None + else: + self.loop.run_until_complete(coro) + ns[methname] = wrapper + + return super().__new__(mcls, name, bases, ns) + + +class TestCase(unittest.TestCase, metaclass=TestCaseMeta): + + @classmethod + def setUpClass(cls): + if os.environ.get('USE_UVLOOP'): + import uvloop + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + + loop = asyncio.new_event_loop() + asyncio.set_event_loop(None) + cls.loop = loop + + @classmethod + def tearDownClass(cls): + cls.loop.close() + asyncio.set_event_loop(None) + + def setUp(self): + self.loop.set_exception_handler(self.loop_exception_handler) + self.__unhandled_exceptions = [] + + def tearDown(self): + if self.__unhandled_exceptions: + formatted = [] + + for i, context in enumerate(self.__unhandled_exceptions): + formatted.append(self._format_loop_exception(context, i + 1)) + + self.fail( + 'unexpected exceptions in asynchronous code:\n' + + '\n'.join(formatted)) + + @contextlib.contextmanager + def assertRunUnder(self, delta): + st = time.monotonic() + try: + yield + finally: + elapsed = time.monotonic() - st + if elapsed > delta: + raise AssertionError( + 'running block took {:0.3f}s which is longer ' + 'than the expected maximum of {:0.3f}s'.format( + elapsed, delta)) + + @contextlib.contextmanager + def assertLoopErrorHandlerCalled(self, msg_re: str): + contexts = [] + + def handler(loop, ctx): + contexts.append(ctx) + + old_handler = self.loop.get_exception_handler() + self.loop.set_exception_handler(handler) + try: + yield + + for ctx in contexts: + msg = ctx.get('message') + if msg and re.search(msg_re, msg): + return + + raise AssertionError( + 'no message matching {!r} was logged with ' + 'loop.call_exception_handler()'.format(msg_re)) + + finally: + self.loop.set_exception_handler(old_handler) + + def loop_exception_handler(self, loop, context): + self.__unhandled_exceptions.append(context) + loop.default_exception_handler(context) + + def _format_loop_exception(self, context, n): + message = context.get('message', 'Unhandled exception in event loop') + exception = context.get('exception') + if exception is not None: + exc_info = (type(exception), exception, exception.__traceback__) + else: + exc_info = None + + lines = [] + for key in sorted(context): + if key in {'message', 'exception'}: + continue + value = context[key] + if key == 'source_traceback': + tb = ''.join(traceback.format_list(value)) + value = 'Object created at (most recent call last):\n' + value += tb.rstrip() + else: + try: + value = repr(value) + except Exception as ex: + value = ('Exception in __repr__ {!r}; ' + 'value type: {!r}'.format(ex, type(value))) + lines.append('[{}]: {}\n\n'.format(key, value)) + + if exc_info is not None: + lines.append('[exception]:\n') + formatted_exc = textwrap.indent( + ''.join(traceback.format_exception(*exc_info)), ' ') + lines.append(formatted_exc) + + details = textwrap.indent(''.join(lines), ' ') + return '{:02d}. {}:\n{}\n'.format(n, message, details) + + +_default_cluster = None + + +def _init_cluster(ClusterCls, cluster_kwargs, initdb_options=None): + cluster = ClusterCls(**cluster_kwargs) + cluster.init(**(initdb_options or {})) + cluster.trust_local_connections() + atexit.register(_shutdown_cluster, cluster) + return cluster + + +def _start_cluster(ClusterCls, cluster_kwargs, server_settings, + initdb_options=None): + cluster = _init_cluster(ClusterCls, cluster_kwargs, initdb_options) + cluster.start(port='dynamic', server_settings=server_settings) + return cluster + + +def _get_initdb_options(initdb_options=None): + if not initdb_options: + initdb_options = {} + else: + initdb_options = dict(initdb_options) + + # Make the default superuser name stable. + if 'username' not in initdb_options: + initdb_options['username'] = 'postgres' + + return initdb_options + + +def _init_default_cluster(initdb_options=None): + global _default_cluster + + if _default_cluster is None: + pg_host = os.environ.get('PGHOST') + if pg_host: + # Using existing cluster, assuming it is initialized and running + _default_cluster = pg_cluster.RunningCluster() + else: + _default_cluster = _init_cluster( + pg_cluster.TempCluster, cluster_kwargs={}, + initdb_options=_get_initdb_options(initdb_options)) + + return _default_cluster + + +def _shutdown_cluster(cluster): + if cluster.get_status() == 'running': + cluster.stop() + if cluster.get_status() != 'not-initialized': + cluster.destroy() + + +def create_pool(dsn=None, *, + min_size=10, + max_size=10, + max_queries=50000, + max_inactive_connection_lifetime=60.0, + setup=None, + init=None, + loop=None, + pool_class=pg_pool.Pool, + connection_class=pg_connection.Connection, + record_class=asyncpg.Record, + **connect_kwargs): + return pool_class( + dsn, + min_size=min_size, max_size=max_size, + max_queries=max_queries, loop=loop, setup=setup, init=init, + max_inactive_connection_lifetime=max_inactive_connection_lifetime, + connection_class=connection_class, + record_class=record_class, + **connect_kwargs) + + +class ClusterTestCase(TestCase): + @classmethod + def get_server_settings(cls): + settings = { + 'log_connections': 'on' + } + + if cls.cluster.get_pg_version() >= (11, 0): + # JITting messes up timing tests, and + # is not essential for testing. + settings['jit'] = 'off' + + return settings + + @classmethod + def new_cluster(cls, ClusterCls, *, cluster_kwargs={}, initdb_options={}): + cluster = _init_cluster(ClusterCls, cluster_kwargs, + _get_initdb_options(initdb_options)) + cls._clusters.append(cluster) + return cluster + + @classmethod + def start_cluster(cls, cluster, *, server_settings={}): + cluster.start(port='dynamic', server_settings=server_settings) + + @classmethod + def setup_cluster(cls): + cls.cluster = _init_default_cluster() + + if cls.cluster.get_status() != 'running': + cls.cluster.start( + port='dynamic', server_settings=cls.get_server_settings()) + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls._clusters = [] + cls.setup_cluster() + + @classmethod + def tearDownClass(cls): + super().tearDownClass() + for cluster in cls._clusters: + if cluster is not _default_cluster: + cluster.stop() + cluster.destroy() + cls._clusters = [] + + @classmethod + def get_connection_spec(cls, kwargs={}): + conn_spec = cls.cluster.get_connection_spec() + if kwargs.get('dsn'): + conn_spec.pop('host') + conn_spec.update(kwargs) + if not os.environ.get('PGHOST') and not kwargs.get('dsn'): + if 'database' not in conn_spec: + conn_spec['database'] = 'postgres' + if 'user' not in conn_spec: + conn_spec['user'] = 'postgres' + return conn_spec + + @classmethod + def connect(cls, **kwargs): + conn_spec = cls.get_connection_spec(kwargs) + return pg_connection.connect(**conn_spec, loop=cls.loop) + + def setUp(self): + super().setUp() + self._pools = [] + + def tearDown(self): + super().tearDown() + for pool in self._pools: + pool.terminate() + self._pools = [] + + def create_pool(self, pool_class=pg_pool.Pool, + connection_class=pg_connection.Connection, **kwargs): + conn_spec = self.get_connection_spec(kwargs) + pool = create_pool(loop=self.loop, pool_class=pool_class, + connection_class=connection_class, **conn_spec) + self._pools.append(pool) + return pool + + +class ProxiedClusterTestCase(ClusterTestCase): + @classmethod + def get_server_settings(cls): + settings = dict(super().get_server_settings()) + settings['listen_addresses'] = '127.0.0.1' + return settings + + @classmethod + def get_proxy_settings(cls): + return {'fuzzing-mode': None} + + @classmethod + def setUpClass(cls): + super().setUpClass() + conn_spec = cls.cluster.get_connection_spec() + host = conn_spec.get('host') + if not host: + host = '127.0.0.1' + elif host.startswith('/'): + host = '127.0.0.1' + cls.proxy = fuzzer.TCPFuzzingProxy( + backend_host=host, + backend_port=conn_spec['port'], + ) + cls.proxy.start() + + @classmethod + def tearDownClass(cls): + cls.proxy.stop() + super().tearDownClass() + + @classmethod + def get_connection_spec(cls, kwargs): + conn_spec = super().get_connection_spec(kwargs) + conn_spec['host'] = cls.proxy.listening_addr + conn_spec['port'] = cls.proxy.listening_port + return conn_spec + + def tearDown(self): + self.proxy.reset() + super().tearDown() + + +def with_connection_options(**options): + if not options: + raise ValueError('no connection options were specified') + + def wrap(func): + func.__connect_options__ = options + return func + + return wrap + + +class ConnectedTestCase(ClusterTestCase): + + def setUp(self): + super().setUp() + + # Extract options set up with `with_connection_options`. + test_func = getattr(self, self._testMethodName).__func__ + opts = getattr(test_func, '__connect_options__', {}) + self.con = self.loop.run_until_complete(self.connect(**opts)) + self.server_version = self.con.get_server_version() + + def tearDown(self): + try: + self.loop.run_until_complete(self.con.close()) + self.con = None + finally: + super().tearDown() + + +class HotStandbyTestCase(ClusterTestCase): + + @classmethod + def setup_cluster(cls): + cls.master_cluster = cls.new_cluster(pg_cluster.TempCluster) + cls.start_cluster( + cls.master_cluster, + server_settings={ + 'max_wal_senders': 10, + 'wal_level': 'hot_standby' + } + ) + + con = None + + try: + con = cls.loop.run_until_complete( + cls.master_cluster.connect( + database='postgres', user='postgres', loop=cls.loop)) + + cls.loop.run_until_complete( + con.execute(''' + CREATE ROLE replication WITH LOGIN REPLICATION + ''')) + + cls.master_cluster.trust_local_replication_by('replication') + + conn_spec = cls.master_cluster.get_connection_spec() + + cls.standby_cluster = cls.new_cluster( + pg_cluster.HotStandbyCluster, + cluster_kwargs={ + 'master': conn_spec, + 'replication_user': 'replication' + } + ) + cls.start_cluster( + cls.standby_cluster, + server_settings={ + 'hot_standby': True + } + ) + + finally: + if con is not None: + cls.loop.run_until_complete(con.close()) + + @classmethod + def get_cluster_connection_spec(cls, cluster, kwargs={}): + conn_spec = cluster.get_connection_spec() + if kwargs.get('dsn'): + conn_spec.pop('host') + conn_spec.update(kwargs) + if not os.environ.get('PGHOST') and not kwargs.get('dsn'): + if 'database' not in conn_spec: + conn_spec['database'] = 'postgres' + if 'user' not in conn_spec: + conn_spec['user'] = 'postgres' + return conn_spec + + @classmethod + def get_connection_spec(cls, kwargs={}): + primary_spec = cls.get_cluster_connection_spec( + cls.master_cluster, kwargs + ) + standby_spec = cls.get_cluster_connection_spec( + cls.standby_cluster, kwargs + ) + return { + 'host': [primary_spec['host'], standby_spec['host']], + 'port': [primary_spec['port'], standby_spec['port']], + 'database': primary_spec['database'], + 'user': primary_spec['user'], + **kwargs + } + + @classmethod + def connect_primary(cls, **kwargs): + conn_spec = cls.get_cluster_connection_spec(cls.master_cluster, kwargs) + return pg_connection.connect(**conn_spec, loop=cls.loop) + + @classmethod + def connect_standby(cls, **kwargs): + conn_spec = cls.get_cluster_connection_spec( + cls.standby_cluster, + kwargs + ) + return pg_connection.connect(**conn_spec, loop=cls.loop) diff --git a/env/Lib/site-packages/asyncpg/_testbase/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/asyncpg/_testbase/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..b2eeecb Binary files /dev/null and b/env/Lib/site-packages/asyncpg/_testbase/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/_testbase/__pycache__/fuzzer.cpython-311.pyc b/env/Lib/site-packages/asyncpg/_testbase/__pycache__/fuzzer.cpython-311.pyc new file mode 100644 index 0000000..4a56746 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/_testbase/__pycache__/fuzzer.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/_testbase/fuzzer.py b/env/Lib/site-packages/asyncpg/_testbase/fuzzer.py new file mode 100644 index 0000000..8874564 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/_testbase/fuzzer.py @@ -0,0 +1,306 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import asyncio +import socket +import threading +import typing + +from asyncpg import cluster + + +class StopServer(Exception): + pass + + +class TCPFuzzingProxy: + def __init__(self, *, listening_addr: str='127.0.0.1', + listening_port: typing.Optional[int]=None, + backend_host: str, backend_port: int, + settings: typing.Optional[dict]=None) -> None: + self.listening_addr = listening_addr + self.listening_port = listening_port + self.backend_host = backend_host + self.backend_port = backend_port + self.settings = settings or {} + self.loop = None + self.connectivity = None + self.connectivity_loss = None + self.stop_event = None + self.connections = {} + self.sock = None + self.listen_task = None + + async def _wait(self, work): + work_task = asyncio.ensure_future(work) + stop_event_task = asyncio.ensure_future(self.stop_event.wait()) + + try: + await asyncio.wait( + [work_task, stop_event_task], + return_when=asyncio.FIRST_COMPLETED) + + if self.stop_event.is_set(): + raise StopServer() + else: + return work_task.result() + finally: + if not work_task.done(): + work_task.cancel() + if not stop_event_task.done(): + stop_event_task.cancel() + + def start(self): + started = threading.Event() + self.thread = threading.Thread( + target=self._start_thread, args=(started,)) + self.thread.start() + if not started.wait(timeout=2): + raise RuntimeError('fuzzer proxy failed to start') + + def stop(self): + self.loop.call_soon_threadsafe(self._stop) + self.thread.join() + + def _stop(self): + self.stop_event.set() + + def _start_thread(self, started_event): + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(self.loop) + + self.connectivity = asyncio.Event() + self.connectivity.set() + self.connectivity_loss = asyncio.Event() + self.stop_event = asyncio.Event() + + if self.listening_port is None: + self.listening_port = cluster.find_available_port() + + self.sock = socket.socket() + self.sock.bind((self.listening_addr, self.listening_port)) + self.sock.listen(50) + self.sock.setblocking(False) + + try: + self.loop.run_until_complete(self._main(started_event)) + finally: + self.loop.close() + + async def _main(self, started_event): + self.listen_task = asyncio.ensure_future(self.listen()) + # Notify the main thread that we are ready to go. + started_event.set() + try: + await self.listen_task + finally: + for c in list(self.connections): + c.close() + await asyncio.sleep(0.01) + if hasattr(self.loop, 'remove_reader'): + self.loop.remove_reader(self.sock.fileno()) + self.sock.close() + + async def listen(self): + while True: + try: + client_sock, _ = await self._wait( + self.loop.sock_accept(self.sock)) + + backend_sock = socket.socket() + backend_sock.setblocking(False) + + await self._wait(self.loop.sock_connect( + backend_sock, (self.backend_host, self.backend_port))) + except StopServer: + break + + conn = Connection(client_sock, backend_sock, self) + conn_task = self.loop.create_task(conn.handle()) + self.connections[conn] = conn_task + + def trigger_connectivity_loss(self): + self.loop.call_soon_threadsafe(self._trigger_connectivity_loss) + + def _trigger_connectivity_loss(self): + self.connectivity.clear() + self.connectivity_loss.set() + + def restore_connectivity(self): + self.loop.call_soon_threadsafe(self._restore_connectivity) + + def _restore_connectivity(self): + self.connectivity.set() + self.connectivity_loss.clear() + + def reset(self): + self.restore_connectivity() + + def _close_connection(self, connection): + conn_task = self.connections.pop(connection, None) + if conn_task is not None: + conn_task.cancel() + + def close_all_connections(self): + for conn in list(self.connections): + self.loop.call_soon_threadsafe(self._close_connection, conn) + + +class Connection: + def __init__(self, client_sock, backend_sock, proxy): + self.client_sock = client_sock + self.backend_sock = backend_sock + self.proxy = proxy + self.loop = proxy.loop + self.connectivity = proxy.connectivity + self.connectivity_loss = proxy.connectivity_loss + self.proxy_to_backend_task = None + self.proxy_from_backend_task = None + self.is_closed = False + + def close(self): + if self.is_closed: + return + + self.is_closed = True + + if self.proxy_to_backend_task is not None: + self.proxy_to_backend_task.cancel() + self.proxy_to_backend_task = None + + if self.proxy_from_backend_task is not None: + self.proxy_from_backend_task.cancel() + self.proxy_from_backend_task = None + + self.proxy._close_connection(self) + + async def handle(self): + self.proxy_to_backend_task = asyncio.ensure_future( + self.proxy_to_backend()) + + self.proxy_from_backend_task = asyncio.ensure_future( + self.proxy_from_backend()) + + try: + await asyncio.wait( + [self.proxy_to_backend_task, self.proxy_from_backend_task], + return_when=asyncio.FIRST_COMPLETED) + + finally: + if self.proxy_to_backend_task is not None: + self.proxy_to_backend_task.cancel() + + if self.proxy_from_backend_task is not None: + self.proxy_from_backend_task.cancel() + + # Asyncio fails to properly remove the readers and writers + # when the task doing recv() or send() is cancelled, so + # we must remove the readers and writers manually before + # closing the sockets. + self.loop.remove_reader(self.client_sock.fileno()) + self.loop.remove_writer(self.client_sock.fileno()) + self.loop.remove_reader(self.backend_sock.fileno()) + self.loop.remove_writer(self.backend_sock.fileno()) + + self.client_sock.close() + self.backend_sock.close() + + async def _read(self, sock, n): + read_task = asyncio.ensure_future( + self.loop.sock_recv(sock, n)) + conn_event_task = asyncio.ensure_future( + self.connectivity_loss.wait()) + + try: + await asyncio.wait( + [read_task, conn_event_task], + return_when=asyncio.FIRST_COMPLETED) + + if self.connectivity_loss.is_set(): + return None + else: + return read_task.result() + finally: + if not self.loop.is_closed(): + if not read_task.done(): + read_task.cancel() + if not conn_event_task.done(): + conn_event_task.cancel() + + async def _write(self, sock, data): + write_task = asyncio.ensure_future( + self.loop.sock_sendall(sock, data)) + conn_event_task = asyncio.ensure_future( + self.connectivity_loss.wait()) + + try: + await asyncio.wait( + [write_task, conn_event_task], + return_when=asyncio.FIRST_COMPLETED) + + if self.connectivity_loss.is_set(): + return None + else: + return write_task.result() + finally: + if not self.loop.is_closed(): + if not write_task.done(): + write_task.cancel() + if not conn_event_task.done(): + conn_event_task.cancel() + + async def proxy_to_backend(self): + buf = None + + try: + while True: + await self.connectivity.wait() + if buf is not None: + data = buf + buf = None + else: + data = await self._read(self.client_sock, 4096) + if data == b'': + break + if self.connectivity_loss.is_set(): + if data: + buf = data + continue + await self._write(self.backend_sock, data) + + except ConnectionError: + pass + + finally: + if not self.loop.is_closed(): + self.loop.call_soon(self.close) + + async def proxy_from_backend(self): + buf = None + + try: + while True: + await self.connectivity.wait() + if buf is not None: + data = buf + buf = None + else: + data = await self._read(self.backend_sock, 4096) + if data == b'': + break + if self.connectivity_loss.is_set(): + if data: + buf = data + continue + await self._write(self.client_sock, data) + + except ConnectionError: + pass + + finally: + if not self.loop.is_closed(): + self.loop.call_soon(self.close) diff --git a/env/Lib/site-packages/asyncpg/_version.py b/env/Lib/site-packages/asyncpg/_version.py new file mode 100644 index 0000000..64da11d --- /dev/null +++ b/env/Lib/site-packages/asyncpg/_version.py @@ -0,0 +1,13 @@ +# This file MUST NOT contain anything but the __version__ assignment. +# +# When making a release, change the value of __version__ +# to an appropriate value, and open a pull request against +# the correct branch (master if making a new feature release). +# The commit message MUST contain a properly formatted release +# log, and the commit must be signed. +# +# The release automation will: build and test the packages for the +# supported platforms, publish the packages on PyPI, merge the PR +# to the target branch, create a Git tag pointing to the commit. + +__version__ = '0.29.0' diff --git a/env/Lib/site-packages/asyncpg/cluster.py b/env/Lib/site-packages/asyncpg/cluster.py new file mode 100644 index 0000000..4467cc2 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/cluster.py @@ -0,0 +1,688 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import asyncio +import os +import os.path +import platform +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import textwrap +import time + +import asyncpg +from asyncpg import serverversion + + +_system = platform.uname().system + +if _system == 'Windows': + def platform_exe(name): + if name.endswith('.exe'): + return name + return name + '.exe' +else: + def platform_exe(name): + return name + + +def find_available_port(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + sock.bind(('127.0.0.1', 0)) + return sock.getsockname()[1] + except Exception: + return None + finally: + sock.close() + + +class ClusterError(Exception): + pass + + +class Cluster: + def __init__(self, data_dir, *, pg_config_path=None): + self._data_dir = data_dir + self._pg_config_path = pg_config_path + self._pg_bin_dir = ( + os.environ.get('PGINSTALLATION') + or os.environ.get('PGBIN') + ) + self._pg_ctl = None + self._daemon_pid = None + self._daemon_process = None + self._connection_addr = None + self._connection_spec_override = None + + def get_pg_version(self): + return self._pg_version + + def is_managed(self): + return True + + def get_data_dir(self): + return self._data_dir + + def get_status(self): + if self._pg_ctl is None: + self._init_env() + + process = subprocess.run( + [self._pg_ctl, 'status', '-D', self._data_dir], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.stdout, process.stderr + + if (process.returncode == 4 or not os.path.exists(self._data_dir) or + not os.listdir(self._data_dir)): + return 'not-initialized' + elif process.returncode == 3: + return 'stopped' + elif process.returncode == 0: + r = re.match(r'.*PID\s?:\s+(\d+).*', stdout.decode()) + if not r: + raise ClusterError( + 'could not parse pg_ctl status output: {}'.format( + stdout.decode())) + self._daemon_pid = int(r.group(1)) + return self._test_connection(timeout=0) + else: + raise ClusterError( + 'pg_ctl status exited with status {:d}: {}'.format( + process.returncode, stderr)) + + async def connect(self, loop=None, **kwargs): + conn_info = self.get_connection_spec() + conn_info.update(kwargs) + return await asyncpg.connect(loop=loop, **conn_info) + + def init(self, **settings): + """Initialize cluster.""" + if self.get_status() != 'not-initialized': + raise ClusterError( + 'cluster in {!r} has already been initialized'.format( + self._data_dir)) + + settings = dict(settings) + if 'encoding' not in settings: + settings['encoding'] = 'UTF-8' + + if settings: + settings_args = ['--{}={}'.format(k, v) + for k, v in settings.items()] + extra_args = ['-o'] + [' '.join(settings_args)] + else: + extra_args = [] + + process = subprocess.run( + [self._pg_ctl, 'init', '-D', self._data_dir] + extra_args, + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + + output = process.stdout + + if process.returncode != 0: + raise ClusterError( + 'pg_ctl init exited with status {:d}:\n{}'.format( + process.returncode, output.decode())) + + return output.decode() + + def start(self, wait=60, *, server_settings={}, **opts): + """Start the cluster.""" + status = self.get_status() + if status == 'running': + return + elif status == 'not-initialized': + raise ClusterError( + 'cluster in {!r} has not been initialized'.format( + self._data_dir)) + + port = opts.pop('port', None) + if port == 'dynamic': + port = find_available_port() + + extra_args = ['--{}={}'.format(k, v) for k, v in opts.items()] + extra_args.append('--port={}'.format(port)) + + sockdir = server_settings.get('unix_socket_directories') + if sockdir is None: + sockdir = server_settings.get('unix_socket_directory') + if sockdir is None and _system != 'Windows': + sockdir = tempfile.gettempdir() + + ssl_key = server_settings.get('ssl_key_file') + if ssl_key: + # Make sure server certificate key file has correct permissions. + keyfile = os.path.join(self._data_dir, 'srvkey.pem') + shutil.copy(ssl_key, keyfile) + os.chmod(keyfile, 0o600) + server_settings = server_settings.copy() + server_settings['ssl_key_file'] = keyfile + + if sockdir is not None: + if self._pg_version < (9, 3): + sockdir_opt = 'unix_socket_directory' + else: + sockdir_opt = 'unix_socket_directories' + + server_settings[sockdir_opt] = sockdir + + for k, v in server_settings.items(): + extra_args.extend(['-c', '{}={}'.format(k, v)]) + + if _system == 'Windows': + # On Windows we have to use pg_ctl as direct execution + # of postgres daemon under an Administrative account + # is not permitted and there is no easy way to drop + # privileges. + if os.getenv('ASYNCPG_DEBUG_SERVER'): + stdout = sys.stdout + print( + 'asyncpg.cluster: Running', + ' '.join([ + self._pg_ctl, 'start', '-D', self._data_dir, + '-o', ' '.join(extra_args) + ]), + file=sys.stderr, + ) + else: + stdout = subprocess.DEVNULL + + process = subprocess.run( + [self._pg_ctl, 'start', '-D', self._data_dir, + '-o', ' '.join(extra_args)], + stdout=stdout, stderr=subprocess.STDOUT) + + if process.returncode != 0: + if process.stderr: + stderr = ':\n{}'.format(process.stderr.decode()) + else: + stderr = '' + raise ClusterError( + 'pg_ctl start exited with status {:d}{}'.format( + process.returncode, stderr)) + else: + if os.getenv('ASYNCPG_DEBUG_SERVER'): + stdout = sys.stdout + else: + stdout = subprocess.DEVNULL + + self._daemon_process = \ + subprocess.Popen( + [self._postgres, '-D', self._data_dir, *extra_args], + stdout=stdout, stderr=subprocess.STDOUT) + + self._daemon_pid = self._daemon_process.pid + + self._test_connection(timeout=wait) + + def reload(self): + """Reload server configuration.""" + status = self.get_status() + if status != 'running': + raise ClusterError('cannot reload: cluster is not running') + + process = subprocess.run( + [self._pg_ctl, 'reload', '-D', self._data_dir], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + stderr = process.stderr + + if process.returncode != 0: + raise ClusterError( + 'pg_ctl stop exited with status {:d}: {}'.format( + process.returncode, stderr.decode())) + + def stop(self, wait=60): + process = subprocess.run( + [self._pg_ctl, 'stop', '-D', self._data_dir, '-t', str(wait), + '-m', 'fast'], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + stderr = process.stderr + + if process.returncode != 0: + raise ClusterError( + 'pg_ctl stop exited with status {:d}: {}'.format( + process.returncode, stderr.decode())) + + if (self._daemon_process is not None and + self._daemon_process.returncode is None): + self._daemon_process.kill() + + def destroy(self): + status = self.get_status() + if status == 'stopped' or status == 'not-initialized': + shutil.rmtree(self._data_dir) + else: + raise ClusterError('cannot destroy {} cluster'.format(status)) + + def _get_connection_spec(self): + if self._connection_addr is None: + self._connection_addr = self._connection_addr_from_pidfile() + + if self._connection_addr is not None: + if self._connection_spec_override: + args = self._connection_addr.copy() + args.update(self._connection_spec_override) + return args + else: + return self._connection_addr + + def get_connection_spec(self): + status = self.get_status() + if status != 'running': + raise ClusterError('cluster is not running') + + return self._get_connection_spec() + + def override_connection_spec(self, **kwargs): + self._connection_spec_override = kwargs + + def reset_wal(self, *, oid=None, xid=None): + status = self.get_status() + if status == 'not-initialized': + raise ClusterError( + 'cannot modify WAL status: cluster is not initialized') + + if status == 'running': + raise ClusterError( + 'cannot modify WAL status: cluster is running') + + opts = [] + if oid is not None: + opts.extend(['-o', str(oid)]) + if xid is not None: + opts.extend(['-x', str(xid)]) + if not opts: + return + + opts.append(self._data_dir) + + try: + reset_wal = self._find_pg_binary('pg_resetwal') + except ClusterError: + reset_wal = self._find_pg_binary('pg_resetxlog') + + process = subprocess.run( + [reset_wal] + opts, + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + stderr = process.stderr + + if process.returncode != 0: + raise ClusterError( + 'pg_resetwal exited with status {:d}: {}'.format( + process.returncode, stderr.decode())) + + def reset_hba(self): + """Remove all records from pg_hba.conf.""" + status = self.get_status() + if status == 'not-initialized': + raise ClusterError( + 'cannot modify HBA records: cluster is not initialized') + + pg_hba = os.path.join(self._data_dir, 'pg_hba.conf') + + try: + with open(pg_hba, 'w'): + pass + except IOError as e: + raise ClusterError( + 'cannot modify HBA records: {}'.format(e)) from e + + def add_hba_entry(self, *, type='host', database, user, address=None, + auth_method, auth_options=None): + """Add a record to pg_hba.conf.""" + status = self.get_status() + if status == 'not-initialized': + raise ClusterError( + 'cannot modify HBA records: cluster is not initialized') + + if type not in {'local', 'host', 'hostssl', 'hostnossl'}: + raise ValueError('invalid HBA record type: {!r}'.format(type)) + + pg_hba = os.path.join(self._data_dir, 'pg_hba.conf') + + record = '{} {} {}'.format(type, database, user) + + if type != 'local': + if address is None: + raise ValueError( + '{!r} entry requires a valid address'.format(type)) + else: + record += ' {}'.format(address) + + record += ' {}'.format(auth_method) + + if auth_options is not None: + record += ' ' + ' '.join( + '{}={}'.format(k, v) for k, v in auth_options) + + try: + with open(pg_hba, 'a') as f: + print(record, file=f) + except IOError as e: + raise ClusterError( + 'cannot modify HBA records: {}'.format(e)) from e + + def trust_local_connections(self): + self.reset_hba() + + if _system != 'Windows': + self.add_hba_entry(type='local', database='all', + user='all', auth_method='trust') + self.add_hba_entry(type='host', address='127.0.0.1/32', + database='all', user='all', + auth_method='trust') + self.add_hba_entry(type='host', address='::1/128', + database='all', user='all', + auth_method='trust') + status = self.get_status() + if status == 'running': + self.reload() + + def trust_local_replication_by(self, user): + if _system != 'Windows': + self.add_hba_entry(type='local', database='replication', + user=user, auth_method='trust') + self.add_hba_entry(type='host', address='127.0.0.1/32', + database='replication', user=user, + auth_method='trust') + self.add_hba_entry(type='host', address='::1/128', + database='replication', user=user, + auth_method='trust') + status = self.get_status() + if status == 'running': + self.reload() + + def _init_env(self): + if not self._pg_bin_dir: + pg_config = self._find_pg_config(self._pg_config_path) + pg_config_data = self._run_pg_config(pg_config) + + self._pg_bin_dir = pg_config_data.get('bindir') + if not self._pg_bin_dir: + raise ClusterError( + 'pg_config output did not provide the BINDIR value') + + self._pg_ctl = self._find_pg_binary('pg_ctl') + self._postgres = self._find_pg_binary('postgres') + self._pg_version = self._get_pg_version() + + def _connection_addr_from_pidfile(self): + pidfile = os.path.join(self._data_dir, 'postmaster.pid') + + try: + with open(pidfile, 'rt') as f: + piddata = f.read() + except FileNotFoundError: + return None + + lines = piddata.splitlines() + + if len(lines) < 6: + # A complete postgres pidfile is at least 6 lines + return None + + pmpid = int(lines[0]) + if self._daemon_pid and pmpid != self._daemon_pid: + # This might be an old pidfile left from previous postgres + # daemon run. + return None + + portnum = lines[3] + sockdir = lines[4] + hostaddr = lines[5] + + if sockdir: + if sockdir[0] != '/': + # Relative sockdir + sockdir = os.path.normpath( + os.path.join(self._data_dir, sockdir)) + host_str = sockdir + else: + host_str = hostaddr + + if host_str == '*': + host_str = 'localhost' + elif host_str == '0.0.0.0': + host_str = '127.0.0.1' + elif host_str == '::': + host_str = '::1' + + return { + 'host': host_str, + 'port': portnum + } + + def _test_connection(self, timeout=60): + self._connection_addr = None + + loop = asyncio.new_event_loop() + + try: + for i in range(timeout): + if self._connection_addr is None: + conn_spec = self._get_connection_spec() + if conn_spec is None: + time.sleep(1) + continue + + try: + con = loop.run_until_complete( + asyncpg.connect(database='postgres', + user='postgres', + timeout=5, loop=loop, + **self._connection_addr)) + except (OSError, asyncio.TimeoutError, + asyncpg.CannotConnectNowError, + asyncpg.PostgresConnectionError): + time.sleep(1) + continue + except asyncpg.PostgresError: + # Any other error other than ServerNotReadyError or + # ConnectionError is interpreted to indicate the server is + # up. + break + else: + loop.run_until_complete(con.close()) + break + finally: + loop.close() + + return 'running' + + def _run_pg_config(self, pg_config_path): + process = subprocess.run( + pg_config_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.stdout, process.stderr + + if process.returncode != 0: + raise ClusterError('pg_config exited with status {:d}: {}'.format( + process.returncode, stderr)) + else: + config = {} + + for line in stdout.splitlines(): + k, eq, v = line.decode('utf-8').partition('=') + if eq: + config[k.strip().lower()] = v.strip() + + return config + + def _find_pg_config(self, pg_config_path): + if pg_config_path is None: + pg_install = ( + os.environ.get('PGINSTALLATION') + or os.environ.get('PGBIN') + ) + if pg_install: + pg_config_path = platform_exe( + os.path.join(pg_install, 'pg_config')) + else: + pathenv = os.environ.get('PATH').split(os.pathsep) + for path in pathenv: + pg_config_path = platform_exe( + os.path.join(path, 'pg_config')) + if os.path.exists(pg_config_path): + break + else: + pg_config_path = None + + if not pg_config_path: + raise ClusterError('could not find pg_config executable') + + if not os.path.isfile(pg_config_path): + raise ClusterError('{!r} is not an executable'.format( + pg_config_path)) + + return pg_config_path + + def _find_pg_binary(self, binary): + bpath = platform_exe(os.path.join(self._pg_bin_dir, binary)) + + if not os.path.isfile(bpath): + raise ClusterError( + 'could not find {} executable: '.format(binary) + + '{!r} does not exist or is not a file'.format(bpath)) + + return bpath + + def _get_pg_version(self): + process = subprocess.run( + [self._postgres, '--version'], + stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = process.stdout, process.stderr + + if process.returncode != 0: + raise ClusterError( + 'postgres --version exited with status {:d}: {}'.format( + process.returncode, stderr)) + + version_string = stdout.decode('utf-8').strip(' \n') + prefix = 'postgres (PostgreSQL) ' + if not version_string.startswith(prefix): + raise ClusterError( + 'could not determine server version from {!r}'.format( + version_string)) + version_string = version_string[len(prefix):] + + return serverversion.split_server_version_string(version_string) + + +class TempCluster(Cluster): + def __init__(self, *, + data_dir_suffix=None, data_dir_prefix=None, + data_dir_parent=None, pg_config_path=None): + self._data_dir = tempfile.mkdtemp(suffix=data_dir_suffix, + prefix=data_dir_prefix, + dir=data_dir_parent) + super().__init__(self._data_dir, pg_config_path=pg_config_path) + + +class HotStandbyCluster(TempCluster): + def __init__(self, *, + master, replication_user, + data_dir_suffix=None, data_dir_prefix=None, + data_dir_parent=None, pg_config_path=None): + self._master = master + self._repl_user = replication_user + super().__init__( + data_dir_suffix=data_dir_suffix, + data_dir_prefix=data_dir_prefix, + data_dir_parent=data_dir_parent, + pg_config_path=pg_config_path) + + def _init_env(self): + super()._init_env() + self._pg_basebackup = self._find_pg_binary('pg_basebackup') + + def init(self, **settings): + """Initialize cluster.""" + if self.get_status() != 'not-initialized': + raise ClusterError( + 'cluster in {!r} has already been initialized'.format( + self._data_dir)) + + process = subprocess.run( + [self._pg_basebackup, '-h', self._master['host'], + '-p', self._master['port'], '-D', self._data_dir, + '-U', self._repl_user], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + + output = process.stdout + + if process.returncode != 0: + raise ClusterError( + 'pg_basebackup init exited with status {:d}:\n{}'.format( + process.returncode, output.decode())) + + if self._pg_version < (12, 0): + with open(os.path.join(self._data_dir, 'recovery.conf'), 'w') as f: + f.write(textwrap.dedent("""\ + standby_mode = 'on' + primary_conninfo = 'host={host} port={port} user={user}' + """.format( + host=self._master['host'], + port=self._master['port'], + user=self._repl_user))) + else: + f = open(os.path.join(self._data_dir, 'standby.signal'), 'w') + f.close() + + return output.decode() + + def start(self, wait=60, *, server_settings={}, **opts): + if self._pg_version >= (12, 0): + server_settings = server_settings.copy() + server_settings['primary_conninfo'] = ( + '"host={host} port={port} user={user}"'.format( + host=self._master['host'], + port=self._master['port'], + user=self._repl_user, + ) + ) + + super().start(wait=wait, server_settings=server_settings, **opts) + + +class RunningCluster(Cluster): + def __init__(self, **kwargs): + self.conn_spec = kwargs + + def is_managed(self): + return False + + def get_connection_spec(self): + return dict(self.conn_spec) + + def get_status(self): + return 'running' + + def init(self, **settings): + pass + + def start(self, wait=60, **settings): + pass + + def stop(self, wait=60): + pass + + def destroy(self): + pass + + def reset_hba(self): + raise ClusterError('cannot modify HBA records of unmanaged cluster') + + def add_hba_entry(self, *, type='host', database, user, address=None, + auth_method, auth_options=None): + raise ClusterError('cannot modify HBA records of unmanaged cluster') diff --git a/env/Lib/site-packages/asyncpg/compat.py b/env/Lib/site-packages/asyncpg/compat.py new file mode 100644 index 0000000..3eec9eb --- /dev/null +++ b/env/Lib/site-packages/asyncpg/compat.py @@ -0,0 +1,61 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import pathlib +import platform +import typing +import sys + + +SYSTEM = platform.uname().system + + +if SYSTEM == 'Windows': + import ctypes.wintypes + + CSIDL_APPDATA = 0x001a + + def get_pg_home_directory() -> typing.Optional[pathlib.Path]: + # We cannot simply use expanduser() as that returns the user's + # home directory, whereas Postgres stores its config in + # %AppData% on Windows. + buf = ctypes.create_unicode_buffer(ctypes.wintypes.MAX_PATH) + r = ctypes.windll.shell32.SHGetFolderPathW(0, CSIDL_APPDATA, 0, 0, buf) + if r: + return None + else: + return pathlib.Path(buf.value) / 'postgresql' + +else: + def get_pg_home_directory() -> typing.Optional[pathlib.Path]: + try: + return pathlib.Path.home() + except (RuntimeError, KeyError): + return None + + +async def wait_closed(stream): + # Not all asyncio versions have StreamWriter.wait_closed(). + if hasattr(stream, 'wait_closed'): + try: + await stream.wait_closed() + except ConnectionResetError: + # On Windows wait_closed() sometimes propagates + # ConnectionResetError which is totally unnecessary. + pass + + +if sys.version_info < (3, 12): + from ._asyncio_compat import wait_for as wait_for # noqa: F401 +else: + from asyncio import wait_for as wait_for # noqa: F401 + + +if sys.version_info < (3, 11): + from ._asyncio_compat import timeout_ctx as timeout # noqa: F401 +else: + from asyncio import timeout as timeout # noqa: F401 diff --git a/env/Lib/site-packages/asyncpg/connect_utils.py b/env/Lib/site-packages/asyncpg/connect_utils.py new file mode 100644 index 0000000..414231f --- /dev/null +++ b/env/Lib/site-packages/asyncpg/connect_utils.py @@ -0,0 +1,1081 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import asyncio +import collections +import enum +import functools +import getpass +import os +import pathlib +import platform +import random +import re +import socket +import ssl as ssl_module +import stat +import struct +import sys +import typing +import urllib.parse +import warnings +import inspect + +from . import compat +from . import exceptions +from . import protocol + + +class SSLMode(enum.IntEnum): + disable = 0 + allow = 1 + prefer = 2 + require = 3 + verify_ca = 4 + verify_full = 5 + + @classmethod + def parse(cls, sslmode): + if isinstance(sslmode, cls): + return sslmode + return getattr(cls, sslmode.replace('-', '_')) + + +_ConnectionParameters = collections.namedtuple( + 'ConnectionParameters', + [ + 'user', + 'password', + 'database', + 'ssl', + 'sslmode', + 'direct_tls', + 'server_settings', + 'target_session_attrs', + ]) + + +_ClientConfiguration = collections.namedtuple( + 'ConnectionConfiguration', + [ + 'command_timeout', + 'statement_cache_size', + 'max_cached_statement_lifetime', + 'max_cacheable_statement_size', + ]) + + +_system = platform.uname().system + + +if _system == 'Windows': + PGPASSFILE = 'pgpass.conf' +else: + PGPASSFILE = '.pgpass' + + +def _read_password_file(passfile: pathlib.Path) \ + -> typing.List[typing.Tuple[str, ...]]: + + passtab = [] + + try: + if not passfile.exists(): + return [] + + if not passfile.is_file(): + warnings.warn( + 'password file {!r} is not a plain file'.format(passfile)) + + return [] + + if _system != 'Windows': + if passfile.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO): + warnings.warn( + 'password file {!r} has group or world access; ' + 'permissions should be u=rw (0600) or less'.format( + passfile)) + + return [] + + with passfile.open('rt') as f: + for line in f: + line = line.strip() + if not line or line.startswith('#'): + # Skip empty lines and comments. + continue + # Backslash escapes both itself and the colon, + # which is a record separator. + line = line.replace(R'\\', '\n') + passtab.append(tuple( + p.replace('\n', R'\\') + for p in re.split(r'(? typing.Optional[pathlib.Path]: + try: + homedir = pathlib.Path.home() + except (RuntimeError, KeyError): + return None + + return (homedir / '.postgresql' / filename).resolve() + + +def _parse_connect_dsn_and_args(*, dsn, host, port, user, + password, passfile, database, ssl, + direct_tls, server_settings, + target_session_attrs): + # `auth_hosts` is the version of host information for the purposes + # of reading the pgpass file. + auth_hosts = None + sslcert = sslkey = sslrootcert = sslcrl = sslpassword = None + ssl_min_protocol_version = ssl_max_protocol_version = None + + if dsn: + parsed = urllib.parse.urlparse(dsn) + + if parsed.scheme not in {'postgresql', 'postgres'}: + raise exceptions.ClientConfigurationError( + 'invalid DSN: scheme is expected to be either ' + '"postgresql" or "postgres", got {!r}'.format(parsed.scheme)) + + if parsed.netloc: + if '@' in parsed.netloc: + dsn_auth, _, dsn_hostspec = parsed.netloc.partition('@') + else: + dsn_hostspec = parsed.netloc + dsn_auth = '' + else: + dsn_auth = dsn_hostspec = '' + + if dsn_auth: + dsn_user, _, dsn_password = dsn_auth.partition(':') + else: + dsn_user = dsn_password = '' + + if not host and dsn_hostspec: + host, port = _parse_hostlist(dsn_hostspec, port, unquote=True) + + if parsed.path and database is None: + dsn_database = parsed.path + if dsn_database.startswith('/'): + dsn_database = dsn_database[1:] + database = urllib.parse.unquote(dsn_database) + + if user is None and dsn_user: + user = urllib.parse.unquote(dsn_user) + + if password is None and dsn_password: + password = urllib.parse.unquote(dsn_password) + + if parsed.query: + query = urllib.parse.parse_qs(parsed.query, strict_parsing=True) + for key, val in query.items(): + if isinstance(val, list): + query[key] = val[-1] + + if 'port' in query: + val = query.pop('port') + if not port and val: + port = [int(p) for p in val.split(',')] + + if 'host' in query: + val = query.pop('host') + if not host and val: + host, port = _parse_hostlist(val, port) + + if 'dbname' in query: + val = query.pop('dbname') + if database is None: + database = val + + if 'database' in query: + val = query.pop('database') + if database is None: + database = val + + if 'user' in query: + val = query.pop('user') + if user is None: + user = val + + if 'password' in query: + val = query.pop('password') + if password is None: + password = val + + if 'passfile' in query: + val = query.pop('passfile') + if passfile is None: + passfile = val + + if 'sslmode' in query: + val = query.pop('sslmode') + if ssl is None: + ssl = val + + if 'sslcert' in query: + sslcert = query.pop('sslcert') + + if 'sslkey' in query: + sslkey = query.pop('sslkey') + + if 'sslrootcert' in query: + sslrootcert = query.pop('sslrootcert') + + if 'sslcrl' in query: + sslcrl = query.pop('sslcrl') + + if 'sslpassword' in query: + sslpassword = query.pop('sslpassword') + + if 'ssl_min_protocol_version' in query: + ssl_min_protocol_version = query.pop( + 'ssl_min_protocol_version' + ) + + if 'ssl_max_protocol_version' in query: + ssl_max_protocol_version = query.pop( + 'ssl_max_protocol_version' + ) + + if 'target_session_attrs' in query: + dsn_target_session_attrs = query.pop( + 'target_session_attrs' + ) + if target_session_attrs is None: + target_session_attrs = dsn_target_session_attrs + + if query: + if server_settings is None: + server_settings = query + else: + server_settings = {**query, **server_settings} + + if not host: + hostspec = os.environ.get('PGHOST') + if hostspec: + host, port = _parse_hostlist(hostspec, port) + + if not host: + auth_hosts = ['localhost'] + + if _system == 'Windows': + host = ['localhost'] + else: + host = ['/run/postgresql', '/var/run/postgresql', + '/tmp', '/private/tmp', 'localhost'] + + if not isinstance(host, (list, tuple)): + host = [host] + + if auth_hosts is None: + auth_hosts = host + + if not port: + portspec = os.environ.get('PGPORT') + if portspec: + if ',' in portspec: + port = [int(p) for p in portspec.split(',')] + else: + port = int(portspec) + else: + port = 5432 + + elif isinstance(port, (list, tuple)): + port = [int(p) for p in port] + + else: + port = int(port) + + port = _validate_port_spec(host, port) + + if user is None: + user = os.getenv('PGUSER') + if not user: + user = getpass.getuser() + + if password is None: + password = os.getenv('PGPASSWORD') + + if database is None: + database = os.getenv('PGDATABASE') + + if database is None: + database = user + + if user is None: + raise exceptions.ClientConfigurationError( + 'could not determine user name to connect with') + + if database is None: + raise exceptions.ClientConfigurationError( + 'could not determine database name to connect to') + + if password is None: + if passfile is None: + passfile = os.getenv('PGPASSFILE') + + if passfile is None: + homedir = compat.get_pg_home_directory() + if homedir: + passfile = homedir / PGPASSFILE + else: + passfile = None + else: + passfile = pathlib.Path(passfile) + + if passfile is not None: + password = _read_password_from_pgpass( + hosts=auth_hosts, ports=port, + database=database, user=user, + passfile=passfile) + + addrs = [] + have_tcp_addrs = False + for h, p in zip(host, port): + if h.startswith('/'): + # UNIX socket name + if '.s.PGSQL.' not in h: + h = os.path.join(h, '.s.PGSQL.{}'.format(p)) + addrs.append(h) + else: + # TCP host/port + addrs.append((h, p)) + have_tcp_addrs = True + + if not addrs: + raise exceptions.InternalClientError( + 'could not determine the database address to connect to') + + if ssl is None: + ssl = os.getenv('PGSSLMODE') + + if ssl is None and have_tcp_addrs: + ssl = 'prefer' + + if isinstance(ssl, (str, SSLMode)): + try: + sslmode = SSLMode.parse(ssl) + except AttributeError: + modes = ', '.join(m.name.replace('_', '-') for m in SSLMode) + raise exceptions.ClientConfigurationError( + '`sslmode` parameter must be one of: {}'.format(modes)) + + # docs at https://www.postgresql.org/docs/10/static/libpq-connect.html + if sslmode < SSLMode.allow: + ssl = False + else: + ssl = ssl_module.SSLContext(ssl_module.PROTOCOL_TLS_CLIENT) + ssl.check_hostname = sslmode >= SSLMode.verify_full + if sslmode < SSLMode.require: + ssl.verify_mode = ssl_module.CERT_NONE + else: + if sslrootcert is None: + sslrootcert = os.getenv('PGSSLROOTCERT') + if sslrootcert: + ssl.load_verify_locations(cafile=sslrootcert) + ssl.verify_mode = ssl_module.CERT_REQUIRED + else: + try: + sslrootcert = _dot_postgresql_path('root.crt') + if sslrootcert is not None: + ssl.load_verify_locations(cafile=sslrootcert) + else: + raise exceptions.ClientConfigurationError( + 'cannot determine location of user ' + 'PostgreSQL configuration directory' + ) + except ( + exceptions.ClientConfigurationError, + FileNotFoundError, + NotADirectoryError, + ): + if sslmode > SSLMode.require: + if sslrootcert is None: + sslrootcert = '~/.postgresql/root.crt' + detail = ( + 'Could not determine location of user ' + 'home directory (HOME is either unset, ' + 'inaccessible, or does not point to a ' + 'valid directory)' + ) + else: + detail = None + raise exceptions.ClientConfigurationError( + f'root certificate file "{sslrootcert}" does ' + f'not exist or cannot be accessed', + hint='Provide the certificate file directly ' + f'or make sure "{sslrootcert}" ' + 'exists and is readable.', + detail=detail, + ) + elif sslmode == SSLMode.require: + ssl.verify_mode = ssl_module.CERT_NONE + else: + assert False, 'unreachable' + else: + ssl.verify_mode = ssl_module.CERT_REQUIRED + + if sslcrl is None: + sslcrl = os.getenv('PGSSLCRL') + if sslcrl: + ssl.load_verify_locations(cafile=sslcrl) + ssl.verify_flags |= ssl_module.VERIFY_CRL_CHECK_CHAIN + else: + sslcrl = _dot_postgresql_path('root.crl') + if sslcrl is not None: + try: + ssl.load_verify_locations(cafile=sslcrl) + except ( + FileNotFoundError, + NotADirectoryError, + ): + pass + else: + ssl.verify_flags |= \ + ssl_module.VERIFY_CRL_CHECK_CHAIN + + if sslkey is None: + sslkey = os.getenv('PGSSLKEY') + if not sslkey: + sslkey = _dot_postgresql_path('postgresql.key') + if sslkey is not None and not sslkey.exists(): + sslkey = None + if not sslpassword: + sslpassword = '' + if sslcert is None: + sslcert = os.getenv('PGSSLCERT') + if sslcert: + ssl.load_cert_chain( + sslcert, keyfile=sslkey, password=lambda: sslpassword + ) + else: + sslcert = _dot_postgresql_path('postgresql.crt') + if sslcert is not None: + try: + ssl.load_cert_chain( + sslcert, + keyfile=sslkey, + password=lambda: sslpassword + ) + except (FileNotFoundError, NotADirectoryError): + pass + + # OpenSSL 1.1.1 keylog file, copied from create_default_context() + if hasattr(ssl, 'keylog_filename'): + keylogfile = os.environ.get('SSLKEYLOGFILE') + if keylogfile and not sys.flags.ignore_environment: + ssl.keylog_filename = keylogfile + + if ssl_min_protocol_version is None: + ssl_min_protocol_version = os.getenv('PGSSLMINPROTOCOLVERSION') + if ssl_min_protocol_version: + ssl.minimum_version = _parse_tls_version( + ssl_min_protocol_version + ) + else: + ssl.minimum_version = _parse_tls_version('TLSv1.2') + + if ssl_max_protocol_version is None: + ssl_max_protocol_version = os.getenv('PGSSLMAXPROTOCOLVERSION') + if ssl_max_protocol_version: + ssl.maximum_version = _parse_tls_version( + ssl_max_protocol_version + ) + + elif ssl is True: + ssl = ssl_module.create_default_context() + sslmode = SSLMode.verify_full + else: + sslmode = SSLMode.disable + + if server_settings is not None and ( + not isinstance(server_settings, dict) or + not all(isinstance(k, str) for k in server_settings) or + not all(isinstance(v, str) for v in server_settings.values())): + raise exceptions.ClientConfigurationError( + 'server_settings is expected to be None or ' + 'a Dict[str, str]') + + if target_session_attrs is None: + target_session_attrs = os.getenv( + "PGTARGETSESSIONATTRS", SessionAttribute.any + ) + try: + target_session_attrs = SessionAttribute(target_session_attrs) + except ValueError: + raise exceptions.ClientConfigurationError( + "target_session_attrs is expected to be one of " + "{!r}" + ", got {!r}".format( + SessionAttribute.__members__.values, target_session_attrs + ) + ) from None + + params = _ConnectionParameters( + user=user, password=password, database=database, ssl=ssl, + sslmode=sslmode, direct_tls=direct_tls, + server_settings=server_settings, + target_session_attrs=target_session_attrs) + + return addrs, params + + +def _parse_connect_arguments(*, dsn, host, port, user, password, passfile, + database, command_timeout, + statement_cache_size, + max_cached_statement_lifetime, + max_cacheable_statement_size, + ssl, direct_tls, server_settings, + target_session_attrs): + local_vars = locals() + for var_name in {'max_cacheable_statement_size', + 'max_cached_statement_lifetime', + 'statement_cache_size'}: + var_val = local_vars[var_name] + if var_val is None or isinstance(var_val, bool) or var_val < 0: + raise ValueError( + '{} is expected to be greater ' + 'or equal to 0, got {!r}'.format(var_name, var_val)) + + if command_timeout is not None: + try: + if isinstance(command_timeout, bool): + raise ValueError + command_timeout = float(command_timeout) + if command_timeout <= 0: + raise ValueError + except ValueError: + raise ValueError( + 'invalid command_timeout value: ' + 'expected greater than 0 float (got {!r})'.format( + command_timeout)) from None + + addrs, params = _parse_connect_dsn_and_args( + dsn=dsn, host=host, port=port, user=user, + password=password, passfile=passfile, ssl=ssl, + direct_tls=direct_tls, database=database, + server_settings=server_settings, + target_session_attrs=target_session_attrs) + + config = _ClientConfiguration( + command_timeout=command_timeout, + statement_cache_size=statement_cache_size, + max_cached_statement_lifetime=max_cached_statement_lifetime, + max_cacheable_statement_size=max_cacheable_statement_size,) + + return addrs, params, config + + +class TLSUpgradeProto(asyncio.Protocol): + def __init__(self, loop, host, port, ssl_context, ssl_is_advisory): + self.on_data = _create_future(loop) + self.host = host + self.port = port + self.ssl_context = ssl_context + self.ssl_is_advisory = ssl_is_advisory + + def data_received(self, data): + if data == b'S': + self.on_data.set_result(True) + elif (self.ssl_is_advisory and + self.ssl_context.verify_mode == ssl_module.CERT_NONE and + data == b'N'): + # ssl_is_advisory will imply that ssl.verify_mode == CERT_NONE, + # since the only way to get ssl_is_advisory is from + # sslmode=prefer. But be extra sure to disallow insecure + # connections when the ssl context asks for real security. + self.on_data.set_result(False) + else: + self.on_data.set_exception( + ConnectionError( + 'PostgreSQL server at "{host}:{port}" ' + 'rejected SSL upgrade'.format( + host=self.host, port=self.port))) + + def connection_lost(self, exc): + if not self.on_data.done(): + if exc is None: + exc = ConnectionError('unexpected connection_lost() call') + self.on_data.set_exception(exc) + + +async def _create_ssl_connection(protocol_factory, host, port, *, + loop, ssl_context, ssl_is_advisory=False): + + tr, pr = await loop.create_connection( + lambda: TLSUpgradeProto(loop, host, port, + ssl_context, ssl_is_advisory), + host, port) + + tr.write(struct.pack('!ll', 8, 80877103)) # SSLRequest message. + + try: + do_ssl_upgrade = await pr.on_data + except (Exception, asyncio.CancelledError): + tr.close() + raise + + if hasattr(loop, 'start_tls'): + if do_ssl_upgrade: + try: + new_tr = await loop.start_tls( + tr, pr, ssl_context, server_hostname=host) + except (Exception, asyncio.CancelledError): + tr.close() + raise + else: + new_tr = tr + + pg_proto = protocol_factory() + pg_proto.is_ssl = do_ssl_upgrade + pg_proto.connection_made(new_tr) + new_tr.set_protocol(pg_proto) + + return new_tr, pg_proto + else: + conn_factory = functools.partial( + loop.create_connection, protocol_factory) + + if do_ssl_upgrade: + conn_factory = functools.partial( + conn_factory, ssl=ssl_context, server_hostname=host) + + sock = _get_socket(tr) + sock = sock.dup() + _set_nodelay(sock) + tr.close() + + try: + new_tr, pg_proto = await conn_factory(sock=sock) + pg_proto.is_ssl = do_ssl_upgrade + return new_tr, pg_proto + except (Exception, asyncio.CancelledError): + sock.close() + raise + + +async def _connect_addr( + *, + addr, + loop, + params, + config, + connection_class, + record_class +): + assert loop is not None + + params_input = params + if callable(params.password): + password = params.password() + if inspect.isawaitable(password): + password = await password + + params = params._replace(password=password) + args = (addr, loop, config, connection_class, record_class, params_input) + + # prepare the params (which attempt has ssl) for the 2 attempts + if params.sslmode == SSLMode.allow: + params_retry = params + params = params._replace(ssl=None) + elif params.sslmode == SSLMode.prefer: + params_retry = params._replace(ssl=None) + else: + # skip retry if we don't have to + return await __connect_addr(params, False, *args) + + # first attempt + try: + return await __connect_addr(params, True, *args) + except _RetryConnectSignal: + pass + + # second attempt + return await __connect_addr(params_retry, False, *args) + + +class _RetryConnectSignal(Exception): + pass + + +async def __connect_addr( + params, + retry, + addr, + loop, + config, + connection_class, + record_class, + params_input, +): + connected = _create_future(loop) + + proto_factory = lambda: protocol.Protocol( + addr, connected, params, record_class, loop) + + if isinstance(addr, str): + # UNIX socket + connector = loop.create_unix_connection(proto_factory, addr) + + elif params.ssl and params.direct_tls: + # if ssl and direct_tls are given, skip STARTTLS and perform direct + # SSL connection + connector = loop.create_connection( + proto_factory, *addr, ssl=params.ssl + ) + + elif params.ssl: + connector = _create_ssl_connection( + proto_factory, *addr, loop=loop, ssl_context=params.ssl, + ssl_is_advisory=params.sslmode == SSLMode.prefer) + else: + connector = loop.create_connection(proto_factory, *addr) + + tr, pr = await connector + + try: + await connected + except ( + exceptions.InvalidAuthorizationSpecificationError, + exceptions.ConnectionDoesNotExistError, # seen on Windows + ): + tr.close() + + # retry=True here is a redundant check because we don't want to + # accidentally raise the internal _RetryConnectSignal to the user + if retry and ( + params.sslmode == SSLMode.allow and not pr.is_ssl or + params.sslmode == SSLMode.prefer and pr.is_ssl + ): + # Trigger retry when: + # 1. First attempt with sslmode=allow, ssl=None failed + # 2. First attempt with sslmode=prefer, ssl=ctx failed while the + # server claimed to support SSL (returning "S" for SSLRequest) + # (likely because pg_hba.conf rejected the connection) + raise _RetryConnectSignal() + + else: + # but will NOT retry if: + # 1. First attempt with sslmode=prefer failed but the server + # doesn't support SSL (returning 'N' for SSLRequest), because + # we already tried to connect without SSL thru ssl_is_advisory + # 2. Second attempt with sslmode=prefer, ssl=None failed + # 3. Second attempt with sslmode=allow, ssl=ctx failed + # 4. Any other sslmode + raise + + except (Exception, asyncio.CancelledError): + tr.close() + raise + + con = connection_class(pr, tr, loop, addr, config, params_input) + pr.set_connection(con) + return con + + +class SessionAttribute(str, enum.Enum): + any = 'any' + primary = 'primary' + standby = 'standby' + prefer_standby = 'prefer-standby' + read_write = "read-write" + read_only = "read-only" + + +def _accept_in_hot_standby(should_be_in_hot_standby: bool): + """ + If the server didn't report "in_hot_standby" at startup, we must determine + the state by checking "SELECT pg_catalog.pg_is_in_recovery()". + If the server allows a connection and states it is in recovery it must + be a replica/standby server. + """ + async def can_be_used(connection): + settings = connection.get_settings() + hot_standby_status = getattr(settings, 'in_hot_standby', None) + if hot_standby_status is not None: + is_in_hot_standby = hot_standby_status == 'on' + else: + is_in_hot_standby = await connection.fetchval( + "SELECT pg_catalog.pg_is_in_recovery()" + ) + return is_in_hot_standby == should_be_in_hot_standby + + return can_be_used + + +def _accept_read_only(should_be_read_only: bool): + """ + Verify the server has not set default_transaction_read_only=True + """ + async def can_be_used(connection): + settings = connection.get_settings() + is_readonly = getattr(settings, 'default_transaction_read_only', 'off') + + if is_readonly == "on": + return should_be_read_only + + return await _accept_in_hot_standby(should_be_read_only)(connection) + return can_be_used + + +async def _accept_any(_): + return True + + +target_attrs_check = { + SessionAttribute.any: _accept_any, + SessionAttribute.primary: _accept_in_hot_standby(False), + SessionAttribute.standby: _accept_in_hot_standby(True), + SessionAttribute.prefer_standby: _accept_in_hot_standby(True), + SessionAttribute.read_write: _accept_read_only(False), + SessionAttribute.read_only: _accept_read_only(True), +} + + +async def _can_use_connection(connection, attr: SessionAttribute): + can_use = target_attrs_check[attr] + return await can_use(connection) + + +async def _connect(*, loop, connection_class, record_class, **kwargs): + if loop is None: + loop = asyncio.get_event_loop() + + addrs, params, config = _parse_connect_arguments(**kwargs) + target_attr = params.target_session_attrs + + candidates = [] + chosen_connection = None + last_error = None + for addr in addrs: + try: + conn = await _connect_addr( + addr=addr, + loop=loop, + params=params, + config=config, + connection_class=connection_class, + record_class=record_class, + ) + candidates.append(conn) + if await _can_use_connection(conn, target_attr): + chosen_connection = conn + break + except OSError as ex: + last_error = ex + else: + if target_attr == SessionAttribute.prefer_standby and candidates: + chosen_connection = random.choice(candidates) + + await asyncio.gather( + *(c.close() for c in candidates if c is not chosen_connection), + return_exceptions=True + ) + + if chosen_connection: + return chosen_connection + + raise last_error or exceptions.TargetServerAttributeNotMatched( + 'None of the hosts match the target attribute requirement ' + '{!r}'.format(target_attr) + ) + + +async def _cancel(*, loop, addr, params: _ConnectionParameters, + backend_pid, backend_secret): + + class CancelProto(asyncio.Protocol): + + def __init__(self): + self.on_disconnect = _create_future(loop) + self.is_ssl = False + + def connection_lost(self, exc): + if not self.on_disconnect.done(): + self.on_disconnect.set_result(True) + + if isinstance(addr, str): + tr, pr = await loop.create_unix_connection(CancelProto, addr) + else: + if params.ssl and params.sslmode != SSLMode.allow: + tr, pr = await _create_ssl_connection( + CancelProto, + *addr, + loop=loop, + ssl_context=params.ssl, + ssl_is_advisory=params.sslmode == SSLMode.prefer) + else: + tr, pr = await loop.create_connection( + CancelProto, *addr) + _set_nodelay(_get_socket(tr)) + + # Pack a CancelRequest message + msg = struct.pack('!llll', 16, 80877102, backend_pid, backend_secret) + + try: + tr.write(msg) + await pr.on_disconnect + finally: + tr.close() + + +def _get_socket(transport): + sock = transport.get_extra_info('socket') + if sock is None: + # Shouldn't happen with any asyncio-complaint event loop. + raise ConnectionError( + 'could not get the socket for transport {!r}'.format(transport)) + return sock + + +def _set_nodelay(sock): + if not hasattr(socket, 'AF_UNIX') or sock.family != socket.AF_UNIX: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + + +def _create_future(loop): + try: + create_future = loop.create_future + except AttributeError: + return asyncio.Future(loop=loop) + else: + return create_future() diff --git a/env/Lib/site-packages/asyncpg/connection.py b/env/Lib/site-packages/asyncpg/connection.py new file mode 100644 index 0000000..0367e36 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/connection.py @@ -0,0 +1,2655 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import asyncio +import asyncpg +import collections +import collections.abc +import contextlib +import functools +import itertools +import inspect +import os +import sys +import time +import traceback +import typing +import warnings +import weakref + +from . import compat +from . import connect_utils +from . import cursor +from . import exceptions +from . import introspection +from . import prepared_stmt +from . import protocol +from . import serverversion +from . import transaction +from . import utils + + +class ConnectionMeta(type): + + def __instancecheck__(cls, instance): + mro = type(instance).__mro__ + return Connection in mro or _ConnectionProxy in mro + + +class Connection(metaclass=ConnectionMeta): + """A representation of a database session. + + Connections are created by calling :func:`~asyncpg.connection.connect`. + """ + + __slots__ = ('_protocol', '_transport', '_loop', + '_top_xact', '_aborted', + '_pool_release_ctr', '_stmt_cache', '_stmts_to_close', + '_stmt_cache_enabled', + '_listeners', '_server_version', '_server_caps', + '_intro_query', '_reset_query', '_proxy', + '_stmt_exclusive_section', '_config', '_params', '_addr', + '_log_listeners', '_termination_listeners', '_cancellations', + '_source_traceback', '_query_loggers', '__weakref__') + + def __init__(self, protocol, transport, loop, + addr, + config: connect_utils._ClientConfiguration, + params: connect_utils._ConnectionParameters): + self._protocol = protocol + self._transport = transport + self._loop = loop + self._top_xact = None + self._aborted = False + # Incremented every time the connection is released back to a pool. + # Used to catch invalid references to connection-related resources + # post-release (e.g. explicit prepared statements). + self._pool_release_ctr = 0 + + self._addr = addr + self._config = config + self._params = params + + self._stmt_cache = _StatementCache( + loop=loop, + max_size=config.statement_cache_size, + on_remove=functools.partial( + _weak_maybe_gc_stmt, weakref.ref(self)), + max_lifetime=config.max_cached_statement_lifetime) + + self._stmts_to_close = set() + self._stmt_cache_enabled = config.statement_cache_size > 0 + + self._listeners = {} + self._log_listeners = set() + self._cancellations = set() + self._termination_listeners = set() + self._query_loggers = set() + + settings = self._protocol.get_settings() + ver_string = settings.server_version + self._server_version = \ + serverversion.split_server_version_string(ver_string) + + self._server_caps = _detect_server_capabilities( + self._server_version, settings) + + if self._server_version < (14, 0): + self._intro_query = introspection.INTRO_LOOKUP_TYPES_13 + else: + self._intro_query = introspection.INTRO_LOOKUP_TYPES + + self._reset_query = None + self._proxy = None + + # Used to serialize operations that might involve anonymous + # statements. Specifically, we want to make the following + # operation atomic: + # ("prepare an anonymous statement", "use the statement") + # + # Used for `con.fetchval()`, `con.fetch()`, `con.fetchrow()`, + # `con.execute()`, and `con.executemany()`. + self._stmt_exclusive_section = _Atomic() + + if loop.get_debug(): + self._source_traceback = _extract_stack() + else: + self._source_traceback = None + + def __del__(self): + if not self.is_closed() and self._protocol is not None: + if self._source_traceback: + msg = "unclosed connection {!r}; created at:\n {}".format( + self, self._source_traceback) + else: + msg = ( + "unclosed connection {!r}; run in asyncio debug " + "mode to show the traceback of connection " + "origin".format(self) + ) + + warnings.warn(msg, ResourceWarning) + if not self._loop.is_closed(): + self.terminate() + + async def add_listener(self, channel, callback): + """Add a listener for Postgres notifications. + + :param str channel: Channel to listen on. + + :param callable callback: + A callable or a coroutine function receiving the following + arguments: + **connection**: a Connection the callback is registered with; + **pid**: PID of the Postgres server that sent the notification; + **channel**: name of the channel the notification was sent to; + **payload**: the payload. + + .. versionchanged:: 0.24.0 + The ``callback`` argument may be a coroutine function. + """ + self._check_open() + if channel not in self._listeners: + await self.fetch('LISTEN {}'.format(utils._quote_ident(channel))) + self._listeners[channel] = set() + self._listeners[channel].add(_Callback.from_callable(callback)) + + async def remove_listener(self, channel, callback): + """Remove a listening callback on the specified channel.""" + if self.is_closed(): + return + if channel not in self._listeners: + return + cb = _Callback.from_callable(callback) + if cb not in self._listeners[channel]: + return + self._listeners[channel].remove(cb) + if not self._listeners[channel]: + del self._listeners[channel] + await self.fetch('UNLISTEN {}'.format(utils._quote_ident(channel))) + + def add_log_listener(self, callback): + """Add a listener for Postgres log messages. + + It will be called when asyncronous NoticeResponse is received + from the connection. Possible message types are: WARNING, NOTICE, + DEBUG, INFO, or LOG. + + :param callable callback: + A callable or a coroutine function receiving the following + arguments: + **connection**: a Connection the callback is registered with; + **message**: the `exceptions.PostgresLogMessage` message. + + .. versionadded:: 0.12.0 + + .. versionchanged:: 0.24.0 + The ``callback`` argument may be a coroutine function. + """ + if self.is_closed(): + raise exceptions.InterfaceError('connection is closed') + self._log_listeners.add(_Callback.from_callable(callback)) + + def remove_log_listener(self, callback): + """Remove a listening callback for log messages. + + .. versionadded:: 0.12.0 + """ + self._log_listeners.discard(_Callback.from_callable(callback)) + + def add_termination_listener(self, callback): + """Add a listener that will be called when the connection is closed. + + :param callable callback: + A callable or a coroutine function receiving one argument: + **connection**: a Connection the callback is registered with. + + .. versionadded:: 0.21.0 + + .. versionchanged:: 0.24.0 + The ``callback`` argument may be a coroutine function. + """ + self._termination_listeners.add(_Callback.from_callable(callback)) + + def remove_termination_listener(self, callback): + """Remove a listening callback for connection termination. + + :param callable callback: + The callable or coroutine function that was passed to + :meth:`Connection.add_termination_listener`. + + .. versionadded:: 0.21.0 + """ + self._termination_listeners.discard(_Callback.from_callable(callback)) + + def add_query_logger(self, callback): + """Add a logger that will be called when queries are executed. + + :param callable callback: + A callable or a coroutine function receiving one argument: + **record**: a LoggedQuery containing `query`, `args`, `timeout`, + `elapsed`, `exception`, `conn_addr`, and + `conn_params`. + + .. versionadded:: 0.29.0 + """ + self._query_loggers.add(_Callback.from_callable(callback)) + + def remove_query_logger(self, callback): + """Remove a query logger callback. + + :param callable callback: + The callable or coroutine function that was passed to + :meth:`Connection.add_query_logger`. + + .. versionadded:: 0.29.0 + """ + self._query_loggers.discard(_Callback.from_callable(callback)) + + def get_server_pid(self): + """Return the PID of the Postgres server the connection is bound to.""" + return self._protocol.get_server_pid() + + def get_server_version(self): + """Return the version of the connected PostgreSQL server. + + The returned value is a named tuple similar to that in + ``sys.version_info``: + + .. code-block:: pycon + + >>> con.get_server_version() + ServerVersion(major=9, minor=6, micro=1, + releaselevel='final', serial=0) + + .. versionadded:: 0.8.0 + """ + return self._server_version + + def get_settings(self): + """Return connection settings. + + :return: :class:`~asyncpg.ConnectionSettings`. + """ + return self._protocol.get_settings() + + def transaction(self, *, isolation=None, readonly=False, + deferrable=False): + """Create a :class:`~transaction.Transaction` object. + + Refer to `PostgreSQL documentation`_ on the meaning of transaction + parameters. + + :param isolation: Transaction isolation mode, can be one of: + `'serializable'`, `'repeatable_read'`, + `'read_uncommitted'`, `'read_committed'`. If not + specified, the behavior is up to the server and + session, which is usually ``read_committed``. + + :param readonly: Specifies whether or not this transaction is + read-only. + + :param deferrable: Specifies whether or not this transaction is + deferrable. + + .. _`PostgreSQL documentation`: + https://www.postgresql.org/docs/ + current/static/sql-set-transaction.html + """ + self._check_open() + return transaction.Transaction(self, isolation, readonly, deferrable) + + def is_in_transaction(self): + """Return True if Connection is currently inside a transaction. + + :return bool: True if inside transaction, False otherwise. + + .. versionadded:: 0.16.0 + """ + return self._protocol.is_in_transaction() + + async def execute(self, query: str, *args, timeout: float=None) -> str: + """Execute an SQL command (or commands). + + This method can execute many SQL commands at once, when no arguments + are provided. + + Example: + + .. code-block:: pycon + + >>> await con.execute(''' + ... CREATE TABLE mytab (a int); + ... INSERT INTO mytab (a) VALUES (100), (200), (300); + ... ''') + INSERT 0 3 + + >>> await con.execute(''' + ... INSERT INTO mytab (a) VALUES ($1), ($2) + ... ''', 10, 20) + INSERT 0 2 + + :param args: Query arguments. + :param float timeout: Optional timeout value in seconds. + :return str: Status of the last SQL command. + + .. versionchanged:: 0.5.4 + Made it possible to pass query arguments. + """ + self._check_open() + + if not args: + if self._query_loggers: + with self._time_and_log(query, args, timeout): + result = await self._protocol.query(query, timeout) + else: + result = await self._protocol.query(query, timeout) + return result + + _, status, _ = await self._execute( + query, + args, + 0, + timeout, + return_status=True, + ) + return status.decode() + + async def executemany(self, command: str, args, *, timeout: float=None): + """Execute an SQL *command* for each sequence of arguments in *args*. + + Example: + + .. code-block:: pycon + + >>> await con.executemany(''' + ... INSERT INTO mytab (a) VALUES ($1, $2, $3); + ... ''', [(1, 2, 3), (4, 5, 6)]) + + :param command: Command to execute. + :param args: An iterable containing sequences of arguments. + :param float timeout: Optional timeout value in seconds. + :return None: This method discards the results of the operations. + + .. versionadded:: 0.7.0 + + .. versionchanged:: 0.11.0 + `timeout` became a keyword-only parameter. + + .. versionchanged:: 0.22.0 + ``executemany()`` is now an atomic operation, which means that + either all executions succeed, or none at all. This is in contrast + to prior versions, where the effect of already-processed iterations + would remain in place when an error has occurred, unless + ``executemany()`` was called in a transaction. + """ + self._check_open() + return await self._executemany(command, args, timeout) + + async def _get_statement( + self, + query, + timeout, + *, + named=False, + use_cache=True, + ignore_custom_codec=False, + record_class=None + ): + if record_class is None: + record_class = self._protocol.get_record_class() + else: + _check_record_class(record_class) + + if use_cache: + statement = self._stmt_cache.get( + (query, record_class, ignore_custom_codec) + ) + if statement is not None: + return statement + + # Only use the cache when: + # * `statement_cache_size` is greater than 0; + # * query size is less than `max_cacheable_statement_size`. + use_cache = ( + self._stmt_cache_enabled + and ( + not self._config.max_cacheable_statement_size + or len(query) <= self._config.max_cacheable_statement_size + ) + ) + + if isinstance(named, str): + stmt_name = named + elif use_cache or named: + stmt_name = self._get_unique_id('stmt') + else: + stmt_name = '' + + statement = await self._protocol.prepare( + stmt_name, + query, + timeout, + record_class=record_class, + ignore_custom_codec=ignore_custom_codec, + ) + need_reprepare = False + types_with_missing_codecs = statement._init_types() + tries = 0 + while types_with_missing_codecs: + settings = self._protocol.get_settings() + + # Introspect newly seen types and populate the + # codec cache. + types, intro_stmt = await self._introspect_types( + types_with_missing_codecs, timeout) + + settings.register_data_types(types) + + # The introspection query has used an anonymous statement, + # which has blown away the anonymous statement we've prepared + # for the query, so we need to re-prepare it. + need_reprepare = not intro_stmt.name and not statement.name + types_with_missing_codecs = statement._init_types() + tries += 1 + if tries > 5: + # In the vast majority of cases there will be only + # one iteration. In rare cases, there might be a race + # with reload_schema_state(), which would cause a + # second try. More than five is clearly a bug. + raise exceptions.InternalClientError( + 'could not resolve query result and/or argument types ' + 'in {} attempts'.format(tries) + ) + + # Now that types have been resolved, populate the codec pipeline + # for the statement. + statement._init_codecs() + + if ( + need_reprepare + or (not statement.name and not self._stmt_cache_enabled) + ): + # Mark this anonymous prepared statement as "unprepared", + # causing it to get re-Parsed in next bind_execute. + # We always do this when stmt_cache_size is set to 0 assuming + # people are running PgBouncer which is mishandling implicit + # transactions. + statement.mark_unprepared() + + if use_cache: + self._stmt_cache.put( + (query, record_class, ignore_custom_codec), statement) + + # If we've just created a new statement object, check if there + # are any statements for GC. + if self._stmts_to_close: + await self._cleanup_stmts() + + return statement + + async def _introspect_types(self, typeoids, timeout): + if self._server_caps.jit: + try: + cfgrow, _ = await self.__execute( + """ + SELECT + current_setting('jit') AS cur, + set_config('jit', 'off', false) AS new + """, + (), + 0, + timeout, + ignore_custom_codec=True, + ) + jit_state = cfgrow[0]['cur'] + except exceptions.UndefinedObjectError: + jit_state = 'off' + else: + jit_state = 'off' + + result = await self.__execute( + self._intro_query, + (list(typeoids),), + 0, + timeout, + ignore_custom_codec=True, + ) + + if jit_state != 'off': + await self.__execute( + """ + SELECT + set_config('jit', $1, false) + """, + (jit_state,), + 0, + timeout, + ignore_custom_codec=True, + ) + + return result + + async def _introspect_type(self, typename, schema): + if ( + schema == 'pg_catalog' + and typename.lower() in protocol.BUILTIN_TYPE_NAME_MAP + ): + typeoid = protocol.BUILTIN_TYPE_NAME_MAP[typename.lower()] + rows = await self._execute( + introspection.TYPE_BY_OID, + [typeoid], + limit=0, + timeout=None, + ignore_custom_codec=True, + ) + else: + rows = await self._execute( + introspection.TYPE_BY_NAME, + [typename, schema], + limit=1, + timeout=None, + ignore_custom_codec=True, + ) + + if not rows: + raise ValueError( + 'unknown type: {}.{}'.format(schema, typename)) + + return rows[0] + + def cursor( + self, + query, + *args, + prefetch=None, + timeout=None, + record_class=None + ): + """Return a *cursor factory* for the specified query. + + :param args: + Query arguments. + :param int prefetch: + The number of rows the *cursor iterator* + will prefetch (defaults to ``50``.) + :param float timeout: + Optional timeout in seconds. + :param type record_class: + If specified, the class to use for records returned by this cursor. + Must be a subclass of :class:`~asyncpg.Record`. If not specified, + a per-connection *record_class* is used. + + :return: + A :class:`~cursor.CursorFactory` object. + + .. versionchanged:: 0.22.0 + Added the *record_class* parameter. + """ + self._check_open() + return cursor.CursorFactory( + self, + query, + None, + args, + prefetch, + timeout, + record_class, + ) + + async def prepare( + self, + query, + *, + name=None, + timeout=None, + record_class=None, + ): + """Create a *prepared statement* for the specified query. + + :param str query: + Text of the query to create a prepared statement for. + :param str name: + Optional name of the returned prepared statement. If not + specified, the name is auto-generated. + :param float timeout: + Optional timeout value in seconds. + :param type record_class: + If specified, the class to use for records returned by the + prepared statement. Must be a subclass of + :class:`~asyncpg.Record`. If not specified, a per-connection + *record_class* is used. + + :return: + A :class:`~prepared_stmt.PreparedStatement` instance. + + .. versionchanged:: 0.22.0 + Added the *record_class* parameter. + + .. versionchanged:: 0.25.0 + Added the *name* parameter. + """ + return await self._prepare( + query, + name=name, + timeout=timeout, + use_cache=False, + record_class=record_class, + ) + + async def _prepare( + self, + query, + *, + name=None, + timeout=None, + use_cache: bool=False, + record_class=None + ): + self._check_open() + stmt = await self._get_statement( + query, + timeout, + named=True if name is None else name, + use_cache=use_cache, + record_class=record_class, + ) + return prepared_stmt.PreparedStatement(self, query, stmt) + + async def fetch( + self, + query, + *args, + timeout=None, + record_class=None + ) -> list: + """Run a query and return the results as a list of :class:`Record`. + + :param str query: + Query text. + :param args: + Query arguments. + :param float timeout: + Optional timeout value in seconds. + :param type record_class: + If specified, the class to use for records returned by this method. + Must be a subclass of :class:`~asyncpg.Record`. If not specified, + a per-connection *record_class* is used. + + :return list: + A list of :class:`~asyncpg.Record` instances. If specified, the + actual type of list elements would be *record_class*. + + .. versionchanged:: 0.22.0 + Added the *record_class* parameter. + """ + self._check_open() + return await self._execute( + query, + args, + 0, + timeout, + record_class=record_class, + ) + + async def fetchval(self, query, *args, column=0, timeout=None): + """Run a query and return a value in the first row. + + :param str query: Query text. + :param args: Query arguments. + :param int column: Numeric index within the record of the value to + return (defaults to 0). + :param float timeout: Optional timeout value in seconds. + If not specified, defaults to the value of + ``command_timeout`` argument to the ``Connection`` + instance constructor. + + :return: The value of the specified column of the first record, or + None if no records were returned by the query. + """ + self._check_open() + data = await self._execute(query, args, 1, timeout) + if not data: + return None + return data[0][column] + + async def fetchrow( + self, + query, + *args, + timeout=None, + record_class=None + ): + """Run a query and return the first row. + + :param str query: + Query text + :param args: + Query arguments + :param float timeout: + Optional timeout value in seconds. + :param type record_class: + If specified, the class to use for the value returned by this + method. Must be a subclass of :class:`~asyncpg.Record`. + If not specified, a per-connection *record_class* is used. + + :return: + The first row as a :class:`~asyncpg.Record` instance, or None if + no records were returned by the query. If specified, + *record_class* is used as the type for the result value. + + .. versionchanged:: 0.22.0 + Added the *record_class* parameter. + """ + self._check_open() + data = await self._execute( + query, + args, + 1, + timeout, + record_class=record_class, + ) + if not data: + return None + return data[0] + + async def copy_from_table(self, table_name, *, output, + columns=None, schema_name=None, timeout=None, + format=None, oids=None, delimiter=None, + null=None, header=None, quote=None, + escape=None, force_quote=None, encoding=None): + """Copy table contents to a file or file-like object. + + :param str table_name: + The name of the table to copy data from. + + :param output: + A :term:`path-like object `, + or a :term:`file-like object `, or + a :term:`coroutine function ` + that takes a ``bytes`` instance as a sole argument. + + :param list columns: + An optional list of column names to copy. + + :param str schema_name: + An optional schema name to qualify the table. + + :param float timeout: + Optional timeout value in seconds. + + The remaining keyword arguments are ``COPY`` statement options, + see `COPY statement documentation`_ for details. + + :return: The status string of the COPY command. + + Example: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> async def run(): + ... con = await asyncpg.connect(user='postgres') + ... result = await con.copy_from_table( + ... 'mytable', columns=('foo', 'bar'), + ... output='file.csv', format='csv') + ... print(result) + ... + >>> asyncio.get_event_loop().run_until_complete(run()) + 'COPY 100' + + .. _`COPY statement documentation`: + https://www.postgresql.org/docs/current/static/sql-copy.html + + .. versionadded:: 0.11.0 + """ + tabname = utils._quote_ident(table_name) + if schema_name: + tabname = utils._quote_ident(schema_name) + '.' + tabname + + if columns: + cols = '({})'.format( + ', '.join(utils._quote_ident(c) for c in columns)) + else: + cols = '' + + opts = self._format_copy_opts( + format=format, oids=oids, delimiter=delimiter, + null=null, header=header, quote=quote, escape=escape, + force_quote=force_quote, encoding=encoding + ) + + copy_stmt = 'COPY {tab}{cols} TO STDOUT {opts}'.format( + tab=tabname, cols=cols, opts=opts) + + return await self._copy_out(copy_stmt, output, timeout) + + async def copy_from_query(self, query, *args, output, + timeout=None, format=None, oids=None, + delimiter=None, null=None, header=None, + quote=None, escape=None, force_quote=None, + encoding=None): + """Copy the results of a query to a file or file-like object. + + :param str query: + The query to copy the results of. + + :param args: + Query arguments. + + :param output: + A :term:`path-like object `, + or a :term:`file-like object `, or + a :term:`coroutine function ` + that takes a ``bytes`` instance as a sole argument. + + :param float timeout: + Optional timeout value in seconds. + + The remaining keyword arguments are ``COPY`` statement options, + see `COPY statement documentation`_ for details. + + :return: The status string of the COPY command. + + Example: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> async def run(): + ... con = await asyncpg.connect(user='postgres') + ... result = await con.copy_from_query( + ... 'SELECT foo, bar FROM mytable WHERE foo > $1', 10, + ... output='file.csv', format='csv') + ... print(result) + ... + >>> asyncio.get_event_loop().run_until_complete(run()) + 'COPY 10' + + .. _`COPY statement documentation`: + https://www.postgresql.org/docs/current/static/sql-copy.html + + .. versionadded:: 0.11.0 + """ + opts = self._format_copy_opts( + format=format, oids=oids, delimiter=delimiter, + null=null, header=header, quote=quote, escape=escape, + force_quote=force_quote, encoding=encoding + ) + + if args: + query = await utils._mogrify(self, query, args) + + copy_stmt = 'COPY ({query}) TO STDOUT {opts}'.format( + query=query, opts=opts) + + return await self._copy_out(copy_stmt, output, timeout) + + async def copy_to_table(self, table_name, *, source, + columns=None, schema_name=None, timeout=None, + format=None, oids=None, freeze=None, + delimiter=None, null=None, header=None, + quote=None, escape=None, force_quote=None, + force_not_null=None, force_null=None, + encoding=None, where=None): + """Copy data to the specified table. + + :param str table_name: + The name of the table to copy data to. + + :param source: + A :term:`path-like object `, + or a :term:`file-like object `, or + an :term:`asynchronous iterable ` + that returns ``bytes``, or an object supporting the + :ref:`buffer protocol `. + + :param list columns: + An optional list of column names to copy. + + :param str schema_name: + An optional schema name to qualify the table. + + :param str where: + An optional SQL expression used to filter rows when copying. + + .. note:: + + Usage of this parameter requires support for the + ``COPY FROM ... WHERE`` syntax, introduced in + PostgreSQL version 12. + + :param float timeout: + Optional timeout value in seconds. + + The remaining keyword arguments are ``COPY`` statement options, + see `COPY statement documentation`_ for details. + + :return: The status string of the COPY command. + + Example: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> async def run(): + ... con = await asyncpg.connect(user='postgres') + ... result = await con.copy_to_table( + ... 'mytable', source='datafile.tbl') + ... print(result) + ... + >>> asyncio.get_event_loop().run_until_complete(run()) + 'COPY 140000' + + .. _`COPY statement documentation`: + https://www.postgresql.org/docs/current/static/sql-copy.html + + .. versionadded:: 0.11.0 + + .. versionadded:: 0.29.0 + Added the *where* parameter. + """ + tabname = utils._quote_ident(table_name) + if schema_name: + tabname = utils._quote_ident(schema_name) + '.' + tabname + + if columns: + cols = '({})'.format( + ', '.join(utils._quote_ident(c) for c in columns)) + else: + cols = '' + + cond = self._format_copy_where(where) + opts = self._format_copy_opts( + format=format, oids=oids, freeze=freeze, delimiter=delimiter, + null=null, header=header, quote=quote, escape=escape, + force_not_null=force_not_null, force_null=force_null, + encoding=encoding + ) + + copy_stmt = 'COPY {tab}{cols} FROM STDIN {opts} {cond}'.format( + tab=tabname, cols=cols, opts=opts, cond=cond) + + return await self._copy_in(copy_stmt, source, timeout) + + async def copy_records_to_table(self, table_name, *, records, + columns=None, schema_name=None, + timeout=None, where=None): + """Copy a list of records to the specified table using binary COPY. + + :param str table_name: + The name of the table to copy data to. + + :param records: + An iterable returning row tuples to copy into the table. + :term:`Asynchronous iterables ` + are also supported. + + :param list columns: + An optional list of column names to copy. + + :param str schema_name: + An optional schema name to qualify the table. + + :param str where: + An optional SQL expression used to filter rows when copying. + + .. note:: + + Usage of this parameter requires support for the + ``COPY FROM ... WHERE`` syntax, introduced in + PostgreSQL version 12. + + + :param float timeout: + Optional timeout value in seconds. + + :return: The status string of the COPY command. + + Example: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> async def run(): + ... con = await asyncpg.connect(user='postgres') + ... result = await con.copy_records_to_table( + ... 'mytable', records=[ + ... (1, 'foo', 'bar'), + ... (2, 'ham', 'spam')]) + ... print(result) + ... + >>> asyncio.get_event_loop().run_until_complete(run()) + 'COPY 2' + + Asynchronous record iterables are also supported: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> async def run(): + ... con = await asyncpg.connect(user='postgres') + ... async def record_gen(size): + ... for i in range(size): + ... yield (i,) + ... result = await con.copy_records_to_table( + ... 'mytable', records=record_gen(100)) + ... print(result) + ... + >>> asyncio.get_event_loop().run_until_complete(run()) + 'COPY 100' + + .. versionadded:: 0.11.0 + + .. versionchanged:: 0.24.0 + The ``records`` argument may be an asynchronous iterable. + + .. versionadded:: 0.29.0 + Added the *where* parameter. + """ + tabname = utils._quote_ident(table_name) + if schema_name: + tabname = utils._quote_ident(schema_name) + '.' + tabname + + if columns: + col_list = ', '.join(utils._quote_ident(c) for c in columns) + cols = '({})'.format(col_list) + else: + col_list = '*' + cols = '' + + intro_query = 'SELECT {cols} FROM {tab} LIMIT 1'.format( + tab=tabname, cols=col_list) + + intro_ps = await self._prepare(intro_query, use_cache=True) + + cond = self._format_copy_where(where) + opts = '(FORMAT binary)' + + copy_stmt = 'COPY {tab}{cols} FROM STDIN {opts} {cond}'.format( + tab=tabname, cols=cols, opts=opts, cond=cond) + + return await self._protocol.copy_in( + copy_stmt, None, None, records, intro_ps._state, timeout) + + def _format_copy_where(self, where): + if where and not self._server_caps.sql_copy_from_where: + raise exceptions.UnsupportedServerFeatureError( + 'the `where` parameter requires PostgreSQL 12 or later') + + if where: + where_clause = 'WHERE ' + where + else: + where_clause = '' + + return where_clause + + def _format_copy_opts(self, *, format=None, oids=None, freeze=None, + delimiter=None, null=None, header=None, quote=None, + escape=None, force_quote=None, force_not_null=None, + force_null=None, encoding=None): + kwargs = dict(locals()) + kwargs.pop('self') + opts = [] + + if force_quote is not None and isinstance(force_quote, bool): + kwargs.pop('force_quote') + if force_quote: + opts.append('FORCE_QUOTE *') + + for k, v in kwargs.items(): + if v is not None: + if k in ('force_not_null', 'force_null', 'force_quote'): + v = '(' + ', '.join(utils._quote_ident(c) for c in v) + ')' + elif k in ('oids', 'freeze', 'header'): + v = str(v) + else: + v = utils._quote_literal(v) + + opts.append('{} {}'.format(k.upper(), v)) + + if opts: + return '(' + ', '.join(opts) + ')' + else: + return '' + + async def _copy_out(self, copy_stmt, output, timeout): + try: + path = os.fspath(output) + except TypeError: + # output is not a path-like object + path = None + + writer = None + opened_by_us = False + run_in_executor = self._loop.run_in_executor + + if path is not None: + # a path + f = await run_in_executor(None, open, path, 'wb') + opened_by_us = True + elif hasattr(output, 'write'): + # file-like + f = output + elif callable(output): + # assuming calling output returns an awaitable. + writer = output + else: + raise TypeError( + 'output is expected to be a file-like object, ' + 'a path-like object or a coroutine function, ' + 'not {}'.format(type(output).__name__) + ) + + if writer is None: + async def _writer(data): + await run_in_executor(None, f.write, data) + writer = _writer + + try: + return await self._protocol.copy_out(copy_stmt, writer, timeout) + finally: + if opened_by_us: + f.close() + + async def _copy_in(self, copy_stmt, source, timeout): + try: + path = os.fspath(source) + except TypeError: + # source is not a path-like object + path = None + + f = None + reader = None + data = None + opened_by_us = False + run_in_executor = self._loop.run_in_executor + + if path is not None: + # a path + f = await run_in_executor(None, open, path, 'rb') + opened_by_us = True + elif hasattr(source, 'read'): + # file-like + f = source + elif isinstance(source, collections.abc.AsyncIterable): + # assuming calling output returns an awaitable. + # copy_in() is designed to handle very large amounts of data, and + # the source async iterable is allowed to return an arbitrary + # amount of data on every iteration. + reader = source + else: + # assuming source is an instance supporting the buffer protocol. + data = source + + if f is not None: + # Copying from a file-like object. + class _Reader: + def __aiter__(self): + return self + + async def __anext__(self): + data = await run_in_executor(None, f.read, 524288) + if len(data) == 0: + raise StopAsyncIteration + else: + return data + + reader = _Reader() + + try: + return await self._protocol.copy_in( + copy_stmt, reader, data, None, None, timeout) + finally: + if opened_by_us: + await run_in_executor(None, f.close) + + async def set_type_codec(self, typename, *, + schema='public', encoder, decoder, + format='text'): + """Set an encoder/decoder pair for the specified data type. + + :param typename: + Name of the data type the codec is for. + + :param schema: + Schema name of the data type the codec is for + (defaults to ``'public'``) + + :param format: + The type of the argument received by the *decoder* callback, + and the type of the *encoder* callback return value. + + If *format* is ``'text'`` (the default), the exchange datum is a + ``str`` instance containing valid text representation of the + data type. + + If *format* is ``'binary'``, the exchange datum is a ``bytes`` + instance containing valid _binary_ representation of the + data type. + + If *format* is ``'tuple'``, the exchange datum is a type-specific + ``tuple`` of values. The table below lists supported data + types and their format for this mode. + + +-----------------+---------------------------------------------+ + | Type | Tuple layout | + +=================+=============================================+ + | ``interval`` | (``months``, ``days``, ``microseconds``) | + +-----------------+---------------------------------------------+ + | ``date`` | (``date ordinal relative to Jan 1 2000``,) | + | | ``-2^31`` for negative infinity timestamp | + | | ``2^31-1`` for positive infinity timestamp. | + +-----------------+---------------------------------------------+ + | ``timestamp`` | (``microseconds relative to Jan 1 2000``,) | + | | ``-2^63`` for negative infinity timestamp | + | | ``2^63-1`` for positive infinity timestamp. | + +-----------------+---------------------------------------------+ + | ``timestamp | (``microseconds relative to Jan 1 2000 | + | with time zone``| UTC``,) | + | | ``-2^63`` for negative infinity timestamp | + | | ``2^63-1`` for positive infinity timestamp. | + +-----------------+---------------------------------------------+ + | ``time`` | (``microseconds``,) | + +-----------------+---------------------------------------------+ + | ``time with | (``microseconds``, | + | time zone`` | ``time zone offset in seconds``) | + +-----------------+---------------------------------------------+ + | any composite | Composite value elements | + | type | | + +-----------------+---------------------------------------------+ + + :param encoder: + Callable accepting a Python object as a single argument and + returning a value encoded according to *format*. + + :param decoder: + Callable accepting a single argument encoded according to *format* + and returning a decoded Python object. + + Example: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> import datetime + >>> from dateutil.relativedelta import relativedelta + >>> async def run(): + ... con = await asyncpg.connect(user='postgres') + ... def encoder(delta): + ... ndelta = delta.normalized() + ... return (ndelta.years * 12 + ndelta.months, + ... ndelta.days, + ... ((ndelta.hours * 3600 + + ... ndelta.minutes * 60 + + ... ndelta.seconds) * 1000000 + + ... ndelta.microseconds)) + ... def decoder(tup): + ... return relativedelta(months=tup[0], days=tup[1], + ... microseconds=tup[2]) + ... await con.set_type_codec( + ... 'interval', schema='pg_catalog', encoder=encoder, + ... decoder=decoder, format='tuple') + ... result = await con.fetchval( + ... "SELECT '2 years 3 mons 1 day'::interval") + ... print(result) + ... print(datetime.datetime(2002, 1, 1) + result) + ... + >>> asyncio.get_event_loop().run_until_complete(run()) + relativedelta(years=+2, months=+3, days=+1) + 2004-04-02 00:00:00 + + .. versionadded:: 0.12.0 + Added the ``format`` keyword argument and support for 'tuple' + format. + + .. versionchanged:: 0.12.0 + The ``binary`` keyword argument is deprecated in favor of + ``format``. + + .. versionchanged:: 0.13.0 + The ``binary`` keyword argument was removed in favor of + ``format``. + + .. versionchanged:: 0.29.0 + Custom codecs for composite types are now supported with + ``format='tuple'``. + + .. note:: + + It is recommended to use the ``'binary'`` or ``'tuple'`` *format* + whenever possible and if the underlying type supports it. Asyncpg + currently does not support text I/O for composite and range types, + and some other functionality, such as + :meth:`Connection.copy_to_table`, does not support types with text + codecs. + """ + self._check_open() + settings = self._protocol.get_settings() + typeinfo = await self._introspect_type(typename, schema) + full_typeinfos = [] + if introspection.is_scalar_type(typeinfo): + kind = 'scalar' + elif introspection.is_composite_type(typeinfo): + if format != 'tuple': + raise exceptions.UnsupportedClientFeatureError( + 'only tuple-format codecs can be used on composite types', + hint="Use `set_type_codec(..., format='tuple')` and " + "pass/interpret data as a Python tuple. See an " + "example at https://magicstack.github.io/asyncpg/" + "current/usage.html#example-decoding-complex-types", + ) + kind = 'composite' + full_typeinfos, _ = await self._introspect_types( + (typeinfo['oid'],), 10) + else: + raise exceptions.InterfaceError( + f'cannot use custom codec on type {schema}.{typename}: ' + f'it is neither a scalar type nor a composite type' + ) + if introspection.is_domain_type(typeinfo): + raise exceptions.UnsupportedClientFeatureError( + 'custom codecs on domain types are not supported', + hint='Set the codec on the base type.', + detail=( + 'PostgreSQL does not distinguish domains from ' + 'their base types in query results at the protocol level.' + ) + ) + + oid = typeinfo['oid'] + settings.add_python_codec( + oid, typename, schema, full_typeinfos, kind, + encoder, decoder, format) + + # Statement cache is no longer valid due to codec changes. + self._drop_local_statement_cache() + + async def reset_type_codec(self, typename, *, schema='public'): + """Reset *typename* codec to the default implementation. + + :param typename: + Name of the data type the codec is for. + + :param schema: + Schema name of the data type the codec is for + (defaults to ``'public'``) + + .. versionadded:: 0.12.0 + """ + + typeinfo = await self._introspect_type(typename, schema) + self._protocol.get_settings().remove_python_codec( + typeinfo['oid'], typename, schema) + + # Statement cache is no longer valid due to codec changes. + self._drop_local_statement_cache() + + async def set_builtin_type_codec(self, typename, *, + schema='public', codec_name, + format=None): + """Set a builtin codec for the specified scalar data type. + + This method has two uses. The first is to register a builtin + codec for an extension type without a stable OID, such as 'hstore'. + The second use is to declare that an extension type or a + user-defined type is wire-compatible with a certain builtin + data type and should be exchanged as such. + + :param typename: + Name of the data type the codec is for. + + :param schema: + Schema name of the data type the codec is for + (defaults to ``'public'``). + + :param codec_name: + The name of the builtin codec to use for the type. + This should be either the name of a known core type + (such as ``"int"``), or the name of a supported extension + type. Currently, the only supported extension type is + ``"pg_contrib.hstore"``. + + :param format: + If *format* is ``None`` (the default), all formats supported + by the target codec are declared to be supported for *typename*. + If *format* is ``'text'`` or ``'binary'``, then only the + specified format is declared to be supported for *typename*. + + .. versionchanged:: 0.18.0 + The *codec_name* argument can be the name of any known + core data type. Added the *format* keyword argument. + """ + self._check_open() + typeinfo = await self._introspect_type(typename, schema) + if not introspection.is_scalar_type(typeinfo): + raise exceptions.InterfaceError( + 'cannot alias non-scalar type {}.{}'.format( + schema, typename)) + + oid = typeinfo['oid'] + + self._protocol.get_settings().set_builtin_type_codec( + oid, typename, schema, 'scalar', codec_name, format) + + # Statement cache is no longer valid due to codec changes. + self._drop_local_statement_cache() + + def is_closed(self): + """Return ``True`` if the connection is closed, ``False`` otherwise. + + :return bool: ``True`` if the connection is closed, ``False`` + otherwise. + """ + return self._aborted or not self._protocol.is_connected() + + async def close(self, *, timeout=None): + """Close the connection gracefully. + + :param float timeout: + Optional timeout value in seconds. + + .. versionchanged:: 0.14.0 + Added the *timeout* parameter. + """ + try: + if not self.is_closed(): + await self._protocol.close(timeout) + except (Exception, asyncio.CancelledError): + # If we fail to close gracefully, abort the connection. + self._abort() + raise + finally: + self._cleanup() + + def terminate(self): + """Terminate the connection without waiting for pending data.""" + if not self.is_closed(): + self._abort() + self._cleanup() + + async def reset(self, *, timeout=None): + self._check_open() + self._listeners.clear() + self._log_listeners.clear() + reset_query = self._get_reset_query() + + if self._protocol.is_in_transaction() or self._top_xact is not None: + if self._top_xact is None or not self._top_xact._managed: + # Managed transactions are guaranteed to __aexit__ + # correctly. + self._loop.call_exception_handler({ + 'message': 'Resetting connection with an ' + 'active transaction {!r}'.format(self) + }) + + self._top_xact = None + reset_query = 'ROLLBACK;\n' + reset_query + + if reset_query: + await self.execute(reset_query, timeout=timeout) + + def _abort(self): + # Put the connection into the aborted state. + self._aborted = True + self._protocol.abort() + self._protocol = None + + def _cleanup(self): + self._call_termination_listeners() + # Free the resources associated with this connection. + # This must be called when a connection is terminated. + + if self._proxy is not None: + # Connection is a member of a pool, so let the pool + # know that this connection is dead. + self._proxy._holder._release_on_close() + + self._mark_stmts_as_closed() + self._listeners.clear() + self._log_listeners.clear() + self._query_loggers.clear() + self._clean_tasks() + + def _clean_tasks(self): + # Wrap-up any remaining tasks associated with this connection. + if self._cancellations: + for fut in self._cancellations: + if not fut.done(): + fut.cancel() + self._cancellations.clear() + + def _check_open(self): + if self.is_closed(): + raise exceptions.InterfaceError('connection is closed') + + def _get_unique_id(self, prefix): + global _uid + _uid += 1 + return '__asyncpg_{}_{:x}__'.format(prefix, _uid) + + def _mark_stmts_as_closed(self): + for stmt in self._stmt_cache.iter_statements(): + stmt.mark_closed() + + for stmt in self._stmts_to_close: + stmt.mark_closed() + + self._stmt_cache.clear() + self._stmts_to_close.clear() + + def _maybe_gc_stmt(self, stmt): + if ( + stmt.refs == 0 + and stmt.name + and not self._stmt_cache.has( + (stmt.query, stmt.record_class, stmt.ignore_custom_codec) + ) + ): + # If low-level `stmt` isn't referenced from any high-level + # `PreparedStatement` object and is not in the `_stmt_cache`: + # + # * mark it as closed, which will make it non-usable + # for any `PreparedStatement` or for methods like + # `Connection.fetch()`. + # + # * schedule it to be formally closed on the server. + stmt.mark_closed() + self._stmts_to_close.add(stmt) + + async def _cleanup_stmts(self): + # Called whenever we create a new prepared statement in + # `Connection._get_statement()` and `_stmts_to_close` is + # not empty. + to_close = self._stmts_to_close + self._stmts_to_close = set() + for stmt in to_close: + # It is imperative that statements are cleaned properly, + # so we ignore the timeout. + await self._protocol.close_statement(stmt, protocol.NO_TIMEOUT) + + async def _cancel(self, waiter): + try: + # Open new connection to the server + await connect_utils._cancel( + loop=self._loop, addr=self._addr, params=self._params, + backend_pid=self._protocol.backend_pid, + backend_secret=self._protocol.backend_secret) + except ConnectionResetError as ex: + # On some systems Postgres will reset the connection + # after processing the cancellation command. + if not waiter.done(): + waiter.set_exception(ex) + except asyncio.CancelledError: + # There are two scenarios in which the cancellation + # itself will be cancelled: 1) the connection is being closed, + # 2) the event loop is being shut down. + # In either case we do not care about the propagation of + # the CancelledError, and don't want the loop to warn about + # an unretrieved exception. + pass + except (Exception, asyncio.CancelledError) as ex: + if not waiter.done(): + waiter.set_exception(ex) + finally: + self._cancellations.discard( + asyncio.current_task(self._loop)) + if not waiter.done(): + waiter.set_result(None) + + def _cancel_current_command(self, waiter): + self._cancellations.add(self._loop.create_task(self._cancel(waiter))) + + def _process_log_message(self, fields, last_query): + if not self._log_listeners: + return + + message = exceptions.PostgresLogMessage.new(fields, query=last_query) + + con_ref = self._unwrap() + for cb in self._log_listeners: + if cb.is_async: + self._loop.create_task(cb.cb(con_ref, message)) + else: + self._loop.call_soon(cb.cb, con_ref, message) + + def _call_termination_listeners(self): + if not self._termination_listeners: + return + + con_ref = self._unwrap() + for cb in self._termination_listeners: + if cb.is_async: + self._loop.create_task(cb.cb(con_ref)) + else: + self._loop.call_soon(cb.cb, con_ref) + + self._termination_listeners.clear() + + def _process_notification(self, pid, channel, payload): + if channel not in self._listeners: + return + + con_ref = self._unwrap() + for cb in self._listeners[channel]: + if cb.is_async: + self._loop.create_task(cb.cb(con_ref, pid, channel, payload)) + else: + self._loop.call_soon(cb.cb, con_ref, pid, channel, payload) + + def _unwrap(self): + if self._proxy is None: + con_ref = self + else: + # `_proxy` is not None when the connection is a member + # of a connection pool. Which means that the user is working + # with a `PoolConnectionProxy` instance, and expects to see it + # (and not the actual Connection) in their event callbacks. + con_ref = self._proxy + return con_ref + + def _get_reset_query(self): + if self._reset_query is not None: + return self._reset_query + + caps = self._server_caps + + _reset_query = [] + if caps.advisory_locks: + _reset_query.append('SELECT pg_advisory_unlock_all();') + if caps.sql_close_all: + _reset_query.append('CLOSE ALL;') + if caps.notifications and caps.plpgsql: + _reset_query.append('UNLISTEN *;') + if caps.sql_reset: + _reset_query.append('RESET ALL;') + + _reset_query = '\n'.join(_reset_query) + self._reset_query = _reset_query + + return _reset_query + + def _set_proxy(self, proxy): + if self._proxy is not None and proxy is not None: + # Should not happen unless there is a bug in `Pool`. + raise exceptions.InterfaceError( + 'internal asyncpg error: connection is already proxied') + + self._proxy = proxy + + def _check_listeners(self, listeners, listener_type): + if listeners: + count = len(listeners) + + w = exceptions.InterfaceWarning( + '{conn!r} is being released to the pool but has {c} active ' + '{type} listener{s}'.format( + conn=self, c=count, type=listener_type, + s='s' if count > 1 else '')) + + warnings.warn(w) + + def _on_release(self, stacklevel=1): + # Invalidate external references to the connection. + self._pool_release_ctr += 1 + # Called when the connection is about to be released to the pool. + # Let's check that the user has not left any listeners on it. + self._check_listeners( + list(itertools.chain.from_iterable(self._listeners.values())), + 'notification') + self._check_listeners( + self._log_listeners, 'log') + + def _drop_local_statement_cache(self): + self._stmt_cache.clear() + + def _drop_global_statement_cache(self): + if self._proxy is not None: + # This connection is a member of a pool, so we delegate + # the cache drop to the pool. + pool = self._proxy._holder._pool + pool._drop_statement_cache() + else: + self._drop_local_statement_cache() + + def _drop_local_type_cache(self): + self._protocol.get_settings().clear_type_cache() + + def _drop_global_type_cache(self): + if self._proxy is not None: + # This connection is a member of a pool, so we delegate + # the cache drop to the pool. + pool = self._proxy._holder._pool + pool._drop_type_cache() + else: + self._drop_local_type_cache() + + async def reload_schema_state(self): + """Indicate that the database schema information must be reloaded. + + For performance reasons, asyncpg caches certain aspects of the + database schema, such as the layout of composite types. Consequently, + when the database schema changes, and asyncpg is not able to + gracefully recover from an error caused by outdated schema + assumptions, an :exc:`~asyncpg.exceptions.OutdatedSchemaCacheError` + is raised. To prevent the exception, this method may be used to inform + asyncpg that the database schema has changed. + + Example: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> async def change_type(con): + ... result = await con.fetch('SELECT id, info FROM tbl') + ... # Change composite's attribute type "int"=>"text" + ... await con.execute('ALTER TYPE custom DROP ATTRIBUTE y') + ... await con.execute('ALTER TYPE custom ADD ATTRIBUTE y text') + ... await con.reload_schema_state() + ... for id_, info in result: + ... new = (info['x'], str(info['y'])) + ... await con.execute( + ... 'UPDATE tbl SET info=$2 WHERE id=$1', id_, new) + ... + >>> async def run(): + ... # Initial schema: + ... # CREATE TYPE custom AS (x int, y int); + ... # CREATE TABLE tbl(id int, info custom); + ... con = await asyncpg.connect(user='postgres') + ... async with con.transaction(): + ... # Prevent concurrent changes in the table + ... await con.execute('LOCK TABLE tbl') + ... await change_type(con) + ... + >>> asyncio.get_event_loop().run_until_complete(run()) + + .. versionadded:: 0.14.0 + """ + self._drop_global_type_cache() + self._drop_global_statement_cache() + + async def _execute( + self, + query, + args, + limit, + timeout, + *, + return_status=False, + ignore_custom_codec=False, + record_class=None + ): + with self._stmt_exclusive_section: + result, _ = await self.__execute( + query, + args, + limit, + timeout, + return_status=return_status, + record_class=record_class, + ignore_custom_codec=ignore_custom_codec, + ) + return result + + @contextlib.contextmanager + def query_logger(self, callback): + """Context manager that adds `callback` to the list of query loggers, + and removes it upon exit. + + :param callable callback: + A callable or a coroutine function receiving one argument: + **record**: a LoggedQuery containing `query`, `args`, `timeout`, + `elapsed`, `exception`, `conn_addr`, and + `conn_params`. + + Example: + + .. code-block:: pycon + + >>> class QuerySaver: + def __init__(self): + self.queries = [] + def __call__(self, record): + self.queries.append(record.query) + >>> with con.query_logger(QuerySaver()): + >>> await con.execute("SELECT 1") + >>> print(log.queries) + ['SELECT 1'] + + .. versionadded:: 0.29.0 + """ + self.add_query_logger(callback) + yield + self.remove_query_logger(callback) + + @contextlib.contextmanager + def _time_and_log(self, query, args, timeout): + start = time.monotonic() + exception = None + try: + yield + except BaseException as ex: + exception = ex + raise + finally: + elapsed = time.monotonic() - start + record = LoggedQuery( + query=query, + args=args, + timeout=timeout, + elapsed=elapsed, + exception=exception, + conn_addr=self._addr, + conn_params=self._params, + ) + for cb in self._query_loggers: + if cb.is_async: + self._loop.create_task(cb.cb(record)) + else: + self._loop.call_soon(cb.cb, record) + + async def __execute( + self, + query, + args, + limit, + timeout, + *, + return_status=False, + ignore_custom_codec=False, + record_class=None + ): + executor = lambda stmt, timeout: self._protocol.bind_execute( + state=stmt, + args=args, + portal_name='', + limit=limit, + return_extra=return_status, + timeout=timeout, + ) + timeout = self._protocol._get_timeout(timeout) + if self._query_loggers: + with self._time_and_log(query, args, timeout): + result, stmt = await self._do_execute( + query, + executor, + timeout, + record_class=record_class, + ignore_custom_codec=ignore_custom_codec, + ) + else: + result, stmt = await self._do_execute( + query, + executor, + timeout, + record_class=record_class, + ignore_custom_codec=ignore_custom_codec, + ) + return result, stmt + + async def _executemany(self, query, args, timeout): + executor = lambda stmt, timeout: self._protocol.bind_execute_many( + state=stmt, + args=args, + portal_name='', + timeout=timeout, + ) + timeout = self._protocol._get_timeout(timeout) + with self._stmt_exclusive_section: + with self._time_and_log(query, args, timeout): + result, _ = await self._do_execute(query, executor, timeout) + return result + + async def _do_execute( + self, + query, + executor, + timeout, + retry=True, + *, + ignore_custom_codec=False, + record_class=None + ): + if timeout is None: + stmt = await self._get_statement( + query, + None, + record_class=record_class, + ignore_custom_codec=ignore_custom_codec, + ) + else: + before = time.monotonic() + stmt = await self._get_statement( + query, + timeout, + record_class=record_class, + ignore_custom_codec=ignore_custom_codec, + ) + after = time.monotonic() + timeout -= after - before + before = after + + try: + if timeout is None: + result = await executor(stmt, None) + else: + try: + result = await executor(stmt, timeout) + finally: + after = time.monotonic() + timeout -= after - before + + except exceptions.OutdatedSchemaCacheError: + # This exception is raised when we detect a difference between + # cached type's info and incoming tuple from the DB (when a type is + # changed by the ALTER TYPE). + # It is not possible to recover (the statement is already done at + # the server's side), the only way is to drop our caches and + # reraise the exception to the caller. + await self.reload_schema_state() + raise + except exceptions.InvalidCachedStatementError: + # PostgreSQL will raise an exception when it detects + # that the result type of the query has changed from + # when the statement was prepared. This may happen, + # for example, after an ALTER TABLE or SET search_path. + # + # When this happens, and there is no transaction running, + # we can simply re-prepare the statement and try once + # again. We deliberately retry only once as this is + # supposed to be a rare occurrence. + # + # If the transaction _is_ running, this error will put it + # into an error state, and we have no choice but to + # re-raise the exception. + # + # In either case we clear the statement cache for this + # connection and all other connections of the pool this + # connection belongs to (if any). + # + # See https://github.com/MagicStack/asyncpg/issues/72 + # and https://github.com/MagicStack/asyncpg/issues/76 + # for discussion. + # + self._drop_global_statement_cache() + if self._protocol.is_in_transaction() or not retry: + raise + else: + return await self._do_execute( + query, executor, timeout, retry=False) + + return result, stmt + + +async def connect(dsn=None, *, + host=None, port=None, + user=None, password=None, passfile=None, + database=None, + loop=None, + timeout=60, + statement_cache_size=100, + max_cached_statement_lifetime=300, + max_cacheable_statement_size=1024 * 15, + command_timeout=None, + ssl=None, + direct_tls=False, + connection_class=Connection, + record_class=protocol.Record, + server_settings=None, + target_session_attrs=None): + r"""A coroutine to establish a connection to a PostgreSQL server. + + The connection parameters may be specified either as a connection + URI in *dsn*, or as specific keyword arguments, or both. + If both *dsn* and keyword arguments are specified, the latter + override the corresponding values parsed from the connection URI. + The default values for the majority of arguments can be specified + using `environment variables `_. + + Returns a new :class:`~asyncpg.connection.Connection` object. + + :param dsn: + Connection arguments specified using as a single string in the + `libpq connection URI format`_: + ``postgres://user:password@host:port/database?option=value``. + The following options are recognized by asyncpg: ``host``, + ``port``, ``user``, ``database`` (or ``dbname``), ``password``, + ``passfile``, ``sslmode``, ``sslcert``, ``sslkey``, ``sslrootcert``, + and ``sslcrl``. Unlike libpq, asyncpg will treat unrecognized + options as `server settings`_ to be used for the connection. + + .. note:: + + The URI must be *valid*, which means that all components must + be properly quoted with :py:func:`urllib.parse.quote`, and + any literal IPv6 addresses must be enclosed in square brackets. + For example: + + .. code-block:: text + + postgres://dbuser@[fe80::1ff:fe23:4567:890a%25eth0]/dbname + + :param host: + Database host address as one of the following: + + - an IP address or a domain name; + - an absolute path to the directory containing the database + server Unix-domain socket (not supported on Windows); + - a sequence of any of the above, in which case the addresses + will be tried in order, and the first successful connection + will be returned. + + If not specified, asyncpg will try the following, in order: + + - host address(es) parsed from the *dsn* argument, + - the value of the ``PGHOST`` environment variable, + - on Unix, common directories used for PostgreSQL Unix-domain + sockets: ``"/run/postgresql"``, ``"/var/run/postgresl"``, + ``"/var/pgsql_socket"``, ``"/private/tmp"``, and ``"/tmp"``, + - ``"localhost"``. + + :param port: + Port number to connect to at the server host + (or Unix-domain socket file extension). If multiple host + addresses were specified, this parameter may specify a + sequence of port numbers of the same length as the host sequence, + or it may specify a single port number to be used for all host + addresses. + + If not specified, the value parsed from the *dsn* argument is used, + or the value of the ``PGPORT`` environment variable, or ``5432`` if + neither is specified. + + :param user: + The name of the database role used for authentication. + + If not specified, the value parsed from the *dsn* argument is used, + or the value of the ``PGUSER`` environment variable, or the + operating system name of the user running the application. + + :param database: + The name of the database to connect to. + + If not specified, the value parsed from the *dsn* argument is used, + or the value of the ``PGDATABASE`` environment variable, or the + computed value of the *user* argument. + + :param password: + Password to be used for authentication, if the server requires + one. If not specified, the value parsed from the *dsn* argument + is used, or the value of the ``PGPASSWORD`` environment variable. + Note that the use of the environment variable is discouraged as + other users and applications may be able to read it without needing + specific privileges. It is recommended to use *passfile* instead. + + Password may be either a string, or a callable that returns a string. + If a callable is provided, it will be called each time a new connection + is established. + + :param passfile: + The name of the file used to store passwords + (defaults to ``~/.pgpass``, or ``%APPDATA%\postgresql\pgpass.conf`` + on Windows). + + :param loop: + An asyncio event loop instance. If ``None``, the default + event loop will be used. + + :param float timeout: + Connection timeout in seconds. + + :param int statement_cache_size: + The size of prepared statement LRU cache. Pass ``0`` to + disable the cache. + + :param int max_cached_statement_lifetime: + The maximum time in seconds a prepared statement will stay + in the cache. Pass ``0`` to allow statements be cached + indefinitely. + + :param int max_cacheable_statement_size: + The maximum size of a statement that can be cached (15KiB by + default). Pass ``0`` to allow all statements to be cached + regardless of their size. + + :param float command_timeout: + The default timeout for operations on this connection + (the default is ``None``: no timeout). + + :param ssl: + Pass ``True`` or an `ssl.SSLContext `_ instance to + require an SSL connection. If ``True``, a default SSL context + returned by `ssl.create_default_context() `_ + will be used. The value can also be one of the following strings: + + - ``'disable'`` - SSL is disabled (equivalent to ``False``) + - ``'prefer'`` - try SSL first, fallback to non-SSL connection + if SSL connection fails + - ``'allow'`` - try without SSL first, then retry with SSL if the first + attempt fails. + - ``'require'`` - only try an SSL connection. Certificate + verification errors are ignored + - ``'verify-ca'`` - only try an SSL connection, and verify + that the server certificate is issued by a trusted certificate + authority (CA) + - ``'verify-full'`` - only try an SSL connection, verify + that the server certificate is issued by a trusted CA and + that the requested server host name matches that in the + certificate. + + The default is ``'prefer'``: try an SSL connection and fallback to + non-SSL connection if that fails. + + .. note:: + + *ssl* is ignored for Unix domain socket communication. + + Example of programmatic SSL context configuration that is equivalent + to ``sslmode=verify-full&sslcert=..&sslkey=..&sslrootcert=..``: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> import ssl + >>> async def main(): + ... # Load CA bundle for server certificate verification, + ... # equivalent to sslrootcert= in DSN. + ... sslctx = ssl.create_default_context( + ... ssl.Purpose.SERVER_AUTH, + ... cafile="path/to/ca_bundle.pem") + ... # If True, equivalent to sslmode=verify-full, if False: + ... # sslmode=verify-ca. + ... sslctx.check_hostname = True + ... # Load client certificate and private key for client + ... # authentication, equivalent to sslcert= and sslkey= in + ... # DSN. + ... sslctx.load_cert_chain( + ... "path/to/client.cert", + ... keyfile="path/to/client.key", + ... ) + ... con = await asyncpg.connect(user='postgres', ssl=sslctx) + ... await con.close() + >>> asyncio.run(main()) + + Example of programmatic SSL context configuration that is equivalent + to ``sslmode=require`` (no server certificate or host verification): + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> import ssl + >>> async def main(): + ... sslctx = ssl.create_default_context( + ... ssl.Purpose.SERVER_AUTH) + ... sslctx.check_hostname = False + ... sslctx.verify_mode = ssl.CERT_NONE + ... con = await asyncpg.connect(user='postgres', ssl=sslctx) + ... await con.close() + >>> asyncio.run(main()) + + :param bool direct_tls: + Pass ``True`` to skip PostgreSQL STARTTLS mode and perform a direct + SSL connection. Must be used alongside ``ssl`` param. + + :param dict server_settings: + An optional dict of server runtime parameters. Refer to + PostgreSQL documentation for + a `list of supported options `_. + + :param type connection_class: + Class of the returned connection object. Must be a subclass of + :class:`~asyncpg.connection.Connection`. + + :param type record_class: + If specified, the class to use for records returned by queries on + this connection object. Must be a subclass of + :class:`~asyncpg.Record`. + + :param SessionAttribute target_session_attrs: + If specified, check that the host has the correct attribute. + Can be one of: + + - ``"any"`` - the first successfully connected host + - ``"primary"`` - the host must NOT be in hot standby mode + - ``"standby"`` - the host must be in hot standby mode + - ``"read-write"`` - the host must allow writes + - ``"read-only"`` - the host most NOT allow writes + - ``"prefer-standby"`` - first try to find a standby host, but if + none of the listed hosts is a standby server, + return any of them. + + If not specified, the value parsed from the *dsn* argument is used, + or the value of the ``PGTARGETSESSIONATTRS`` environment variable, + or ``"any"`` if neither is specified. + + :return: A :class:`~asyncpg.connection.Connection` instance. + + Example: + + .. code-block:: pycon + + >>> import asyncpg + >>> import asyncio + >>> async def run(): + ... con = await asyncpg.connect(user='postgres') + ... types = await con.fetch('SELECT * FROM pg_type') + ... print(types) + ... + >>> asyncio.get_event_loop().run_until_complete(run()) + [= 0 + self._max_size = new_size + self._maybe_cleanup() + + def get_max_lifetime(self): + return self._max_lifetime + + def set_max_lifetime(self, new_lifetime): + assert new_lifetime >= 0 + self._max_lifetime = new_lifetime + for entry in self._entries.values(): + # For every entry cancel the existing callback + # and setup a new one if necessary. + self._set_entry_timeout(entry) + + def get(self, query, *, promote=True): + if not self._max_size: + # The cache is disabled. + return + + entry = self._entries.get(query) # type: _StatementCacheEntry + if entry is None: + return + + if entry._statement.closed: + # Happens in unittests when we call `stmt._state.mark_closed()` + # manually or when a prepared statement closes itself on type + # cache error. + self._entries.pop(query) + self._clear_entry_callback(entry) + return + + if promote: + # `promote` is `False` when `get()` is called by `has()`. + self._entries.move_to_end(query, last=True) + + return entry._statement + + def has(self, query): + return self.get(query, promote=False) is not None + + def put(self, query, statement): + if not self._max_size: + # The cache is disabled. + return + + self._entries[query] = self._new_entry(query, statement) + + # Check if the cache is bigger than max_size and trim it + # if necessary. + self._maybe_cleanup() + + def iter_statements(self): + return (e._statement for e in self._entries.values()) + + def clear(self): + # Store entries for later. + entries = tuple(self._entries.values()) + + # Clear the entries dict. + self._entries.clear() + + # Make sure that we cancel all scheduled callbacks + # and call on_remove callback for each entry. + for entry in entries: + self._clear_entry_callback(entry) + self._on_remove(entry._statement) + + def _set_entry_timeout(self, entry): + # Clear the existing timeout. + self._clear_entry_callback(entry) + + # Set the new timeout if it's not 0. + if self._max_lifetime: + entry._cleanup_cb = self._loop.call_later( + self._max_lifetime, self._on_entry_expired, entry) + + def _new_entry(self, query, statement): + entry = _StatementCacheEntry(self, query, statement) + self._set_entry_timeout(entry) + return entry + + def _on_entry_expired(self, entry): + # `call_later` callback, called when an entry stayed longer + # than `self._max_lifetime`. + if self._entries.get(entry._query) is entry: + self._entries.pop(entry._query) + self._on_remove(entry._statement) + + def _clear_entry_callback(self, entry): + if entry._cleanup_cb is not None: + entry._cleanup_cb.cancel() + + def _maybe_cleanup(self): + # Delete cache entries until the size of the cache is `max_size`. + while len(self._entries) > self._max_size: + old_query, old_entry = self._entries.popitem(last=False) + self._clear_entry_callback(old_entry) + + # Let the connection know that the statement was removed + # from the cache. + self._on_remove(old_entry._statement) + + +class _Callback(typing.NamedTuple): + + cb: typing.Callable[..., None] + is_async: bool + + @classmethod + def from_callable(cls, cb: typing.Callable[..., None]) -> '_Callback': + if inspect.iscoroutinefunction(cb): + is_async = True + elif callable(cb): + is_async = False + else: + raise exceptions.InterfaceError( + 'expected a callable or an `async def` function,' + 'got {!r}'.format(cb) + ) + + return cls(cb, is_async) + + +class _Atomic: + __slots__ = ('_acquired',) + + def __init__(self): + self._acquired = 0 + + def __enter__(self): + if self._acquired: + raise exceptions.InterfaceError( + 'cannot perform operation: another operation is in progress') + self._acquired = 1 + + def __exit__(self, t, e, tb): + self._acquired = 0 + + +class _ConnectionProxy: + # Base class to enable `isinstance(Connection)` check. + __slots__ = () + + +LoggedQuery = collections.namedtuple( + 'LoggedQuery', + ['query', 'args', 'timeout', 'elapsed', 'exception', 'conn_addr', + 'conn_params']) +LoggedQuery.__doc__ = 'Log record of an executed query.' + + +ServerCapabilities = collections.namedtuple( + 'ServerCapabilities', + ['advisory_locks', 'notifications', 'plpgsql', 'sql_reset', + 'sql_close_all', 'sql_copy_from_where', 'jit']) +ServerCapabilities.__doc__ = 'PostgreSQL server capabilities.' + + +def _detect_server_capabilities(server_version, connection_settings): + if hasattr(connection_settings, 'padb_revision'): + # Amazon Redshift detected. + advisory_locks = False + notifications = False + plpgsql = False + sql_reset = True + sql_close_all = False + jit = False + sql_copy_from_where = False + elif hasattr(connection_settings, 'crdb_version'): + # CockroachDB detected. + advisory_locks = False + notifications = False + plpgsql = False + sql_reset = False + sql_close_all = False + jit = False + sql_copy_from_where = False + elif hasattr(connection_settings, 'crate_version'): + # CrateDB detected. + advisory_locks = False + notifications = False + plpgsql = False + sql_reset = False + sql_close_all = False + jit = False + sql_copy_from_where = False + else: + # Standard PostgreSQL server assumed. + advisory_locks = True + notifications = True + plpgsql = True + sql_reset = True + sql_close_all = True + jit = server_version >= (11, 0) + sql_copy_from_where = server_version.major >= 12 + + return ServerCapabilities( + advisory_locks=advisory_locks, + notifications=notifications, + plpgsql=plpgsql, + sql_reset=sql_reset, + sql_close_all=sql_close_all, + sql_copy_from_where=sql_copy_from_where, + jit=jit, + ) + + +def _extract_stack(limit=10): + """Replacement for traceback.extract_stack() that only does the + necessary work for asyncio debug mode. + """ + frame = sys._getframe().f_back + try: + stack = traceback.StackSummary.extract( + traceback.walk_stack(frame), lookup_lines=False) + finally: + del frame + + apg_path = asyncpg.__path__[0] + i = 0 + while i < len(stack) and stack[i][0].startswith(apg_path): + i += 1 + stack = stack[i:i + limit] + + stack.reverse() + return ''.join(traceback.format_list(stack)) + + +def _check_record_class(record_class): + if record_class is protocol.Record: + pass + elif ( + isinstance(record_class, type) + and issubclass(record_class, protocol.Record) + ): + if ( + record_class.__new__ is not object.__new__ + or record_class.__init__ is not object.__init__ + ): + raise exceptions.InterfaceError( + 'record_class must not redefine __new__ or __init__' + ) + else: + raise exceptions.InterfaceError( + 'record_class is expected to be a subclass of ' + 'asyncpg.Record, got {!r}'.format(record_class) + ) + + +def _weak_maybe_gc_stmt(weak_ref, stmt): + self = weak_ref() + if self is not None: + self._maybe_gc_stmt(stmt) + + +_uid = 0 diff --git a/env/Lib/site-packages/asyncpg/connresource.py b/env/Lib/site-packages/asyncpg/connresource.py new file mode 100644 index 0000000..3b0c1d3 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/connresource.py @@ -0,0 +1,44 @@ + +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import functools + +from . import exceptions + + +def guarded(meth): + """A decorator to add a sanity check to ConnectionResource methods.""" + + @functools.wraps(meth) + def _check(self, *args, **kwargs): + self._check_conn_validity(meth.__name__) + return meth(self, *args, **kwargs) + + return _check + + +class ConnectionResource: + __slots__ = ('_connection', '_con_release_ctr') + + def __init__(self, connection): + self._connection = connection + self._con_release_ctr = connection._pool_release_ctr + + def _check_conn_validity(self, meth_name): + con_release_ctr = self._connection._pool_release_ctr + if con_release_ctr != self._con_release_ctr: + raise exceptions.InterfaceError( + 'cannot call {}.{}(): ' + 'the underlying connection has been released back ' + 'to the pool'.format(self.__class__.__name__, meth_name)) + + if self._connection.is_closed(): + raise exceptions.InterfaceError( + 'cannot call {}.{}(): ' + 'the underlying connection is closed'.format( + self.__class__.__name__, meth_name)) diff --git a/env/Lib/site-packages/asyncpg/cursor.py b/env/Lib/site-packages/asyncpg/cursor.py new file mode 100644 index 0000000..b4abeed --- /dev/null +++ b/env/Lib/site-packages/asyncpg/cursor.py @@ -0,0 +1,323 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import collections + +from . import connresource +from . import exceptions + + +class CursorFactory(connresource.ConnectionResource): + """A cursor interface for the results of a query. + + A cursor interface can be used to initiate efficient traversal of the + results of a large query. + """ + + __slots__ = ( + '_state', + '_args', + '_prefetch', + '_query', + '_timeout', + '_record_class', + ) + + def __init__( + self, + connection, + query, + state, + args, + prefetch, + timeout, + record_class + ): + super().__init__(connection) + self._args = args + self._prefetch = prefetch + self._query = query + self._timeout = timeout + self._state = state + self._record_class = record_class + if state is not None: + state.attach() + + @connresource.guarded + def __aiter__(self): + prefetch = 50 if self._prefetch is None else self._prefetch + return CursorIterator( + self._connection, + self._query, + self._state, + self._args, + self._record_class, + prefetch, + self._timeout, + ) + + @connresource.guarded + def __await__(self): + if self._prefetch is not None: + raise exceptions.InterfaceError( + 'prefetch argument can only be specified for iterable cursor') + cursor = Cursor( + self._connection, + self._query, + self._state, + self._args, + self._record_class, + ) + return cursor._init(self._timeout).__await__() + + def __del__(self): + if self._state is not None: + self._state.detach() + self._connection._maybe_gc_stmt(self._state) + + +class BaseCursor(connresource.ConnectionResource): + + __slots__ = ( + '_state', + '_args', + '_portal_name', + '_exhausted', + '_query', + '_record_class', + ) + + def __init__(self, connection, query, state, args, record_class): + super().__init__(connection) + self._args = args + self._state = state + if state is not None: + state.attach() + self._portal_name = None + self._exhausted = False + self._query = query + self._record_class = record_class + + def _check_ready(self): + if self._state is None: + raise exceptions.InterfaceError( + 'cursor: no associated prepared statement') + + if self._state.closed: + raise exceptions.InterfaceError( + 'cursor: the prepared statement is closed') + + if not self._connection._top_xact: + raise exceptions.NoActiveSQLTransactionError( + 'cursor cannot be created outside of a transaction') + + async def _bind_exec(self, n, timeout): + self._check_ready() + + if self._portal_name: + raise exceptions.InterfaceError( + 'cursor already has an open portal') + + con = self._connection + protocol = con._protocol + + self._portal_name = con._get_unique_id('portal') + buffer, _, self._exhausted = await protocol.bind_execute( + self._state, self._args, self._portal_name, n, True, timeout) + return buffer + + async def _bind(self, timeout): + self._check_ready() + + if self._portal_name: + raise exceptions.InterfaceError( + 'cursor already has an open portal') + + con = self._connection + protocol = con._protocol + + self._portal_name = con._get_unique_id('portal') + buffer = await protocol.bind(self._state, self._args, + self._portal_name, + timeout) + return buffer + + async def _exec(self, n, timeout): + self._check_ready() + + if not self._portal_name: + raise exceptions.InterfaceError( + 'cursor does not have an open portal') + + protocol = self._connection._protocol + buffer, _, self._exhausted = await protocol.execute( + self._state, self._portal_name, n, True, timeout) + return buffer + + async def _close_portal(self, timeout): + self._check_ready() + + if not self._portal_name: + raise exceptions.InterfaceError( + 'cursor does not have an open portal') + + protocol = self._connection._protocol + await protocol.close_portal(self._portal_name, timeout) + self._portal_name = None + + def __repr__(self): + attrs = [] + if self._exhausted: + attrs.append('exhausted') + attrs.append('') # to separate from id + + if self.__class__.__module__.startswith('asyncpg.'): + mod = 'asyncpg' + else: + mod = self.__class__.__module__ + + return '<{}.{} "{!s:.30}" {}{:#x}>'.format( + mod, self.__class__.__name__, + self._state.query, + ' '.join(attrs), id(self)) + + def __del__(self): + if self._state is not None: + self._state.detach() + self._connection._maybe_gc_stmt(self._state) + + +class CursorIterator(BaseCursor): + + __slots__ = ('_buffer', '_prefetch', '_timeout') + + def __init__( + self, + connection, + query, + state, + args, + record_class, + prefetch, + timeout + ): + super().__init__(connection, query, state, args, record_class) + + if prefetch <= 0: + raise exceptions.InterfaceError( + 'prefetch argument must be greater than zero') + + self._buffer = collections.deque() + self._prefetch = prefetch + self._timeout = timeout + + @connresource.guarded + def __aiter__(self): + return self + + @connresource.guarded + async def __anext__(self): + if self._state is None: + self._state = await self._connection._get_statement( + self._query, + self._timeout, + named=True, + record_class=self._record_class, + ) + self._state.attach() + + if not self._portal_name and not self._exhausted: + buffer = await self._bind_exec(self._prefetch, self._timeout) + self._buffer.extend(buffer) + + if not self._buffer and not self._exhausted: + buffer = await self._exec(self._prefetch, self._timeout) + self._buffer.extend(buffer) + + if self._portal_name and self._exhausted: + await self._close_portal(self._timeout) + + if self._buffer: + return self._buffer.popleft() + + raise StopAsyncIteration + + +class Cursor(BaseCursor): + """An open *portal* into the results of a query.""" + + __slots__ = () + + async def _init(self, timeout): + if self._state is None: + self._state = await self._connection._get_statement( + self._query, + timeout, + named=True, + record_class=self._record_class, + ) + self._state.attach() + self._check_ready() + await self._bind(timeout) + return self + + @connresource.guarded + async def fetch(self, n, *, timeout=None): + r"""Return the next *n* rows as a list of :class:`Record` objects. + + :param float timeout: Optional timeout value in seconds. + + :return: A list of :class:`Record` instances. + """ + self._check_ready() + if n <= 0: + raise exceptions.InterfaceError('n must be greater than zero') + if self._exhausted: + return [] + recs = await self._exec(n, timeout) + if len(recs) < n: + self._exhausted = True + return recs + + @connresource.guarded + async def fetchrow(self, *, timeout=None): + r"""Return the next row. + + :param float timeout: Optional timeout value in seconds. + + :return: A :class:`Record` instance. + """ + self._check_ready() + if self._exhausted: + return None + recs = await self._exec(1, timeout) + if len(recs) < 1: + self._exhausted = True + return None + return recs[0] + + @connresource.guarded + async def forward(self, n, *, timeout=None) -> int: + r"""Skip over the next *n* rows. + + :param float timeout: Optional timeout value in seconds. + + :return: A number of rows actually skipped over (<= *n*). + """ + self._check_ready() + if n <= 0: + raise exceptions.InterfaceError('n must be greater than zero') + + protocol = self._connection._protocol + status = await protocol.query('MOVE FORWARD {:d} {}'.format( + n, self._portal_name), timeout) + + advanced = int(status.split()[1]) + if advanced < n: + self._exhausted = True + + return advanced diff --git a/env/Lib/site-packages/asyncpg/exceptions/__init__.py b/env/Lib/site-packages/asyncpg/exceptions/__init__.py new file mode 100644 index 0000000..8c97d5a --- /dev/null +++ b/env/Lib/site-packages/asyncpg/exceptions/__init__.py @@ -0,0 +1,1198 @@ +# GENERATED FROM postgresql/src/backend/utils/errcodes.txt +# DO NOT MODIFY, use tools/generate_exceptions.py to update + +from ._base import * # NOQA +from . import _base + + +class PostgresWarning(_base.PostgresLogMessage, Warning): + sqlstate = '01000' + + +class DynamicResultSetsReturned(PostgresWarning): + sqlstate = '0100C' + + +class ImplicitZeroBitPadding(PostgresWarning): + sqlstate = '01008' + + +class NullValueEliminatedInSetFunction(PostgresWarning): + sqlstate = '01003' + + +class PrivilegeNotGranted(PostgresWarning): + sqlstate = '01007' + + +class PrivilegeNotRevoked(PostgresWarning): + sqlstate = '01006' + + +class StringDataRightTruncation(PostgresWarning): + sqlstate = '01004' + + +class DeprecatedFeature(PostgresWarning): + sqlstate = '01P01' + + +class NoData(PostgresWarning): + sqlstate = '02000' + + +class NoAdditionalDynamicResultSetsReturned(NoData): + sqlstate = '02001' + + +class SQLStatementNotYetCompleteError(_base.PostgresError): + sqlstate = '03000' + + +class PostgresConnectionError(_base.PostgresError): + sqlstate = '08000' + + +class ConnectionDoesNotExistError(PostgresConnectionError): + sqlstate = '08003' + + +class ConnectionFailureError(PostgresConnectionError): + sqlstate = '08006' + + +class ClientCannotConnectError(PostgresConnectionError): + sqlstate = '08001' + + +class ConnectionRejectionError(PostgresConnectionError): + sqlstate = '08004' + + +class TransactionResolutionUnknownError(PostgresConnectionError): + sqlstate = '08007' + + +class ProtocolViolationError(PostgresConnectionError): + sqlstate = '08P01' + + +class TriggeredActionError(_base.PostgresError): + sqlstate = '09000' + + +class FeatureNotSupportedError(_base.PostgresError): + sqlstate = '0A000' + + +class InvalidCachedStatementError(FeatureNotSupportedError): + pass + + +class InvalidTransactionInitiationError(_base.PostgresError): + sqlstate = '0B000' + + +class LocatorError(_base.PostgresError): + sqlstate = '0F000' + + +class InvalidLocatorSpecificationError(LocatorError): + sqlstate = '0F001' + + +class InvalidGrantorError(_base.PostgresError): + sqlstate = '0L000' + + +class InvalidGrantOperationError(InvalidGrantorError): + sqlstate = '0LP01' + + +class InvalidRoleSpecificationError(_base.PostgresError): + sqlstate = '0P000' + + +class DiagnosticsError(_base.PostgresError): + sqlstate = '0Z000' + + +class StackedDiagnosticsAccessedWithoutActiveHandlerError(DiagnosticsError): + sqlstate = '0Z002' + + +class CaseNotFoundError(_base.PostgresError): + sqlstate = '20000' + + +class CardinalityViolationError(_base.PostgresError): + sqlstate = '21000' + + +class DataError(_base.PostgresError): + sqlstate = '22000' + + +class ArraySubscriptError(DataError): + sqlstate = '2202E' + + +class CharacterNotInRepertoireError(DataError): + sqlstate = '22021' + + +class DatetimeFieldOverflowError(DataError): + sqlstate = '22008' + + +class DivisionByZeroError(DataError): + sqlstate = '22012' + + +class ErrorInAssignmentError(DataError): + sqlstate = '22005' + + +class EscapeCharacterConflictError(DataError): + sqlstate = '2200B' + + +class IndicatorOverflowError(DataError): + sqlstate = '22022' + + +class IntervalFieldOverflowError(DataError): + sqlstate = '22015' + + +class InvalidArgumentForLogarithmError(DataError): + sqlstate = '2201E' + + +class InvalidArgumentForNtileFunctionError(DataError): + sqlstate = '22014' + + +class InvalidArgumentForNthValueFunctionError(DataError): + sqlstate = '22016' + + +class InvalidArgumentForPowerFunctionError(DataError): + sqlstate = '2201F' + + +class InvalidArgumentForWidthBucketFunctionError(DataError): + sqlstate = '2201G' + + +class InvalidCharacterValueForCastError(DataError): + sqlstate = '22018' + + +class InvalidDatetimeFormatError(DataError): + sqlstate = '22007' + + +class InvalidEscapeCharacterError(DataError): + sqlstate = '22019' + + +class InvalidEscapeOctetError(DataError): + sqlstate = '2200D' + + +class InvalidEscapeSequenceError(DataError): + sqlstate = '22025' + + +class NonstandardUseOfEscapeCharacterError(DataError): + sqlstate = '22P06' + + +class InvalidIndicatorParameterValueError(DataError): + sqlstate = '22010' + + +class InvalidParameterValueError(DataError): + sqlstate = '22023' + + +class InvalidPrecedingOrFollowingSizeError(DataError): + sqlstate = '22013' + + +class InvalidRegularExpressionError(DataError): + sqlstate = '2201B' + + +class InvalidRowCountInLimitClauseError(DataError): + sqlstate = '2201W' + + +class InvalidRowCountInResultOffsetClauseError(DataError): + sqlstate = '2201X' + + +class InvalidTablesampleArgumentError(DataError): + sqlstate = '2202H' + + +class InvalidTablesampleRepeatError(DataError): + sqlstate = '2202G' + + +class InvalidTimeZoneDisplacementValueError(DataError): + sqlstate = '22009' + + +class InvalidUseOfEscapeCharacterError(DataError): + sqlstate = '2200C' + + +class MostSpecificTypeMismatchError(DataError): + sqlstate = '2200G' + + +class NullValueNotAllowedError(DataError): + sqlstate = '22004' + + +class NullValueNoIndicatorParameterError(DataError): + sqlstate = '22002' + + +class NumericValueOutOfRangeError(DataError): + sqlstate = '22003' + + +class SequenceGeneratorLimitExceededError(DataError): + sqlstate = '2200H' + + +class StringDataLengthMismatchError(DataError): + sqlstate = '22026' + + +class StringDataRightTruncationError(DataError): + sqlstate = '22001' + + +class SubstringError(DataError): + sqlstate = '22011' + + +class TrimError(DataError): + sqlstate = '22027' + + +class UnterminatedCStringError(DataError): + sqlstate = '22024' + + +class ZeroLengthCharacterStringError(DataError): + sqlstate = '2200F' + + +class PostgresFloatingPointError(DataError): + sqlstate = '22P01' + + +class InvalidTextRepresentationError(DataError): + sqlstate = '22P02' + + +class InvalidBinaryRepresentationError(DataError): + sqlstate = '22P03' + + +class BadCopyFileFormatError(DataError): + sqlstate = '22P04' + + +class UntranslatableCharacterError(DataError): + sqlstate = '22P05' + + +class NotAnXmlDocumentError(DataError): + sqlstate = '2200L' + + +class InvalidXmlDocumentError(DataError): + sqlstate = '2200M' + + +class InvalidXmlContentError(DataError): + sqlstate = '2200N' + + +class InvalidXmlCommentError(DataError): + sqlstate = '2200S' + + +class InvalidXmlProcessingInstructionError(DataError): + sqlstate = '2200T' + + +class DuplicateJsonObjectKeyValueError(DataError): + sqlstate = '22030' + + +class InvalidArgumentForSQLJsonDatetimeFunctionError(DataError): + sqlstate = '22031' + + +class InvalidJsonTextError(DataError): + sqlstate = '22032' + + +class InvalidSQLJsonSubscriptError(DataError): + sqlstate = '22033' + + +class MoreThanOneSQLJsonItemError(DataError): + sqlstate = '22034' + + +class NoSQLJsonItemError(DataError): + sqlstate = '22035' + + +class NonNumericSQLJsonItemError(DataError): + sqlstate = '22036' + + +class NonUniqueKeysInAJsonObjectError(DataError): + sqlstate = '22037' + + +class SingletonSQLJsonItemRequiredError(DataError): + sqlstate = '22038' + + +class SQLJsonArrayNotFoundError(DataError): + sqlstate = '22039' + + +class SQLJsonMemberNotFoundError(DataError): + sqlstate = '2203A' + + +class SQLJsonNumberNotFoundError(DataError): + sqlstate = '2203B' + + +class SQLJsonObjectNotFoundError(DataError): + sqlstate = '2203C' + + +class TooManyJsonArrayElementsError(DataError): + sqlstate = '2203D' + + +class TooManyJsonObjectMembersError(DataError): + sqlstate = '2203E' + + +class SQLJsonScalarRequiredError(DataError): + sqlstate = '2203F' + + +class SQLJsonItemCannotBeCastToTargetTypeError(DataError): + sqlstate = '2203G' + + +class IntegrityConstraintViolationError(_base.PostgresError): + sqlstate = '23000' + + +class RestrictViolationError(IntegrityConstraintViolationError): + sqlstate = '23001' + + +class NotNullViolationError(IntegrityConstraintViolationError): + sqlstate = '23502' + + +class ForeignKeyViolationError(IntegrityConstraintViolationError): + sqlstate = '23503' + + +class UniqueViolationError(IntegrityConstraintViolationError): + sqlstate = '23505' + + +class CheckViolationError(IntegrityConstraintViolationError): + sqlstate = '23514' + + +class ExclusionViolationError(IntegrityConstraintViolationError): + sqlstate = '23P01' + + +class InvalidCursorStateError(_base.PostgresError): + sqlstate = '24000' + + +class InvalidTransactionStateError(_base.PostgresError): + sqlstate = '25000' + + +class ActiveSQLTransactionError(InvalidTransactionStateError): + sqlstate = '25001' + + +class BranchTransactionAlreadyActiveError(InvalidTransactionStateError): + sqlstate = '25002' + + +class HeldCursorRequiresSameIsolationLevelError(InvalidTransactionStateError): + sqlstate = '25008' + + +class InappropriateAccessModeForBranchTransactionError( + InvalidTransactionStateError): + sqlstate = '25003' + + +class InappropriateIsolationLevelForBranchTransactionError( + InvalidTransactionStateError): + sqlstate = '25004' + + +class NoActiveSQLTransactionForBranchTransactionError( + InvalidTransactionStateError): + sqlstate = '25005' + + +class ReadOnlySQLTransactionError(InvalidTransactionStateError): + sqlstate = '25006' + + +class SchemaAndDataStatementMixingNotSupportedError( + InvalidTransactionStateError): + sqlstate = '25007' + + +class NoActiveSQLTransactionError(InvalidTransactionStateError): + sqlstate = '25P01' + + +class InFailedSQLTransactionError(InvalidTransactionStateError): + sqlstate = '25P02' + + +class IdleInTransactionSessionTimeoutError(InvalidTransactionStateError): + sqlstate = '25P03' + + +class InvalidSQLStatementNameError(_base.PostgresError): + sqlstate = '26000' + + +class TriggeredDataChangeViolationError(_base.PostgresError): + sqlstate = '27000' + + +class InvalidAuthorizationSpecificationError(_base.PostgresError): + sqlstate = '28000' + + +class InvalidPasswordError(InvalidAuthorizationSpecificationError): + sqlstate = '28P01' + + +class DependentPrivilegeDescriptorsStillExistError(_base.PostgresError): + sqlstate = '2B000' + + +class DependentObjectsStillExistError( + DependentPrivilegeDescriptorsStillExistError): + sqlstate = '2BP01' + + +class InvalidTransactionTerminationError(_base.PostgresError): + sqlstate = '2D000' + + +class SQLRoutineError(_base.PostgresError): + sqlstate = '2F000' + + +class FunctionExecutedNoReturnStatementError(SQLRoutineError): + sqlstate = '2F005' + + +class ModifyingSQLDataNotPermittedError(SQLRoutineError): + sqlstate = '2F002' + + +class ProhibitedSQLStatementAttemptedError(SQLRoutineError): + sqlstate = '2F003' + + +class ReadingSQLDataNotPermittedError(SQLRoutineError): + sqlstate = '2F004' + + +class InvalidCursorNameError(_base.PostgresError): + sqlstate = '34000' + + +class ExternalRoutineError(_base.PostgresError): + sqlstate = '38000' + + +class ContainingSQLNotPermittedError(ExternalRoutineError): + sqlstate = '38001' + + +class ModifyingExternalRoutineSQLDataNotPermittedError(ExternalRoutineError): + sqlstate = '38002' + + +class ProhibitedExternalRoutineSQLStatementAttemptedError( + ExternalRoutineError): + sqlstate = '38003' + + +class ReadingExternalRoutineSQLDataNotPermittedError(ExternalRoutineError): + sqlstate = '38004' + + +class ExternalRoutineInvocationError(_base.PostgresError): + sqlstate = '39000' + + +class InvalidSqlstateReturnedError(ExternalRoutineInvocationError): + sqlstate = '39001' + + +class NullValueInExternalRoutineNotAllowedError( + ExternalRoutineInvocationError): + sqlstate = '39004' + + +class TriggerProtocolViolatedError(ExternalRoutineInvocationError): + sqlstate = '39P01' + + +class SrfProtocolViolatedError(ExternalRoutineInvocationError): + sqlstate = '39P02' + + +class EventTriggerProtocolViolatedError(ExternalRoutineInvocationError): + sqlstate = '39P03' + + +class SavepointError(_base.PostgresError): + sqlstate = '3B000' + + +class InvalidSavepointSpecificationError(SavepointError): + sqlstate = '3B001' + + +class InvalidCatalogNameError(_base.PostgresError): + sqlstate = '3D000' + + +class InvalidSchemaNameError(_base.PostgresError): + sqlstate = '3F000' + + +class TransactionRollbackError(_base.PostgresError): + sqlstate = '40000' + + +class TransactionIntegrityConstraintViolationError(TransactionRollbackError): + sqlstate = '40002' + + +class SerializationError(TransactionRollbackError): + sqlstate = '40001' + + +class StatementCompletionUnknownError(TransactionRollbackError): + sqlstate = '40003' + + +class DeadlockDetectedError(TransactionRollbackError): + sqlstate = '40P01' + + +class SyntaxOrAccessError(_base.PostgresError): + sqlstate = '42000' + + +class PostgresSyntaxError(SyntaxOrAccessError): + sqlstate = '42601' + + +class InsufficientPrivilegeError(SyntaxOrAccessError): + sqlstate = '42501' + + +class CannotCoerceError(SyntaxOrAccessError): + sqlstate = '42846' + + +class GroupingError(SyntaxOrAccessError): + sqlstate = '42803' + + +class WindowingError(SyntaxOrAccessError): + sqlstate = '42P20' + + +class InvalidRecursionError(SyntaxOrAccessError): + sqlstate = '42P19' + + +class InvalidForeignKeyError(SyntaxOrAccessError): + sqlstate = '42830' + + +class InvalidNameError(SyntaxOrAccessError): + sqlstate = '42602' + + +class NameTooLongError(SyntaxOrAccessError): + sqlstate = '42622' + + +class ReservedNameError(SyntaxOrAccessError): + sqlstate = '42939' + + +class DatatypeMismatchError(SyntaxOrAccessError): + sqlstate = '42804' + + +class IndeterminateDatatypeError(SyntaxOrAccessError): + sqlstate = '42P18' + + +class CollationMismatchError(SyntaxOrAccessError): + sqlstate = '42P21' + + +class IndeterminateCollationError(SyntaxOrAccessError): + sqlstate = '42P22' + + +class WrongObjectTypeError(SyntaxOrAccessError): + sqlstate = '42809' + + +class GeneratedAlwaysError(SyntaxOrAccessError): + sqlstate = '428C9' + + +class UndefinedColumnError(SyntaxOrAccessError): + sqlstate = '42703' + + +class UndefinedFunctionError(SyntaxOrAccessError): + sqlstate = '42883' + + +class UndefinedTableError(SyntaxOrAccessError): + sqlstate = '42P01' + + +class UndefinedParameterError(SyntaxOrAccessError): + sqlstate = '42P02' + + +class UndefinedObjectError(SyntaxOrAccessError): + sqlstate = '42704' + + +class DuplicateColumnError(SyntaxOrAccessError): + sqlstate = '42701' + + +class DuplicateCursorError(SyntaxOrAccessError): + sqlstate = '42P03' + + +class DuplicateDatabaseError(SyntaxOrAccessError): + sqlstate = '42P04' + + +class DuplicateFunctionError(SyntaxOrAccessError): + sqlstate = '42723' + + +class DuplicatePreparedStatementError(SyntaxOrAccessError): + sqlstate = '42P05' + + +class DuplicateSchemaError(SyntaxOrAccessError): + sqlstate = '42P06' + + +class DuplicateTableError(SyntaxOrAccessError): + sqlstate = '42P07' + + +class DuplicateAliasError(SyntaxOrAccessError): + sqlstate = '42712' + + +class DuplicateObjectError(SyntaxOrAccessError): + sqlstate = '42710' + + +class AmbiguousColumnError(SyntaxOrAccessError): + sqlstate = '42702' + + +class AmbiguousFunctionError(SyntaxOrAccessError): + sqlstate = '42725' + + +class AmbiguousParameterError(SyntaxOrAccessError): + sqlstate = '42P08' + + +class AmbiguousAliasError(SyntaxOrAccessError): + sqlstate = '42P09' + + +class InvalidColumnReferenceError(SyntaxOrAccessError): + sqlstate = '42P10' + + +class InvalidColumnDefinitionError(SyntaxOrAccessError): + sqlstate = '42611' + + +class InvalidCursorDefinitionError(SyntaxOrAccessError): + sqlstate = '42P11' + + +class InvalidDatabaseDefinitionError(SyntaxOrAccessError): + sqlstate = '42P12' + + +class InvalidFunctionDefinitionError(SyntaxOrAccessError): + sqlstate = '42P13' + + +class InvalidPreparedStatementDefinitionError(SyntaxOrAccessError): + sqlstate = '42P14' + + +class InvalidSchemaDefinitionError(SyntaxOrAccessError): + sqlstate = '42P15' + + +class InvalidTableDefinitionError(SyntaxOrAccessError): + sqlstate = '42P16' + + +class InvalidObjectDefinitionError(SyntaxOrAccessError): + sqlstate = '42P17' + + +class WithCheckOptionViolationError(_base.PostgresError): + sqlstate = '44000' + + +class InsufficientResourcesError(_base.PostgresError): + sqlstate = '53000' + + +class DiskFullError(InsufficientResourcesError): + sqlstate = '53100' + + +class OutOfMemoryError(InsufficientResourcesError): + sqlstate = '53200' + + +class TooManyConnectionsError(InsufficientResourcesError): + sqlstate = '53300' + + +class ConfigurationLimitExceededError(InsufficientResourcesError): + sqlstate = '53400' + + +class ProgramLimitExceededError(_base.PostgresError): + sqlstate = '54000' + + +class StatementTooComplexError(ProgramLimitExceededError): + sqlstate = '54001' + + +class TooManyColumnsError(ProgramLimitExceededError): + sqlstate = '54011' + + +class TooManyArgumentsError(ProgramLimitExceededError): + sqlstate = '54023' + + +class ObjectNotInPrerequisiteStateError(_base.PostgresError): + sqlstate = '55000' + + +class ObjectInUseError(ObjectNotInPrerequisiteStateError): + sqlstate = '55006' + + +class CantChangeRuntimeParamError(ObjectNotInPrerequisiteStateError): + sqlstate = '55P02' + + +class LockNotAvailableError(ObjectNotInPrerequisiteStateError): + sqlstate = '55P03' + + +class UnsafeNewEnumValueUsageError(ObjectNotInPrerequisiteStateError): + sqlstate = '55P04' + + +class OperatorInterventionError(_base.PostgresError): + sqlstate = '57000' + + +class QueryCanceledError(OperatorInterventionError): + sqlstate = '57014' + + +class AdminShutdownError(OperatorInterventionError): + sqlstate = '57P01' + + +class CrashShutdownError(OperatorInterventionError): + sqlstate = '57P02' + + +class CannotConnectNowError(OperatorInterventionError): + sqlstate = '57P03' + + +class DatabaseDroppedError(OperatorInterventionError): + sqlstate = '57P04' + + +class IdleSessionTimeoutError(OperatorInterventionError): + sqlstate = '57P05' + + +class PostgresSystemError(_base.PostgresError): + sqlstate = '58000' + + +class PostgresIOError(PostgresSystemError): + sqlstate = '58030' + + +class UndefinedFileError(PostgresSystemError): + sqlstate = '58P01' + + +class DuplicateFileError(PostgresSystemError): + sqlstate = '58P02' + + +class SnapshotTooOldError(_base.PostgresError): + sqlstate = '72000' + + +class ConfigFileError(_base.PostgresError): + sqlstate = 'F0000' + + +class LockFileExistsError(ConfigFileError): + sqlstate = 'F0001' + + +class FDWError(_base.PostgresError): + sqlstate = 'HV000' + + +class FDWColumnNameNotFoundError(FDWError): + sqlstate = 'HV005' + + +class FDWDynamicParameterValueNeededError(FDWError): + sqlstate = 'HV002' + + +class FDWFunctionSequenceError(FDWError): + sqlstate = 'HV010' + + +class FDWInconsistentDescriptorInformationError(FDWError): + sqlstate = 'HV021' + + +class FDWInvalidAttributeValueError(FDWError): + sqlstate = 'HV024' + + +class FDWInvalidColumnNameError(FDWError): + sqlstate = 'HV007' + + +class FDWInvalidColumnNumberError(FDWError): + sqlstate = 'HV008' + + +class FDWInvalidDataTypeError(FDWError): + sqlstate = 'HV004' + + +class FDWInvalidDataTypeDescriptorsError(FDWError): + sqlstate = 'HV006' + + +class FDWInvalidDescriptorFieldIdentifierError(FDWError): + sqlstate = 'HV091' + + +class FDWInvalidHandleError(FDWError): + sqlstate = 'HV00B' + + +class FDWInvalidOptionIndexError(FDWError): + sqlstate = 'HV00C' + + +class FDWInvalidOptionNameError(FDWError): + sqlstate = 'HV00D' + + +class FDWInvalidStringLengthOrBufferLengthError(FDWError): + sqlstate = 'HV090' + + +class FDWInvalidStringFormatError(FDWError): + sqlstate = 'HV00A' + + +class FDWInvalidUseOfNullPointerError(FDWError): + sqlstate = 'HV009' + + +class FDWTooManyHandlesError(FDWError): + sqlstate = 'HV014' + + +class FDWOutOfMemoryError(FDWError): + sqlstate = 'HV001' + + +class FDWNoSchemasError(FDWError): + sqlstate = 'HV00P' + + +class FDWOptionNameNotFoundError(FDWError): + sqlstate = 'HV00J' + + +class FDWReplyHandleError(FDWError): + sqlstate = 'HV00K' + + +class FDWSchemaNotFoundError(FDWError): + sqlstate = 'HV00Q' + + +class FDWTableNotFoundError(FDWError): + sqlstate = 'HV00R' + + +class FDWUnableToCreateExecutionError(FDWError): + sqlstate = 'HV00L' + + +class FDWUnableToCreateReplyError(FDWError): + sqlstate = 'HV00M' + + +class FDWUnableToEstablishConnectionError(FDWError): + sqlstate = 'HV00N' + + +class PLPGSQLError(_base.PostgresError): + sqlstate = 'P0000' + + +class RaiseError(PLPGSQLError): + sqlstate = 'P0001' + + +class NoDataFoundError(PLPGSQLError): + sqlstate = 'P0002' + + +class TooManyRowsError(PLPGSQLError): + sqlstate = 'P0003' + + +class AssertError(PLPGSQLError): + sqlstate = 'P0004' + + +class InternalServerError(_base.PostgresError): + sqlstate = 'XX000' + + +class DataCorruptedError(InternalServerError): + sqlstate = 'XX001' + + +class IndexCorruptedError(InternalServerError): + sqlstate = 'XX002' + + +__all__ = ( + 'ActiveSQLTransactionError', 'AdminShutdownError', + 'AmbiguousAliasError', 'AmbiguousColumnError', + 'AmbiguousFunctionError', 'AmbiguousParameterError', + 'ArraySubscriptError', 'AssertError', 'BadCopyFileFormatError', + 'BranchTransactionAlreadyActiveError', 'CannotCoerceError', + 'CannotConnectNowError', 'CantChangeRuntimeParamError', + 'CardinalityViolationError', 'CaseNotFoundError', + 'CharacterNotInRepertoireError', 'CheckViolationError', + 'ClientCannotConnectError', 'CollationMismatchError', + 'ConfigFileError', 'ConfigurationLimitExceededError', + 'ConnectionDoesNotExistError', 'ConnectionFailureError', + 'ConnectionRejectionError', 'ContainingSQLNotPermittedError', + 'CrashShutdownError', 'DataCorruptedError', 'DataError', + 'DatabaseDroppedError', 'DatatypeMismatchError', + 'DatetimeFieldOverflowError', 'DeadlockDetectedError', + 'DependentObjectsStillExistError', + 'DependentPrivilegeDescriptorsStillExistError', 'DeprecatedFeature', + 'DiagnosticsError', 'DiskFullError', 'DivisionByZeroError', + 'DuplicateAliasError', 'DuplicateColumnError', 'DuplicateCursorError', + 'DuplicateDatabaseError', 'DuplicateFileError', + 'DuplicateFunctionError', 'DuplicateJsonObjectKeyValueError', + 'DuplicateObjectError', 'DuplicatePreparedStatementError', + 'DuplicateSchemaError', 'DuplicateTableError', + 'DynamicResultSetsReturned', 'ErrorInAssignmentError', + 'EscapeCharacterConflictError', 'EventTriggerProtocolViolatedError', + 'ExclusionViolationError', 'ExternalRoutineError', + 'ExternalRoutineInvocationError', 'FDWColumnNameNotFoundError', + 'FDWDynamicParameterValueNeededError', 'FDWError', + 'FDWFunctionSequenceError', + 'FDWInconsistentDescriptorInformationError', + 'FDWInvalidAttributeValueError', 'FDWInvalidColumnNameError', + 'FDWInvalidColumnNumberError', 'FDWInvalidDataTypeDescriptorsError', + 'FDWInvalidDataTypeError', 'FDWInvalidDescriptorFieldIdentifierError', + 'FDWInvalidHandleError', 'FDWInvalidOptionIndexError', + 'FDWInvalidOptionNameError', 'FDWInvalidStringFormatError', + 'FDWInvalidStringLengthOrBufferLengthError', + 'FDWInvalidUseOfNullPointerError', 'FDWNoSchemasError', + 'FDWOptionNameNotFoundError', 'FDWOutOfMemoryError', + 'FDWReplyHandleError', 'FDWSchemaNotFoundError', + 'FDWTableNotFoundError', 'FDWTooManyHandlesError', + 'FDWUnableToCreateExecutionError', 'FDWUnableToCreateReplyError', + 'FDWUnableToEstablishConnectionError', 'FeatureNotSupportedError', + 'ForeignKeyViolationError', 'FunctionExecutedNoReturnStatementError', + 'GeneratedAlwaysError', 'GroupingError', + 'HeldCursorRequiresSameIsolationLevelError', + 'IdleInTransactionSessionTimeoutError', 'IdleSessionTimeoutError', + 'ImplicitZeroBitPadding', 'InFailedSQLTransactionError', + 'InappropriateAccessModeForBranchTransactionError', + 'InappropriateIsolationLevelForBranchTransactionError', + 'IndeterminateCollationError', 'IndeterminateDatatypeError', + 'IndexCorruptedError', 'IndicatorOverflowError', + 'InsufficientPrivilegeError', 'InsufficientResourcesError', + 'IntegrityConstraintViolationError', 'InternalServerError', + 'IntervalFieldOverflowError', 'InvalidArgumentForLogarithmError', + 'InvalidArgumentForNthValueFunctionError', + 'InvalidArgumentForNtileFunctionError', + 'InvalidArgumentForPowerFunctionError', + 'InvalidArgumentForSQLJsonDatetimeFunctionError', + 'InvalidArgumentForWidthBucketFunctionError', + 'InvalidAuthorizationSpecificationError', + 'InvalidBinaryRepresentationError', 'InvalidCachedStatementError', + 'InvalidCatalogNameError', 'InvalidCharacterValueForCastError', + 'InvalidColumnDefinitionError', 'InvalidColumnReferenceError', + 'InvalidCursorDefinitionError', 'InvalidCursorNameError', + 'InvalidCursorStateError', 'InvalidDatabaseDefinitionError', + 'InvalidDatetimeFormatError', 'InvalidEscapeCharacterError', + 'InvalidEscapeOctetError', 'InvalidEscapeSequenceError', + 'InvalidForeignKeyError', 'InvalidFunctionDefinitionError', + 'InvalidGrantOperationError', 'InvalidGrantorError', + 'InvalidIndicatorParameterValueError', 'InvalidJsonTextError', + 'InvalidLocatorSpecificationError', 'InvalidNameError', + 'InvalidObjectDefinitionError', 'InvalidParameterValueError', + 'InvalidPasswordError', 'InvalidPrecedingOrFollowingSizeError', + 'InvalidPreparedStatementDefinitionError', 'InvalidRecursionError', + 'InvalidRegularExpressionError', 'InvalidRoleSpecificationError', + 'InvalidRowCountInLimitClauseError', + 'InvalidRowCountInResultOffsetClauseError', + 'InvalidSQLJsonSubscriptError', 'InvalidSQLStatementNameError', + 'InvalidSavepointSpecificationError', 'InvalidSchemaDefinitionError', + 'InvalidSchemaNameError', 'InvalidSqlstateReturnedError', + 'InvalidTableDefinitionError', 'InvalidTablesampleArgumentError', + 'InvalidTablesampleRepeatError', 'InvalidTextRepresentationError', + 'InvalidTimeZoneDisplacementValueError', + 'InvalidTransactionInitiationError', 'InvalidTransactionStateError', + 'InvalidTransactionTerminationError', + 'InvalidUseOfEscapeCharacterError', 'InvalidXmlCommentError', + 'InvalidXmlContentError', 'InvalidXmlDocumentError', + 'InvalidXmlProcessingInstructionError', 'LocatorError', + 'LockFileExistsError', 'LockNotAvailableError', + 'ModifyingExternalRoutineSQLDataNotPermittedError', + 'ModifyingSQLDataNotPermittedError', 'MoreThanOneSQLJsonItemError', + 'MostSpecificTypeMismatchError', 'NameTooLongError', + 'NoActiveSQLTransactionError', + 'NoActiveSQLTransactionForBranchTransactionError', + 'NoAdditionalDynamicResultSetsReturned', 'NoData', 'NoDataFoundError', + 'NoSQLJsonItemError', 'NonNumericSQLJsonItemError', + 'NonUniqueKeysInAJsonObjectError', + 'NonstandardUseOfEscapeCharacterError', 'NotAnXmlDocumentError', + 'NotNullViolationError', 'NullValueEliminatedInSetFunction', + 'NullValueInExternalRoutineNotAllowedError', + 'NullValueNoIndicatorParameterError', 'NullValueNotAllowedError', + 'NumericValueOutOfRangeError', 'ObjectInUseError', + 'ObjectNotInPrerequisiteStateError', 'OperatorInterventionError', + 'OutOfMemoryError', 'PLPGSQLError', 'PostgresConnectionError', + 'PostgresFloatingPointError', 'PostgresIOError', + 'PostgresSyntaxError', 'PostgresSystemError', 'PostgresWarning', + 'PrivilegeNotGranted', 'PrivilegeNotRevoked', + 'ProgramLimitExceededError', + 'ProhibitedExternalRoutineSQLStatementAttemptedError', + 'ProhibitedSQLStatementAttemptedError', 'ProtocolViolationError', + 'QueryCanceledError', 'RaiseError', 'ReadOnlySQLTransactionError', + 'ReadingExternalRoutineSQLDataNotPermittedError', + 'ReadingSQLDataNotPermittedError', 'ReservedNameError', + 'RestrictViolationError', 'SQLJsonArrayNotFoundError', + 'SQLJsonItemCannotBeCastToTargetTypeError', + 'SQLJsonMemberNotFoundError', 'SQLJsonNumberNotFoundError', + 'SQLJsonObjectNotFoundError', 'SQLJsonScalarRequiredError', + 'SQLRoutineError', 'SQLStatementNotYetCompleteError', + 'SavepointError', 'SchemaAndDataStatementMixingNotSupportedError', + 'SequenceGeneratorLimitExceededError', 'SerializationError', + 'SingletonSQLJsonItemRequiredError', 'SnapshotTooOldError', + 'SrfProtocolViolatedError', + 'StackedDiagnosticsAccessedWithoutActiveHandlerError', + 'StatementCompletionUnknownError', 'StatementTooComplexError', + 'StringDataLengthMismatchError', 'StringDataRightTruncation', + 'StringDataRightTruncationError', 'SubstringError', + 'SyntaxOrAccessError', 'TooManyArgumentsError', 'TooManyColumnsError', + 'TooManyConnectionsError', 'TooManyJsonArrayElementsError', + 'TooManyJsonObjectMembersError', 'TooManyRowsError', + 'TransactionIntegrityConstraintViolationError', + 'TransactionResolutionUnknownError', 'TransactionRollbackError', + 'TriggerProtocolViolatedError', 'TriggeredActionError', + 'TriggeredDataChangeViolationError', 'TrimError', + 'UndefinedColumnError', 'UndefinedFileError', + 'UndefinedFunctionError', 'UndefinedObjectError', + 'UndefinedParameterError', 'UndefinedTableError', + 'UniqueViolationError', 'UnsafeNewEnumValueUsageError', + 'UnterminatedCStringError', 'UntranslatableCharacterError', + 'WindowingError', 'WithCheckOptionViolationError', + 'WrongObjectTypeError', 'ZeroLengthCharacterStringError' +) + +__all__ += _base.__all__ diff --git a/env/Lib/site-packages/asyncpg/exceptions/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/asyncpg/exceptions/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..dfcb388 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/exceptions/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/exceptions/__pycache__/_base.cpython-311.pyc b/env/Lib/site-packages/asyncpg/exceptions/__pycache__/_base.cpython-311.pyc new file mode 100644 index 0000000..7d82a21 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/exceptions/__pycache__/_base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/exceptions/_base.py b/env/Lib/site-packages/asyncpg/exceptions/_base.py new file mode 100644 index 0000000..00e9699 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/exceptions/_base.py @@ -0,0 +1,299 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import asyncpg +import sys +import textwrap + + +__all__ = ('PostgresError', 'FatalPostgresError', 'UnknownPostgresError', + 'InterfaceError', 'InterfaceWarning', 'PostgresLogMessage', + 'ClientConfigurationError', + 'InternalClientError', 'OutdatedSchemaCacheError', 'ProtocolError', + 'UnsupportedClientFeatureError', 'TargetServerAttributeNotMatched', + 'UnsupportedServerFeatureError') + + +def _is_asyncpg_class(cls): + modname = cls.__module__ + return modname == 'asyncpg' or modname.startswith('asyncpg.') + + +class PostgresMessageMeta(type): + + _message_map = {} + _field_map = { + 'S': 'severity', + 'V': 'severity_en', + 'C': 'sqlstate', + 'M': 'message', + 'D': 'detail', + 'H': 'hint', + 'P': 'position', + 'p': 'internal_position', + 'q': 'internal_query', + 'W': 'context', + 's': 'schema_name', + 't': 'table_name', + 'c': 'column_name', + 'd': 'data_type_name', + 'n': 'constraint_name', + 'F': 'server_source_filename', + 'L': 'server_source_line', + 'R': 'server_source_function' + } + + def __new__(mcls, name, bases, dct): + cls = super().__new__(mcls, name, bases, dct) + if cls.__module__ == mcls.__module__ and name == 'PostgresMessage': + for f in mcls._field_map.values(): + setattr(cls, f, None) + + if _is_asyncpg_class(cls): + mod = sys.modules[cls.__module__] + if hasattr(mod, name): + raise RuntimeError('exception class redefinition: {}'.format( + name)) + + code = dct.get('sqlstate') + if code is not None: + existing = mcls._message_map.get(code) + if existing is not None: + raise TypeError('{} has duplicate SQLSTATE code, which is' + 'already defined by {}'.format( + name, existing.__name__)) + mcls._message_map[code] = cls + + return cls + + @classmethod + def get_message_class_for_sqlstate(mcls, code): + return mcls._message_map.get(code, UnknownPostgresError) + + +class PostgresMessage(metaclass=PostgresMessageMeta): + + @classmethod + def _get_error_class(cls, fields): + sqlstate = fields.get('C') + return type(cls).get_message_class_for_sqlstate(sqlstate) + + @classmethod + def _get_error_dict(cls, fields, query): + dct = { + 'query': query + } + + field_map = type(cls)._field_map + for k, v in fields.items(): + field = field_map.get(k) + if field: + dct[field] = v + + return dct + + @classmethod + def _make_constructor(cls, fields, query=None): + dct = cls._get_error_dict(fields, query) + + exccls = cls._get_error_class(fields) + message = dct.get('message', '') + + # PostgreSQL will raise an exception when it detects + # that the result type of the query has changed from + # when the statement was prepared. + # + # The original error is somewhat cryptic and unspecific, + # so we raise a custom subclass that is easier to handle + # and identify. + # + # Note that we specifically do not rely on the error + # message, as it is localizable. + is_icse = ( + exccls.__name__ == 'FeatureNotSupportedError' and + _is_asyncpg_class(exccls) and + dct.get('server_source_function') == 'RevalidateCachedQuery' + ) + + if is_icse: + exceptions = sys.modules[exccls.__module__] + exccls = exceptions.InvalidCachedStatementError + message = ('cached statement plan is invalid due to a database ' + 'schema or configuration change') + + is_prepared_stmt_error = ( + exccls.__name__ in ('DuplicatePreparedStatementError', + 'InvalidSQLStatementNameError') and + _is_asyncpg_class(exccls) + ) + + if is_prepared_stmt_error: + hint = dct.get('hint', '') + hint += textwrap.dedent("""\ + + NOTE: pgbouncer with pool_mode set to "transaction" or + "statement" does not support prepared statements properly. + You have two options: + + * if you are using pgbouncer for connection pooling to a + single server, switch to the connection pool functionality + provided by asyncpg, it is a much better option for this + purpose; + + * if you have no option of avoiding the use of pgbouncer, + then you can set statement_cache_size to 0 when creating + the asyncpg connection object. + """) + + dct['hint'] = hint + + return exccls, message, dct + + def as_dict(self): + dct = {} + for f in type(self)._field_map.values(): + val = getattr(self, f) + if val is not None: + dct[f] = val + return dct + + +class PostgresError(PostgresMessage, Exception): + """Base class for all Postgres errors.""" + + def __str__(self): + msg = self.args[0] + if self.detail: + msg += '\nDETAIL: {}'.format(self.detail) + if self.hint: + msg += '\nHINT: {}'.format(self.hint) + + return msg + + @classmethod + def new(cls, fields, query=None): + exccls, message, dct = cls._make_constructor(fields, query) + ex = exccls(message) + ex.__dict__.update(dct) + return ex + + +class FatalPostgresError(PostgresError): + """A fatal error that should result in server disconnection.""" + + +class UnknownPostgresError(FatalPostgresError): + """An error with an unknown SQLSTATE code.""" + + +class InterfaceMessage: + def __init__(self, *, detail=None, hint=None): + self.detail = detail + self.hint = hint + + def __str__(self): + msg = self.args[0] + if self.detail: + msg += '\nDETAIL: {}'.format(self.detail) + if self.hint: + msg += '\nHINT: {}'.format(self.hint) + + return msg + + +class InterfaceError(InterfaceMessage, Exception): + """An error caused by improper use of asyncpg API.""" + + def __init__(self, msg, *, detail=None, hint=None): + InterfaceMessage.__init__(self, detail=detail, hint=hint) + Exception.__init__(self, msg) + + def with_msg(self, msg): + return type(self)( + msg, + detail=self.detail, + hint=self.hint, + ).with_traceback( + self.__traceback__ + ) + + +class ClientConfigurationError(InterfaceError, ValueError): + """An error caused by improper client configuration.""" + + +class DataError(InterfaceError, ValueError): + """An error caused by invalid query input.""" + + +class UnsupportedClientFeatureError(InterfaceError): + """Requested feature is unsupported by asyncpg.""" + + +class UnsupportedServerFeatureError(InterfaceError): + """Requested feature is unsupported by PostgreSQL server.""" + + +class InterfaceWarning(InterfaceMessage, UserWarning): + """A warning caused by an improper use of asyncpg API.""" + + def __init__(self, msg, *, detail=None, hint=None): + InterfaceMessage.__init__(self, detail=detail, hint=hint) + UserWarning.__init__(self, msg) + + +class InternalClientError(Exception): + """All unexpected errors not classified otherwise.""" + + +class ProtocolError(InternalClientError): + """Unexpected condition in the handling of PostgreSQL protocol input.""" + + +class TargetServerAttributeNotMatched(InternalClientError): + """Could not find a host that satisfies the target attribute requirement""" + + +class OutdatedSchemaCacheError(InternalClientError): + """A value decoding error caused by a schema change before row fetching.""" + + def __init__(self, msg, *, schema=None, data_type=None, position=None): + super().__init__(msg) + self.schema_name = schema + self.data_type_name = data_type + self.position = position + + +class PostgresLogMessage(PostgresMessage): + """A base class for non-error server messages.""" + + def __str__(self): + return '{}: {}'.format(type(self).__name__, self.message) + + def __setattr__(self, name, val): + raise TypeError('instances of {} are immutable'.format( + type(self).__name__)) + + @classmethod + def new(cls, fields, query=None): + exccls, message_text, dct = cls._make_constructor(fields, query) + + if exccls is UnknownPostgresError: + exccls = PostgresLogMessage + + if exccls is PostgresLogMessage: + severity = dct.get('severity_en') or dct.get('severity') + if severity and severity.upper() == 'WARNING': + exccls = asyncpg.PostgresWarning + + if issubclass(exccls, (BaseException, Warning)): + msg = exccls(message_text) + else: + msg = exccls() + + msg.__dict__.update(dct) + return msg diff --git a/env/Lib/site-packages/asyncpg/introspection.py b/env/Lib/site-packages/asyncpg/introspection.py new file mode 100644 index 0000000..6c2caf0 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/introspection.py @@ -0,0 +1,292 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +_TYPEINFO_13 = '''\ + ( + SELECT + t.oid AS oid, + ns.nspname AS ns, + t.typname AS name, + t.typtype AS kind, + (CASE WHEN t.typtype = 'd' THEN + (WITH RECURSIVE typebases(oid, depth) AS ( + SELECT + t2.typbasetype AS oid, + 0 AS depth + FROM + pg_type t2 + WHERE + t2.oid = t.oid + + UNION ALL + + SELECT + t2.typbasetype AS oid, + tb.depth + 1 AS depth + FROM + pg_type t2, + typebases tb + WHERE + tb.oid = t2.oid + AND t2.typbasetype != 0 + ) SELECT oid FROM typebases ORDER BY depth DESC LIMIT 1) + + ELSE NULL + END) AS basetype, + t.typelem AS elemtype, + elem_t.typdelim AS elemdelim, + range_t.rngsubtype AS range_subtype, + (CASE WHEN t.typtype = 'c' THEN + (SELECT + array_agg(ia.atttypid ORDER BY ia.attnum) + FROM + pg_attribute ia + INNER JOIN pg_class c + ON (ia.attrelid = c.oid) + WHERE + ia.attnum > 0 AND NOT ia.attisdropped + AND c.reltype = t.oid) + + ELSE NULL + END) AS attrtypoids, + (CASE WHEN t.typtype = 'c' THEN + (SELECT + array_agg(ia.attname::text ORDER BY ia.attnum) + FROM + pg_attribute ia + INNER JOIN pg_class c + ON (ia.attrelid = c.oid) + WHERE + ia.attnum > 0 AND NOT ia.attisdropped + AND c.reltype = t.oid) + + ELSE NULL + END) AS attrnames + FROM + pg_catalog.pg_type AS t + INNER JOIN pg_catalog.pg_namespace ns ON ( + ns.oid = t.typnamespace) + LEFT JOIN pg_type elem_t ON ( + t.typlen = -1 AND + t.typelem != 0 AND + t.typelem = elem_t.oid + ) + LEFT JOIN pg_range range_t ON ( + t.oid = range_t.rngtypid + ) + ) +''' + + +INTRO_LOOKUP_TYPES_13 = '''\ +WITH RECURSIVE typeinfo_tree( + oid, ns, name, kind, basetype, elemtype, elemdelim, + range_subtype, attrtypoids, attrnames, depth) +AS ( + SELECT + ti.oid, ti.ns, ti.name, ti.kind, ti.basetype, + ti.elemtype, ti.elemdelim, ti.range_subtype, + ti.attrtypoids, ti.attrnames, 0 + FROM + {typeinfo} AS ti + WHERE + ti.oid = any($1::oid[]) + + UNION ALL + + SELECT + ti.oid, ti.ns, ti.name, ti.kind, ti.basetype, + ti.elemtype, ti.elemdelim, ti.range_subtype, + ti.attrtypoids, ti.attrnames, tt.depth + 1 + FROM + {typeinfo} ti, + typeinfo_tree tt + WHERE + (tt.elemtype IS NOT NULL AND ti.oid = tt.elemtype) + OR (tt.attrtypoids IS NOT NULL AND ti.oid = any(tt.attrtypoids)) + OR (tt.range_subtype IS NOT NULL AND ti.oid = tt.range_subtype) + OR (tt.basetype IS NOT NULL AND ti.oid = tt.basetype) +) + +SELECT DISTINCT + *, + basetype::regtype::text AS basetype_name, + elemtype::regtype::text AS elemtype_name, + range_subtype::regtype::text AS range_subtype_name +FROM + typeinfo_tree +ORDER BY + depth DESC +'''.format(typeinfo=_TYPEINFO_13) + + +_TYPEINFO = '''\ + ( + SELECT + t.oid AS oid, + ns.nspname AS ns, + t.typname AS name, + t.typtype AS kind, + (CASE WHEN t.typtype = 'd' THEN + (WITH RECURSIVE typebases(oid, depth) AS ( + SELECT + t2.typbasetype AS oid, + 0 AS depth + FROM + pg_type t2 + WHERE + t2.oid = t.oid + + UNION ALL + + SELECT + t2.typbasetype AS oid, + tb.depth + 1 AS depth + FROM + pg_type t2, + typebases tb + WHERE + tb.oid = t2.oid + AND t2.typbasetype != 0 + ) SELECT oid FROM typebases ORDER BY depth DESC LIMIT 1) + + ELSE NULL + END) AS basetype, + t.typelem AS elemtype, + elem_t.typdelim AS elemdelim, + COALESCE( + range_t.rngsubtype, + multirange_t.rngsubtype) AS range_subtype, + (CASE WHEN t.typtype = 'c' THEN + (SELECT + array_agg(ia.atttypid ORDER BY ia.attnum) + FROM + pg_attribute ia + INNER JOIN pg_class c + ON (ia.attrelid = c.oid) + WHERE + ia.attnum > 0 AND NOT ia.attisdropped + AND c.reltype = t.oid) + + ELSE NULL + END) AS attrtypoids, + (CASE WHEN t.typtype = 'c' THEN + (SELECT + array_agg(ia.attname::text ORDER BY ia.attnum) + FROM + pg_attribute ia + INNER JOIN pg_class c + ON (ia.attrelid = c.oid) + WHERE + ia.attnum > 0 AND NOT ia.attisdropped + AND c.reltype = t.oid) + + ELSE NULL + END) AS attrnames + FROM + pg_catalog.pg_type AS t + INNER JOIN pg_catalog.pg_namespace ns ON ( + ns.oid = t.typnamespace) + LEFT JOIN pg_type elem_t ON ( + t.typlen = -1 AND + t.typelem != 0 AND + t.typelem = elem_t.oid + ) + LEFT JOIN pg_range range_t ON ( + t.oid = range_t.rngtypid + ) + LEFT JOIN pg_range multirange_t ON ( + t.oid = multirange_t.rngmultitypid + ) + ) +''' + + +INTRO_LOOKUP_TYPES = '''\ +WITH RECURSIVE typeinfo_tree( + oid, ns, name, kind, basetype, elemtype, elemdelim, + range_subtype, attrtypoids, attrnames, depth) +AS ( + SELECT + ti.oid, ti.ns, ti.name, ti.kind, ti.basetype, + ti.elemtype, ti.elemdelim, ti.range_subtype, + ti.attrtypoids, ti.attrnames, 0 + FROM + {typeinfo} AS ti + WHERE + ti.oid = any($1::oid[]) + + UNION ALL + + SELECT + ti.oid, ti.ns, ti.name, ti.kind, ti.basetype, + ti.elemtype, ti.elemdelim, ti.range_subtype, + ti.attrtypoids, ti.attrnames, tt.depth + 1 + FROM + {typeinfo} ti, + typeinfo_tree tt + WHERE + (tt.elemtype IS NOT NULL AND ti.oid = tt.elemtype) + OR (tt.attrtypoids IS NOT NULL AND ti.oid = any(tt.attrtypoids)) + OR (tt.range_subtype IS NOT NULL AND ti.oid = tt.range_subtype) + OR (tt.basetype IS NOT NULL AND ti.oid = tt.basetype) +) + +SELECT DISTINCT + *, + basetype::regtype::text AS basetype_name, + elemtype::regtype::text AS elemtype_name, + range_subtype::regtype::text AS range_subtype_name +FROM + typeinfo_tree +ORDER BY + depth DESC +'''.format(typeinfo=_TYPEINFO) + + +TYPE_BY_NAME = '''\ +SELECT + t.oid, + t.typelem AS elemtype, + t.typtype AS kind +FROM + pg_catalog.pg_type AS t + INNER JOIN pg_catalog.pg_namespace ns ON (ns.oid = t.typnamespace) +WHERE + t.typname = $1 AND ns.nspname = $2 +''' + + +TYPE_BY_OID = '''\ +SELECT + t.oid, + t.typelem AS elemtype, + t.typtype AS kind +FROM + pg_catalog.pg_type AS t +WHERE + t.oid = $1 +''' + + +# 'b' for a base type, 'd' for a domain, 'e' for enum. +SCALAR_TYPE_KINDS = (b'b', b'd', b'e') + + +def is_scalar_type(typeinfo) -> bool: + return ( + typeinfo['kind'] in SCALAR_TYPE_KINDS and + not typeinfo['elemtype'] + ) + + +def is_domain_type(typeinfo) -> bool: + return typeinfo['kind'] == b'd' + + +def is_composite_type(typeinfo) -> bool: + return typeinfo['kind'] == b'c' diff --git a/env/Lib/site-packages/asyncpg/pgproto/__init__.pxd b/env/Lib/site-packages/asyncpg/pgproto/__init__.pxd new file mode 100644 index 0000000..1df403c --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/__init__.pxd @@ -0,0 +1,5 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 diff --git a/env/Lib/site-packages/asyncpg/pgproto/__init__.py b/env/Lib/site-packages/asyncpg/pgproto/__init__.py new file mode 100644 index 0000000..1df403c --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/__init__.py @@ -0,0 +1,5 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 diff --git a/env/Lib/site-packages/asyncpg/pgproto/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/asyncpg/pgproto/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..d06c9c2 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/pgproto/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/pgproto/__pycache__/types.cpython-311.pyc b/env/Lib/site-packages/asyncpg/pgproto/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000..4ce98ee Binary files /dev/null and b/env/Lib/site-packages/asyncpg/pgproto/__pycache__/types.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/pgproto/buffer.pxd b/env/Lib/site-packages/asyncpg/pgproto/buffer.pxd new file mode 100644 index 0000000..c2d4c6e --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/buffer.pxd @@ -0,0 +1,136 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef class WriteBuffer: + cdef: + # Preallocated small buffer + bint _smallbuf_inuse + char _smallbuf[_BUFFER_INITIAL_SIZE] + + char *_buf + + # Allocated size + ssize_t _size + + # Length of data in the buffer + ssize_t _length + + # Number of memoryviews attached to the buffer + int _view_count + + # True is start_message was used + bint _message_mode + + cdef inline len(self): + return self._length + + cdef inline write_len_prefixed_utf8(self, str s): + return self.write_len_prefixed_bytes(s.encode('utf-8')) + + cdef inline _check_readonly(self) + cdef inline _ensure_alloced(self, ssize_t extra_length) + cdef _reallocate(self, ssize_t new_size) + cdef inline reset(self) + cdef inline start_message(self, char type) + cdef inline end_message(self) + cdef write_buffer(self, WriteBuffer buf) + cdef write_byte(self, char b) + cdef write_bytes(self, bytes data) + cdef write_len_prefixed_buffer(self, WriteBuffer buf) + cdef write_len_prefixed_bytes(self, bytes data) + cdef write_bytestring(self, bytes string) + cdef write_str(self, str string, str encoding) + cdef write_frbuf(self, FRBuffer *buf) + cdef write_cstr(self, const char *data, ssize_t len) + cdef write_int16(self, int16_t i) + cdef write_int32(self, int32_t i) + cdef write_int64(self, int64_t i) + cdef write_float(self, float f) + cdef write_double(self, double d) + + @staticmethod + cdef WriteBuffer new_message(char type) + + @staticmethod + cdef WriteBuffer new() + + +ctypedef const char * (*try_consume_message_method)(object, ssize_t*) +ctypedef int32_t (*take_message_type_method)(object, char) except -1 +ctypedef int32_t (*take_message_method)(object) except -1 +ctypedef char (*get_message_type_method)(object) + + +cdef class ReadBuffer: + cdef: + # A deque of buffers (bytes objects) + object _bufs + object _bufs_append + object _bufs_popleft + + # A pointer to the first buffer in `_bufs` + bytes _buf0 + + # A pointer to the previous first buffer + # (used to prolong the life of _buf0 when using + # methods like _try_read_bytes) + bytes _buf0_prev + + # Number of buffers in `_bufs` + int32_t _bufs_len + + # A read position in the first buffer in `_bufs` + ssize_t _pos0 + + # Length of the first buffer in `_bufs` + ssize_t _len0 + + # A total number of buffered bytes in ReadBuffer + ssize_t _length + + char _current_message_type + int32_t _current_message_len + ssize_t _current_message_len_unread + bint _current_message_ready + + cdef inline len(self): + return self._length + + cdef inline char get_message_type(self): + return self._current_message_type + + cdef inline int32_t get_message_length(self): + return self._current_message_len + + cdef feed_data(self, data) + cdef inline _ensure_first_buf(self) + cdef _switch_to_next_buf(self) + cdef inline char read_byte(self) except? -1 + cdef inline const char* _try_read_bytes(self, ssize_t nbytes) + cdef inline _read_into(self, char *buf, ssize_t nbytes) + cdef inline _read_and_discard(self, ssize_t nbytes) + cdef bytes read_bytes(self, ssize_t nbytes) + cdef bytes read_len_prefixed_bytes(self) + cdef str read_len_prefixed_utf8(self) + cdef read_uuid(self) + cdef inline int64_t read_int64(self) except? -1 + cdef inline int32_t read_int32(self) except? -1 + cdef inline int16_t read_int16(self) except? -1 + cdef inline read_null_str(self) + cdef int32_t take_message(self) except -1 + cdef inline int32_t take_message_type(self, char mtype) except -1 + cdef int32_t put_message(self) except -1 + cdef inline const char* try_consume_message(self, ssize_t* len) + cdef bytes consume_message(self) + cdef discard_message(self) + cdef redirect_messages(self, WriteBuffer buf, char mtype, int stop_at=?) + cdef bytearray consume_messages(self, char mtype) + cdef finish_message(self) + cdef inline _finish_message(self) + + @staticmethod + cdef ReadBuffer new_message_parser(object data) diff --git a/env/Lib/site-packages/asyncpg/pgproto/buffer.pyx b/env/Lib/site-packages/asyncpg/pgproto/buffer.pyx new file mode 100644 index 0000000..e05d4c7 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/buffer.pyx @@ -0,0 +1,817 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from libc.string cimport memcpy + +import collections + +class BufferError(Exception): + pass + +@cython.no_gc_clear +@cython.final +@cython.freelist(_BUFFER_FREELIST_SIZE) +cdef class WriteBuffer: + + def __cinit__(self): + self._smallbuf_inuse = True + self._buf = self._smallbuf + self._size = _BUFFER_INITIAL_SIZE + self._length = 0 + self._message_mode = 0 + + def __dealloc__(self): + if self._buf is not NULL and not self._smallbuf_inuse: + cpython.PyMem_Free(self._buf) + self._buf = NULL + self._size = 0 + + if self._view_count: + raise BufferError( + 'Deallocating buffer with attached memoryviews') + + def __getbuffer__(self, Py_buffer *buffer, int flags): + self._view_count += 1 + + cpython.PyBuffer_FillInfo( + buffer, self, self._buf, self._length, + 1, # read-only + flags) + + def __releasebuffer__(self, Py_buffer *buffer): + self._view_count -= 1 + + cdef inline _check_readonly(self): + if self._view_count: + raise BufferError('the buffer is in read-only mode') + + cdef inline _ensure_alloced(self, ssize_t extra_length): + cdef ssize_t new_size = extra_length + self._length + + if new_size > self._size: + self._reallocate(new_size) + + cdef _reallocate(self, ssize_t new_size): + cdef char *new_buf + + if new_size < _BUFFER_MAX_GROW: + new_size = _BUFFER_MAX_GROW + else: + # Add a little extra + new_size += _BUFFER_INITIAL_SIZE + + if self._smallbuf_inuse: + new_buf = cpython.PyMem_Malloc( + sizeof(char) * new_size) + if new_buf is NULL: + self._buf = NULL + self._size = 0 + self._length = 0 + raise MemoryError + memcpy(new_buf, self._buf, self._size) + self._size = new_size + self._buf = new_buf + self._smallbuf_inuse = False + else: + new_buf = cpython.PyMem_Realloc( + self._buf, new_size) + if new_buf is NULL: + cpython.PyMem_Free(self._buf) + self._buf = NULL + self._size = 0 + self._length = 0 + raise MemoryError + self._buf = new_buf + self._size = new_size + + cdef inline start_message(self, char type): + if self._length != 0: + raise BufferError( + 'cannot start_message for a non-empty buffer') + self._ensure_alloced(5) + self._message_mode = 1 + self._buf[0] = type + self._length = 5 + + cdef inline end_message(self): + # "length-1" to exclude the message type byte + cdef ssize_t mlen = self._length - 1 + + self._check_readonly() + if not self._message_mode: + raise BufferError( + 'end_message can only be called with start_message') + if self._length < 5: + raise BufferError('end_message: buffer is too small') + if mlen > _MAXINT32: + raise BufferError('end_message: message is too large') + + hton.pack_int32(&self._buf[1], mlen) + return self + + cdef inline reset(self): + self._length = 0 + self._message_mode = 0 + + cdef write_buffer(self, WriteBuffer buf): + self._check_readonly() + + if not buf._length: + return + + self._ensure_alloced(buf._length) + memcpy(self._buf + self._length, + buf._buf, + buf._length) + self._length += buf._length + + cdef write_byte(self, char b): + self._check_readonly() + + self._ensure_alloced(1) + self._buf[self._length] = b + self._length += 1 + + cdef write_bytes(self, bytes data): + cdef char* buf + cdef ssize_t len + + cpython.PyBytes_AsStringAndSize(data, &buf, &len) + self.write_cstr(buf, len) + + cdef write_bytestring(self, bytes string): + cdef char* buf + cdef ssize_t len + + cpython.PyBytes_AsStringAndSize(string, &buf, &len) + # PyBytes_AsStringAndSize returns a null-terminated buffer, + # but the null byte is not counted in len. hence the + 1 + self.write_cstr(buf, len + 1) + + cdef write_str(self, str string, str encoding): + self.write_bytestring(string.encode(encoding)) + + cdef write_len_prefixed_buffer(self, WriteBuffer buf): + # Write a length-prefixed (not NULL-terminated) bytes sequence. + self.write_int32(buf.len()) + self.write_buffer(buf) + + cdef write_len_prefixed_bytes(self, bytes data): + # Write a length-prefixed (not NULL-terminated) bytes sequence. + cdef: + char *buf + ssize_t size + + cpython.PyBytes_AsStringAndSize(data, &buf, &size) + if size > _MAXINT32: + raise BufferError('string is too large') + # `size` does not account for the NULL at the end. + self.write_int32(size) + self.write_cstr(buf, size) + + cdef write_frbuf(self, FRBuffer *buf): + cdef: + ssize_t buf_len = buf.len + if buf_len > 0: + self.write_cstr(frb_read_all(buf), buf_len) + + cdef write_cstr(self, const char *data, ssize_t len): + self._check_readonly() + self._ensure_alloced(len) + + memcpy(self._buf + self._length, data, len) + self._length += len + + cdef write_int16(self, int16_t i): + self._check_readonly() + self._ensure_alloced(2) + + hton.pack_int16(&self._buf[self._length], i) + self._length += 2 + + cdef write_int32(self, int32_t i): + self._check_readonly() + self._ensure_alloced(4) + + hton.pack_int32(&self._buf[self._length], i) + self._length += 4 + + cdef write_int64(self, int64_t i): + self._check_readonly() + self._ensure_alloced(8) + + hton.pack_int64(&self._buf[self._length], i) + self._length += 8 + + cdef write_float(self, float f): + self._check_readonly() + self._ensure_alloced(4) + + hton.pack_float(&self._buf[self._length], f) + self._length += 4 + + cdef write_double(self, double d): + self._check_readonly() + self._ensure_alloced(8) + + hton.pack_double(&self._buf[self._length], d) + self._length += 8 + + @staticmethod + cdef WriteBuffer new_message(char type): + cdef WriteBuffer buf + buf = WriteBuffer.__new__(WriteBuffer) + buf.start_message(type) + return buf + + @staticmethod + cdef WriteBuffer new(): + cdef WriteBuffer buf + buf = WriteBuffer.__new__(WriteBuffer) + return buf + + +@cython.no_gc_clear +@cython.final +@cython.freelist(_BUFFER_FREELIST_SIZE) +cdef class ReadBuffer: + + def __cinit__(self): + self._bufs = collections.deque() + self._bufs_append = self._bufs.append + self._bufs_popleft = self._bufs.popleft + self._bufs_len = 0 + self._buf0 = None + self._buf0_prev = None + self._pos0 = 0 + self._len0 = 0 + self._length = 0 + + self._current_message_type = 0 + self._current_message_len = 0 + self._current_message_len_unread = 0 + self._current_message_ready = 0 + + cdef feed_data(self, data): + cdef: + ssize_t dlen + bytes data_bytes + + if not cpython.PyBytes_CheckExact(data): + if cpythonx.PyByteArray_CheckExact(data): + # ProactorEventLoop in Python 3.10+ seems to be sending + # bytearray objects instead of bytes. Handle this here + # to avoid duplicating this check in every data_received(). + data = bytes(data) + else: + raise BufferError( + 'feed_data: a bytes or bytearray object expected') + + # Uncomment the below code to test code paths that + # read single int/str/bytes sequences are split over + # multiple received buffers. + # + # ll = 107 + # if len(data) > ll: + # self.feed_data(data[:ll]) + # self.feed_data(data[ll:]) + # return + + data_bytes = data + + dlen = cpython.Py_SIZE(data_bytes) + if dlen == 0: + # EOF? + return + + self._bufs_append(data_bytes) + self._length += dlen + + if self._bufs_len == 0: + # First buffer + self._len0 = dlen + self._buf0 = data_bytes + + self._bufs_len += 1 + + cdef inline _ensure_first_buf(self): + if PG_DEBUG: + if self._len0 == 0: + raise BufferError('empty first buffer') + if self._length == 0: + raise BufferError('empty buffer') + + if self._pos0 == self._len0: + self._switch_to_next_buf() + + cdef _switch_to_next_buf(self): + # The first buffer is fully read, discard it + self._bufs_popleft() + self._bufs_len -= 1 + + # Shouldn't fail, since we've checked that `_length >= 1` + # in _ensure_first_buf() + self._buf0_prev = self._buf0 + self._buf0 = self._bufs[0] + + self._pos0 = 0 + self._len0 = len(self._buf0) + + if PG_DEBUG: + if self._len0 < 1: + raise BufferError( + 'debug: second buffer of ReadBuffer is empty') + + cdef inline const char* _try_read_bytes(self, ssize_t nbytes): + # Try to read *nbytes* from the first buffer. + # + # Returns pointer to data if there is at least *nbytes* + # in the buffer, NULL otherwise. + # + # Important: caller must call _ensure_first_buf() prior + # to calling try_read_bytes, and must not overread + + cdef: + const char *result + + if PG_DEBUG: + if nbytes > self._length: + return NULL + + if self._current_message_ready: + if self._current_message_len_unread < nbytes: + return NULL + + if self._pos0 + nbytes <= self._len0: + result = cpython.PyBytes_AS_STRING(self._buf0) + result += self._pos0 + self._pos0 += nbytes + self._length -= nbytes + if self._current_message_ready: + self._current_message_len_unread -= nbytes + return result + else: + return NULL + + cdef inline _read_into(self, char *buf, ssize_t nbytes): + cdef: + ssize_t nread + char *buf0 + + while True: + buf0 = cpython.PyBytes_AS_STRING(self._buf0) + + if self._pos0 + nbytes > self._len0: + nread = self._len0 - self._pos0 + memcpy(buf, buf0 + self._pos0, nread) + self._pos0 = self._len0 + self._length -= nread + nbytes -= nread + buf += nread + self._ensure_first_buf() + + else: + memcpy(buf, buf0 + self._pos0, nbytes) + self._pos0 += nbytes + self._length -= nbytes + break + + cdef inline _read_and_discard(self, ssize_t nbytes): + cdef: + ssize_t nread + + self._ensure_first_buf() + while True: + if self._pos0 + nbytes > self._len0: + nread = self._len0 - self._pos0 + self._pos0 = self._len0 + self._length -= nread + nbytes -= nread + self._ensure_first_buf() + + else: + self._pos0 += nbytes + self._length -= nbytes + break + + cdef bytes read_bytes(self, ssize_t nbytes): + cdef: + bytes result + ssize_t nread + const char *cbuf + char *buf + + self._ensure_first_buf() + cbuf = self._try_read_bytes(nbytes) + if cbuf != NULL: + return cpython.PyBytes_FromStringAndSize(cbuf, nbytes) + + if nbytes > self._length: + raise BufferError( + 'not enough data to read {} bytes'.format(nbytes)) + + if self._current_message_ready: + self._current_message_len_unread -= nbytes + if self._current_message_len_unread < 0: + raise BufferError('buffer overread') + + result = cpython.PyBytes_FromStringAndSize(NULL, nbytes) + buf = cpython.PyBytes_AS_STRING(result) + self._read_into(buf, nbytes) + return result + + cdef bytes read_len_prefixed_bytes(self): + cdef int32_t size = self.read_int32() + if size < 0: + raise BufferError( + 'negative length for a len-prefixed bytes value') + if size == 0: + return b'' + return self.read_bytes(size) + + cdef str read_len_prefixed_utf8(self): + cdef: + int32_t size + const char *cbuf + + size = self.read_int32() + if size < 0: + raise BufferError( + 'negative length for a len-prefixed bytes value') + + if size == 0: + return '' + + self._ensure_first_buf() + cbuf = self._try_read_bytes(size) + if cbuf != NULL: + return cpython.PyUnicode_DecodeUTF8(cbuf, size, NULL) + else: + return self.read_bytes(size).decode('utf-8') + + cdef read_uuid(self): + cdef: + bytes mem + const char *cbuf + + self._ensure_first_buf() + cbuf = self._try_read_bytes(16) + if cbuf != NULL: + return pg_uuid_from_buf(cbuf) + else: + return pg_UUID(self.read_bytes(16)) + + cdef inline char read_byte(self) except? -1: + cdef const char *first_byte + + if PG_DEBUG: + if not self._buf0: + raise BufferError( + 'debug: first buffer of ReadBuffer is empty') + + self._ensure_first_buf() + first_byte = self._try_read_bytes(1) + if first_byte is NULL: + raise BufferError('not enough data to read one byte') + + return first_byte[0] + + cdef inline int64_t read_int64(self) except? -1: + cdef: + bytes mem + const char *cbuf + + self._ensure_first_buf() + cbuf = self._try_read_bytes(8) + if cbuf != NULL: + return hton.unpack_int64(cbuf) + else: + mem = self.read_bytes(8) + return hton.unpack_int64(cpython.PyBytes_AS_STRING(mem)) + + cdef inline int32_t read_int32(self) except? -1: + cdef: + bytes mem + const char *cbuf + + self._ensure_first_buf() + cbuf = self._try_read_bytes(4) + if cbuf != NULL: + return hton.unpack_int32(cbuf) + else: + mem = self.read_bytes(4) + return hton.unpack_int32(cpython.PyBytes_AS_STRING(mem)) + + cdef inline int16_t read_int16(self) except? -1: + cdef: + bytes mem + const char *cbuf + + self._ensure_first_buf() + cbuf = self._try_read_bytes(2) + if cbuf != NULL: + return hton.unpack_int16(cbuf) + else: + mem = self.read_bytes(2) + return hton.unpack_int16(cpython.PyBytes_AS_STRING(mem)) + + cdef inline read_null_str(self): + if not self._current_message_ready: + raise BufferError( + 'read_null_str only works when the message guaranteed ' + 'to be in the buffer') + + cdef: + ssize_t pos + ssize_t nread + bytes result + const char *buf + const char *buf_start + + self._ensure_first_buf() + + buf_start = cpython.PyBytes_AS_STRING(self._buf0) + buf = buf_start + self._pos0 + while buf - buf_start < self._len0: + if buf[0] == 0: + pos = buf - buf_start + nread = pos - self._pos0 + buf = self._try_read_bytes(nread + 1) + if buf != NULL: + return cpython.PyBytes_FromStringAndSize(buf, nread) + else: + break + else: + buf += 1 + + result = b'' + while True: + pos = self._buf0.find(b'\x00', self._pos0) + if pos >= 0: + result += self._buf0[self._pos0 : pos] + nread = pos - self._pos0 + 1 + self._pos0 = pos + 1 + self._length -= nread + + self._current_message_len_unread -= nread + if self._current_message_len_unread < 0: + raise BufferError( + 'read_null_str: buffer overread') + + return result + + else: + result += self._buf0[self._pos0:] + nread = self._len0 - self._pos0 + self._pos0 = self._len0 + self._length -= nread + + self._current_message_len_unread -= nread + if self._current_message_len_unread < 0: + raise BufferError( + 'read_null_str: buffer overread') + + self._ensure_first_buf() + + cdef int32_t take_message(self) except -1: + cdef: + const char *cbuf + + if self._current_message_ready: + return 1 + + if self._current_message_type == 0: + if self._length < 1: + return 0 + self._ensure_first_buf() + cbuf = self._try_read_bytes(1) + if cbuf == NULL: + raise BufferError( + 'failed to read one byte on a non-empty buffer') + self._current_message_type = cbuf[0] + + if self._current_message_len == 0: + if self._length < 4: + return 0 + + self._ensure_first_buf() + cbuf = self._try_read_bytes(4) + if cbuf != NULL: + self._current_message_len = hton.unpack_int32(cbuf) + else: + self._current_message_len = self.read_int32() + + self._current_message_len_unread = self._current_message_len - 4 + + if self._length < self._current_message_len_unread: + return 0 + + self._current_message_ready = 1 + return 1 + + cdef inline int32_t take_message_type(self, char mtype) except -1: + cdef const char *buf0 + + if self._current_message_ready: + return self._current_message_type == mtype + elif self._length >= 1: + self._ensure_first_buf() + buf0 = cpython.PyBytes_AS_STRING(self._buf0) + + return buf0[self._pos0] == mtype and self.take_message() + else: + return 0 + + cdef int32_t put_message(self) except -1: + if not self._current_message_ready: + raise BufferError( + 'cannot put message: no message taken') + self._current_message_ready = False + return 0 + + cdef inline const char* try_consume_message(self, ssize_t* len): + cdef: + ssize_t buf_len + const char *buf + + if not self._current_message_ready: + return NULL + + self._ensure_first_buf() + buf_len = self._current_message_len_unread + buf = self._try_read_bytes(buf_len) + if buf != NULL: + len[0] = buf_len + self._finish_message() + return buf + + cdef discard_message(self): + if not self._current_message_ready: + raise BufferError('no message to discard') + if self._current_message_len_unread > 0: + self._read_and_discard(self._current_message_len_unread) + self._current_message_len_unread = 0 + self._finish_message() + + cdef bytes consume_message(self): + if not self._current_message_ready: + raise BufferError('no message to consume') + if self._current_message_len_unread > 0: + mem = self.read_bytes(self._current_message_len_unread) + else: + mem = b'' + self._finish_message() + return mem + + cdef redirect_messages(self, WriteBuffer buf, char mtype, + int stop_at=0): + if not self._current_message_ready: + raise BufferError( + 'consume_full_messages called on a buffer without a ' + 'complete first message') + if mtype != self._current_message_type: + raise BufferError( + 'consume_full_messages called with a wrong mtype') + if self._current_message_len_unread != self._current_message_len - 4: + raise BufferError( + 'consume_full_messages called on a partially read message') + + cdef: + const char* cbuf + ssize_t cbuf_len + int32_t msg_len + ssize_t new_pos0 + ssize_t pos_delta + int32_t done + + while True: + buf.write_byte(mtype) + buf.write_int32(self._current_message_len) + + cbuf = self.try_consume_message(&cbuf_len) + if cbuf != NULL: + buf.write_cstr(cbuf, cbuf_len) + else: + buf.write_bytes(self.consume_message()) + + if self._length > 0: + self._ensure_first_buf() + else: + return + + if stop_at and buf._length >= stop_at: + return + + # Fast path: exhaust buf0 as efficiently as possible. + if self._pos0 + 5 <= self._len0: + cbuf = cpython.PyBytes_AS_STRING(self._buf0) + new_pos0 = self._pos0 + cbuf_len = self._len0 + + done = 0 + # Scan the first buffer and find the position of the + # end of the last "mtype" message. + while new_pos0 + 5 <= cbuf_len: + if (cbuf + new_pos0)[0] != mtype: + done = 1 + break + if (stop_at and + (buf._length + new_pos0 - self._pos0) > stop_at): + done = 1 + break + msg_len = hton.unpack_int32(cbuf + new_pos0 + 1) + 1 + if new_pos0 + msg_len > cbuf_len: + break + new_pos0 += msg_len + + if new_pos0 != self._pos0: + assert self._pos0 < new_pos0 <= self._len0 + + pos_delta = new_pos0 - self._pos0 + buf.write_cstr( + cbuf + self._pos0, + pos_delta) + + self._pos0 = new_pos0 + self._length -= pos_delta + + assert self._length >= 0 + + if done: + # The next message is of a different type. + return + + # Back to slow path. + if not self.take_message_type(mtype): + return + + cdef bytearray consume_messages(self, char mtype): + """Consume consecutive messages of the same type.""" + cdef: + char *buf + ssize_t nbytes + ssize_t total_bytes = 0 + bytearray result + + if not self.take_message_type(mtype): + return None + + # consume_messages is a volume-oriented method, so + # we assume that the remainder of the buffer will contain + # messages of the requested type. + result = cpythonx.PyByteArray_FromStringAndSize(NULL, self._length) + buf = cpythonx.PyByteArray_AsString(result) + + while self.take_message_type(mtype): + self._ensure_first_buf() + nbytes = self._current_message_len_unread + self._read_into(buf, nbytes) + buf += nbytes + total_bytes += nbytes + self._finish_message() + + # Clamp the result to an actual size read. + cpythonx.PyByteArray_Resize(result, total_bytes) + + return result + + cdef finish_message(self): + if self._current_message_type == 0 or not self._current_message_ready: + # The message has already been finished (e.g by consume_message()), + # or has been put back by put_message(). + return + + if self._current_message_len_unread: + if PG_DEBUG: + mtype = chr(self._current_message_type) + + discarded = self.consume_message() + + if PG_DEBUG: + print('!!! discarding message {!r} unread data: {!r}'.format( + mtype, + discarded)) + + self._finish_message() + + cdef inline _finish_message(self): + self._current_message_type = 0 + self._current_message_len = 0 + self._current_message_ready = 0 + self._current_message_len_unread = 0 + + @staticmethod + cdef ReadBuffer new_message_parser(object data): + cdef ReadBuffer buf + + buf = ReadBuffer.__new__(ReadBuffer) + buf.feed_data(data) + + buf._current_message_ready = 1 + buf._current_message_len_unread = buf._len0 + + return buf diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/__init__.pxd b/env/Lib/site-packages/asyncpg/pgproto/codecs/__init__.pxd new file mode 100644 index 0000000..2dbcbd3 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/__init__.pxd @@ -0,0 +1,157 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef class CodecContext: + + cpdef get_text_codec(self) + cdef is_encoding_utf8(self) + cpdef get_json_decoder(self) + cdef is_decoding_json(self) + cpdef get_json_encoder(self) + cdef is_encoding_json(self) + + +ctypedef object (*encode_func)(CodecContext settings, + WriteBuffer buf, + object obj) + +ctypedef object (*decode_func)(CodecContext settings, + FRBuffer *buf) + + +# Datetime +cdef date_encode(CodecContext settings, WriteBuffer buf, obj) +cdef date_decode(CodecContext settings, FRBuffer * buf) +cdef date_encode_tuple(CodecContext settings, WriteBuffer buf, obj) +cdef date_decode_tuple(CodecContext settings, FRBuffer * buf) +cdef timestamp_encode(CodecContext settings, WriteBuffer buf, obj) +cdef timestamp_decode(CodecContext settings, FRBuffer * buf) +cdef timestamp_encode_tuple(CodecContext settings, WriteBuffer buf, obj) +cdef timestamp_decode_tuple(CodecContext settings, FRBuffer * buf) +cdef timestamptz_encode(CodecContext settings, WriteBuffer buf, obj) +cdef timestamptz_decode(CodecContext settings, FRBuffer * buf) +cdef time_encode(CodecContext settings, WriteBuffer buf, obj) +cdef time_decode(CodecContext settings, FRBuffer * buf) +cdef time_encode_tuple(CodecContext settings, WriteBuffer buf, obj) +cdef time_decode_tuple(CodecContext settings, FRBuffer * buf) +cdef timetz_encode(CodecContext settings, WriteBuffer buf, obj) +cdef timetz_decode(CodecContext settings, FRBuffer * buf) +cdef timetz_encode_tuple(CodecContext settings, WriteBuffer buf, obj) +cdef timetz_decode_tuple(CodecContext settings, FRBuffer * buf) +cdef interval_encode(CodecContext settings, WriteBuffer buf, obj) +cdef interval_decode(CodecContext settings, FRBuffer * buf) +cdef interval_encode_tuple(CodecContext settings, WriteBuffer buf, tuple obj) +cdef interval_decode_tuple(CodecContext settings, FRBuffer * buf) + + +# Bits +cdef bits_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef bits_decode(CodecContext settings, FRBuffer * buf) + + +# Bools +cdef bool_encode(CodecContext settings, WriteBuffer buf, obj) +cdef bool_decode(CodecContext settings, FRBuffer * buf) + + +# Geometry +cdef box_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef box_decode(CodecContext settings, FRBuffer * buf) +cdef line_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef line_decode(CodecContext settings, FRBuffer * buf) +cdef lseg_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef lseg_decode(CodecContext settings, FRBuffer * buf) +cdef point_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef point_decode(CodecContext settings, FRBuffer * buf) +cdef path_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef path_decode(CodecContext settings, FRBuffer * buf) +cdef poly_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef poly_decode(CodecContext settings, FRBuffer * buf) +cdef circle_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef circle_decode(CodecContext settings, FRBuffer * buf) + + +# Hstore +cdef hstore_encode(CodecContext settings, WriteBuffer buf, obj) +cdef hstore_decode(CodecContext settings, FRBuffer * buf) + + +# Ints +cdef int2_encode(CodecContext settings, WriteBuffer buf, obj) +cdef int2_decode(CodecContext settings, FRBuffer * buf) +cdef int4_encode(CodecContext settings, WriteBuffer buf, obj) +cdef int4_decode(CodecContext settings, FRBuffer * buf) +cdef uint4_encode(CodecContext settings, WriteBuffer buf, obj) +cdef uint4_decode(CodecContext settings, FRBuffer * buf) +cdef int8_encode(CodecContext settings, WriteBuffer buf, obj) +cdef int8_decode(CodecContext settings, FRBuffer * buf) +cdef uint8_encode(CodecContext settings, WriteBuffer buf, obj) +cdef uint8_decode(CodecContext settings, FRBuffer * buf) + + +# Floats +cdef float4_encode(CodecContext settings, WriteBuffer buf, obj) +cdef float4_decode(CodecContext settings, FRBuffer * buf) +cdef float8_encode(CodecContext settings, WriteBuffer buf, obj) +cdef float8_decode(CodecContext settings, FRBuffer * buf) + + +# JSON +cdef jsonb_encode(CodecContext settings, WriteBuffer buf, obj) +cdef jsonb_decode(CodecContext settings, FRBuffer * buf) + + +# JSON path +cdef jsonpath_encode(CodecContext settings, WriteBuffer buf, obj) +cdef jsonpath_decode(CodecContext settings, FRBuffer * buf) + + +# Text +cdef as_pg_string_and_size( + CodecContext settings, obj, char **cstr, ssize_t *size) +cdef text_encode(CodecContext settings, WriteBuffer buf, obj) +cdef text_decode(CodecContext settings, FRBuffer * buf) + +# Bytea +cdef bytea_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef bytea_decode(CodecContext settings, FRBuffer * buf) + + +# UUID +cdef uuid_encode(CodecContext settings, WriteBuffer wbuf, obj) +cdef uuid_decode(CodecContext settings, FRBuffer * buf) + + +# Numeric +cdef numeric_encode_text(CodecContext settings, WriteBuffer buf, obj) +cdef numeric_decode_text(CodecContext settings, FRBuffer * buf) +cdef numeric_encode_binary(CodecContext settings, WriteBuffer buf, obj) +cdef numeric_decode_binary(CodecContext settings, FRBuffer * buf) +cdef numeric_decode_binary_ex(CodecContext settings, FRBuffer * buf, + bint trail_fract_zero) + + +# Void +cdef void_encode(CodecContext settings, WriteBuffer buf, obj) +cdef void_decode(CodecContext settings, FRBuffer * buf) + + +# tid +cdef tid_encode(CodecContext settings, WriteBuffer buf, obj) +cdef tid_decode(CodecContext settings, FRBuffer * buf) + + +# Network +cdef cidr_encode(CodecContext settings, WriteBuffer buf, obj) +cdef cidr_decode(CodecContext settings, FRBuffer * buf) +cdef inet_encode(CodecContext settings, WriteBuffer buf, obj) +cdef inet_decode(CodecContext settings, FRBuffer * buf) + + +# pg_snapshot +cdef pg_snapshot_encode(CodecContext settings, WriteBuffer buf, obj) +cdef pg_snapshot_decode(CodecContext settings, FRBuffer * buf) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/bits.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/bits.pyx new file mode 100644 index 0000000..14f7bb0 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/bits.pyx @@ -0,0 +1,47 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef bits_encode(CodecContext settings, WriteBuffer wbuf, obj): + cdef: + Py_buffer pybuf + bint pybuf_used = False + char *buf + ssize_t len + ssize_t bitlen + + if cpython.PyBytes_CheckExact(obj): + buf = cpython.PyBytes_AS_STRING(obj) + len = cpython.Py_SIZE(obj) + bitlen = len * 8 + elif isinstance(obj, pgproto_types.BitString): + cpython.PyBytes_AsStringAndSize(obj.bytes, &buf, &len) + bitlen = obj.__len__() + else: + cpython.PyObject_GetBuffer(obj, &pybuf, cpython.PyBUF_SIMPLE) + pybuf_used = True + buf = pybuf.buf + len = pybuf.len + bitlen = len * 8 + + try: + if bitlen > _MAXINT32: + raise ValueError('bit value too long') + wbuf.write_int32(4 + len) + wbuf.write_int32(bitlen) + wbuf.write_cstr(buf, len) + finally: + if pybuf_used: + cpython.PyBuffer_Release(&pybuf) + + +cdef bits_decode(CodecContext settings, FRBuffer *buf): + cdef: + int32_t bitlen = hton.unpack_int32(frb_read(buf, 4)) + ssize_t buf_len = buf.len + + bytes_ = cpython.PyBytes_FromStringAndSize(frb_read_all(buf), buf_len) + return pgproto_types.BitString.frombytes(bytes_, bitlen) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/bytea.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/bytea.pyx new file mode 100644 index 0000000..1581825 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/bytea.pyx @@ -0,0 +1,34 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef bytea_encode(CodecContext settings, WriteBuffer wbuf, obj): + cdef: + Py_buffer pybuf + bint pybuf_used = False + char *buf + ssize_t len + + if cpython.PyBytes_CheckExact(obj): + buf = cpython.PyBytes_AS_STRING(obj) + len = cpython.Py_SIZE(obj) + else: + cpython.PyObject_GetBuffer(obj, &pybuf, cpython.PyBUF_SIMPLE) + pybuf_used = True + buf = pybuf.buf + len = pybuf.len + + try: + wbuf.write_int32(len) + wbuf.write_cstr(buf, len) + finally: + if pybuf_used: + cpython.PyBuffer_Release(&pybuf) + + +cdef bytea_decode(CodecContext settings, FRBuffer *buf): + cdef ssize_t buf_len = buf.len + return cpython.PyBytes_FromStringAndSize(frb_read_all(buf), buf_len) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/context.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/context.pyx new file mode 100644 index 0000000..c4d4416 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/context.pyx @@ -0,0 +1,26 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef class CodecContext: + + cpdef get_text_codec(self): + raise NotImplementedError + + cdef is_encoding_utf8(self): + raise NotImplementedError + + cpdef get_json_decoder(self): + raise NotImplementedError + + cdef is_decoding_json(self): + return False + + cpdef get_json_encoder(self): + raise NotImplementedError + + cdef is_encoding_json(self): + return False diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/datetime.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/datetime.pyx new file mode 100644 index 0000000..bed0b9e --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/datetime.pyx @@ -0,0 +1,423 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cimport cpython.datetime +import datetime + +cpython.datetime.import_datetime() + +utc = datetime.timezone.utc +date_from_ordinal = datetime.date.fromordinal +timedelta = datetime.timedelta + +pg_epoch_datetime = datetime.datetime(2000, 1, 1) +cdef int32_t pg_epoch_datetime_ts = \ + cpython.PyLong_AsLong(int(pg_epoch_datetime.timestamp())) + +pg_epoch_datetime_utc = datetime.datetime(2000, 1, 1, tzinfo=utc) +cdef int32_t pg_epoch_datetime_utc_ts = \ + cpython.PyLong_AsLong(int(pg_epoch_datetime_utc.timestamp())) + +pg_epoch_date = datetime.date(2000, 1, 1) +cdef int32_t pg_date_offset_ord = \ + cpython.PyLong_AsLong(pg_epoch_date.toordinal()) + +# Binary representations of infinity for datetimes. +cdef int64_t pg_time64_infinity = 0x7fffffffffffffff +cdef int64_t pg_time64_negative_infinity = 0x8000000000000000 +cdef int32_t pg_date_infinity = 0x7fffffff +cdef int32_t pg_date_negative_infinity = 0x80000000 + +infinity_datetime = datetime.datetime( + datetime.MAXYEAR, 12, 31, 23, 59, 59, 999999) + +cdef int32_t infinity_datetime_ord = cpython.PyLong_AsLong( + infinity_datetime.toordinal()) + +cdef int64_t infinity_datetime_ts = 252455615999999999 + +negative_infinity_datetime = datetime.datetime( + datetime.MINYEAR, 1, 1, 0, 0, 0, 0) + +cdef int32_t negative_infinity_datetime_ord = cpython.PyLong_AsLong( + negative_infinity_datetime.toordinal()) + +cdef int64_t negative_infinity_datetime_ts = -63082281600000000 + +infinity_date = datetime.date(datetime.MAXYEAR, 12, 31) + +cdef int32_t infinity_date_ord = cpython.PyLong_AsLong( + infinity_date.toordinal()) + +negative_infinity_date = datetime.date(datetime.MINYEAR, 1, 1) + +cdef int32_t negative_infinity_date_ord = cpython.PyLong_AsLong( + negative_infinity_date.toordinal()) + + +cdef inline _local_timezone(): + d = datetime.datetime.now(datetime.timezone.utc).astimezone() + return datetime.timezone(d.utcoffset()) + + +cdef inline _encode_time(WriteBuffer buf, int64_t seconds, + int32_t microseconds): + # XXX: add support for double timestamps + # int64 timestamps, + cdef int64_t ts = seconds * 1000000 + microseconds + + if ts == infinity_datetime_ts: + buf.write_int64(pg_time64_infinity) + elif ts == negative_infinity_datetime_ts: + buf.write_int64(pg_time64_negative_infinity) + else: + buf.write_int64(ts) + + +cdef inline int32_t _decode_time(FRBuffer *buf, int64_t *seconds, + int32_t *microseconds): + cdef int64_t ts = hton.unpack_int64(frb_read(buf, 8)) + + if ts == pg_time64_infinity: + return 1 + elif ts == pg_time64_negative_infinity: + return -1 + else: + seconds[0] = ts // 1000000 + microseconds[0] = (ts % 1000000) + return 0 + + +cdef date_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + int32_t ordinal = cpython.PyLong_AsLong(obj.toordinal()) + int32_t pg_ordinal + + if ordinal == infinity_date_ord: + pg_ordinal = pg_date_infinity + elif ordinal == negative_infinity_date_ord: + pg_ordinal = pg_date_negative_infinity + else: + pg_ordinal = ordinal - pg_date_offset_ord + + buf.write_int32(4) + buf.write_int32(pg_ordinal) + + +cdef date_encode_tuple(CodecContext settings, WriteBuffer buf, obj): + cdef: + int32_t pg_ordinal + + if len(obj) != 1: + raise ValueError( + 'date tuple encoder: expecting 1 element ' + 'in tuple, got {}'.format(len(obj))) + + pg_ordinal = obj[0] + buf.write_int32(4) + buf.write_int32(pg_ordinal) + + +cdef date_decode(CodecContext settings, FRBuffer *buf): + cdef int32_t pg_ordinal = hton.unpack_int32(frb_read(buf, 4)) + + if pg_ordinal == pg_date_infinity: + return infinity_date + elif pg_ordinal == pg_date_negative_infinity: + return negative_infinity_date + else: + return date_from_ordinal(pg_ordinal + pg_date_offset_ord) + + +cdef date_decode_tuple(CodecContext settings, FRBuffer *buf): + cdef int32_t pg_ordinal = hton.unpack_int32(frb_read(buf, 4)) + + return (pg_ordinal,) + + +cdef timestamp_encode(CodecContext settings, WriteBuffer buf, obj): + if not cpython.datetime.PyDateTime_Check(obj): + if cpython.datetime.PyDate_Check(obj): + obj = datetime.datetime(obj.year, obj.month, obj.day) + else: + raise TypeError( + 'expected a datetime.date or datetime.datetime instance, ' + 'got {!r}'.format(type(obj).__name__) + ) + + delta = obj - pg_epoch_datetime + cdef: + int64_t seconds = cpython.PyLong_AsLongLong(delta.days) * 86400 + \ + cpython.PyLong_AsLong(delta.seconds) + int32_t microseconds = cpython.PyLong_AsLong( + delta.microseconds) + + buf.write_int32(8) + _encode_time(buf, seconds, microseconds) + + +cdef timestamp_encode_tuple(CodecContext settings, WriteBuffer buf, obj): + cdef: + int64_t microseconds + + if len(obj) != 1: + raise ValueError( + 'timestamp tuple encoder: expecting 1 element ' + 'in tuple, got {}'.format(len(obj))) + + microseconds = obj[0] + + buf.write_int32(8) + buf.write_int64(microseconds) + + +cdef timestamp_decode(CodecContext settings, FRBuffer *buf): + cdef: + int64_t seconds = 0 + int32_t microseconds = 0 + int32_t inf = _decode_time(buf, &seconds, µseconds) + + if inf > 0: + # positive infinity + return infinity_datetime + elif inf < 0: + # negative infinity + return negative_infinity_datetime + else: + return pg_epoch_datetime.__add__( + timedelta(0, seconds, microseconds)) + + +cdef timestamp_decode_tuple(CodecContext settings, FRBuffer *buf): + cdef: + int64_t ts = hton.unpack_int64(frb_read(buf, 8)) + + return (ts,) + + +cdef timestamptz_encode(CodecContext settings, WriteBuffer buf, obj): + if not cpython.datetime.PyDateTime_Check(obj): + if cpython.datetime.PyDate_Check(obj): + obj = datetime.datetime(obj.year, obj.month, obj.day, + tzinfo=_local_timezone()) + else: + raise TypeError( + 'expected a datetime.date or datetime.datetime instance, ' + 'got {!r}'.format(type(obj).__name__) + ) + + buf.write_int32(8) + + if obj == infinity_datetime: + buf.write_int64(pg_time64_infinity) + return + elif obj == negative_infinity_datetime: + buf.write_int64(pg_time64_negative_infinity) + return + + utc_dt = obj.astimezone(utc) + + delta = utc_dt - pg_epoch_datetime_utc + cdef: + int64_t seconds = cpython.PyLong_AsLongLong(delta.days) * 86400 + \ + cpython.PyLong_AsLong(delta.seconds) + int32_t microseconds = cpython.PyLong_AsLong( + delta.microseconds) + + _encode_time(buf, seconds, microseconds) + + +cdef timestamptz_decode(CodecContext settings, FRBuffer *buf): + cdef: + int64_t seconds = 0 + int32_t microseconds = 0 + int32_t inf = _decode_time(buf, &seconds, µseconds) + + if inf > 0: + # positive infinity + return infinity_datetime + elif inf < 0: + # negative infinity + return negative_infinity_datetime + else: + return pg_epoch_datetime_utc.__add__( + timedelta(0, seconds, microseconds)) + + +cdef time_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + int64_t seconds = cpython.PyLong_AsLong(obj.hour) * 3600 + \ + cpython.PyLong_AsLong(obj.minute) * 60 + \ + cpython.PyLong_AsLong(obj.second) + int32_t microseconds = cpython.PyLong_AsLong(obj.microsecond) + + buf.write_int32(8) + _encode_time(buf, seconds, microseconds) + + +cdef time_encode_tuple(CodecContext settings, WriteBuffer buf, obj): + cdef: + int64_t microseconds + + if len(obj) != 1: + raise ValueError( + 'time tuple encoder: expecting 1 element ' + 'in tuple, got {}'.format(len(obj))) + + microseconds = obj[0] + + buf.write_int32(8) + buf.write_int64(microseconds) + + +cdef time_decode(CodecContext settings, FRBuffer *buf): + cdef: + int64_t seconds = 0 + int32_t microseconds = 0 + + _decode_time(buf, &seconds, µseconds) + + cdef: + int64_t minutes = (seconds / 60) + int64_t sec = seconds % 60 + int64_t hours = (minutes / 60) + int64_t min = minutes % 60 + + return datetime.time(hours, min, sec, microseconds) + + +cdef time_decode_tuple(CodecContext settings, FRBuffer *buf): + cdef: + int64_t ts = hton.unpack_int64(frb_read(buf, 8)) + + return (ts,) + + +cdef timetz_encode(CodecContext settings, WriteBuffer buf, obj): + offset = obj.tzinfo.utcoffset(None) + + cdef: + int32_t offset_sec = \ + cpython.PyLong_AsLong(offset.days) * 24 * 60 * 60 + \ + cpython.PyLong_AsLong(offset.seconds) + + int64_t seconds = cpython.PyLong_AsLong(obj.hour) * 3600 + \ + cpython.PyLong_AsLong(obj.minute) * 60 + \ + cpython.PyLong_AsLong(obj.second) + + int32_t microseconds = cpython.PyLong_AsLong(obj.microsecond) + + buf.write_int32(12) + _encode_time(buf, seconds, microseconds) + # In Python utcoffset() is the difference between the local time + # and the UTC, whereas in PostgreSQL it's the opposite, + # so we need to flip the sign. + buf.write_int32(-offset_sec) + + +cdef timetz_encode_tuple(CodecContext settings, WriteBuffer buf, obj): + cdef: + int64_t microseconds + int32_t offset_sec + + if len(obj) != 2: + raise ValueError( + 'time tuple encoder: expecting 2 elements2 ' + 'in tuple, got {}'.format(len(obj))) + + microseconds = obj[0] + offset_sec = obj[1] + + buf.write_int32(12) + buf.write_int64(microseconds) + buf.write_int32(offset_sec) + + +cdef timetz_decode(CodecContext settings, FRBuffer *buf): + time = time_decode(settings, buf) + cdef int32_t offset = (hton.unpack_int32(frb_read(buf, 4)) / 60) + # See the comment in the `timetz_encode` method. + return time.replace(tzinfo=datetime.timezone(timedelta(minutes=-offset))) + + +cdef timetz_decode_tuple(CodecContext settings, FRBuffer *buf): + cdef: + int64_t microseconds = hton.unpack_int64(frb_read(buf, 8)) + int32_t offset_sec = hton.unpack_int32(frb_read(buf, 4)) + + return (microseconds, offset_sec) + + +cdef interval_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + int32_t days = cpython.PyLong_AsLong(obj.days) + int64_t seconds = cpython.PyLong_AsLongLong(obj.seconds) + int32_t microseconds = cpython.PyLong_AsLong(obj.microseconds) + + buf.write_int32(16) + _encode_time(buf, seconds, microseconds) + buf.write_int32(days) + buf.write_int32(0) # Months + + +cdef interval_encode_tuple(CodecContext settings, WriteBuffer buf, + tuple obj): + cdef: + int32_t months + int32_t days + int64_t microseconds + + if len(obj) != 3: + raise ValueError( + 'interval tuple encoder: expecting 3 elements ' + 'in tuple, got {}'.format(len(obj))) + + months = obj[0] + days = obj[1] + microseconds = obj[2] + + buf.write_int32(16) + buf.write_int64(microseconds) + buf.write_int32(days) + buf.write_int32(months) + + +cdef interval_decode(CodecContext settings, FRBuffer *buf): + cdef: + int32_t days + int32_t months + int32_t years + int64_t seconds = 0 + int32_t microseconds = 0 + + _decode_time(buf, &seconds, µseconds) + + days = hton.unpack_int32(frb_read(buf, 4)) + months = hton.unpack_int32(frb_read(buf, 4)) + + if months < 0: + years = -(-months // 12) + months = -(-months % 12) + else: + years = (months // 12) + months = (months % 12) + + return datetime.timedelta(days=days + months * 30 + years * 365, + seconds=seconds, microseconds=microseconds) + + +cdef interval_decode_tuple(CodecContext settings, FRBuffer *buf): + cdef: + int32_t days + int32_t months + int64_t microseconds + + microseconds = hton.unpack_int64(frb_read(buf, 8)) + days = hton.unpack_int32(frb_read(buf, 4)) + months = hton.unpack_int32(frb_read(buf, 4)) + + return (months, days, microseconds) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/float.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/float.pyx new file mode 100644 index 0000000..94eda03 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/float.pyx @@ -0,0 +1,34 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from libc cimport math + + +cdef float4_encode(CodecContext settings, WriteBuffer buf, obj): + cdef double dval = cpython.PyFloat_AsDouble(obj) + cdef float fval = dval + if math.isinf(fval) and not math.isinf(dval): + raise ValueError('value out of float32 range') + + buf.write_int32(4) + buf.write_float(fval) + + +cdef float4_decode(CodecContext settings, FRBuffer *buf): + cdef float f = hton.unpack_float(frb_read(buf, 4)) + return cpython.PyFloat_FromDouble(f) + + +cdef float8_encode(CodecContext settings, WriteBuffer buf, obj): + cdef double dval = cpython.PyFloat_AsDouble(obj) + buf.write_int32(8) + buf.write_double(dval) + + +cdef float8_decode(CodecContext settings, FRBuffer *buf): + cdef double f = hton.unpack_double(frb_read(buf, 8)) + return cpython.PyFloat_FromDouble(f) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/geometry.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/geometry.pyx new file mode 100644 index 0000000..44aac64 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/geometry.pyx @@ -0,0 +1,164 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef inline _encode_points(WriteBuffer wbuf, object points): + cdef object point + + for point in points: + wbuf.write_double(point[0]) + wbuf.write_double(point[1]) + + +cdef inline _decode_points(FRBuffer *buf): + cdef: + int32_t npts = hton.unpack_int32(frb_read(buf, 4)) + pts = cpython.PyTuple_New(npts) + int32_t i + object point + double x + double y + + for i in range(npts): + x = hton.unpack_double(frb_read(buf, 8)) + y = hton.unpack_double(frb_read(buf, 8)) + point = pgproto_types.Point(x, y) + cpython.Py_INCREF(point) + cpython.PyTuple_SET_ITEM(pts, i, point) + + return pts + + +cdef box_encode(CodecContext settings, WriteBuffer wbuf, obj): + wbuf.write_int32(32) + _encode_points(wbuf, (obj[0], obj[1])) + + +cdef box_decode(CodecContext settings, FRBuffer *buf): + cdef: + double high_x = hton.unpack_double(frb_read(buf, 8)) + double high_y = hton.unpack_double(frb_read(buf, 8)) + double low_x = hton.unpack_double(frb_read(buf, 8)) + double low_y = hton.unpack_double(frb_read(buf, 8)) + + return pgproto_types.Box( + pgproto_types.Point(high_x, high_y), + pgproto_types.Point(low_x, low_y)) + + +cdef line_encode(CodecContext settings, WriteBuffer wbuf, obj): + wbuf.write_int32(24) + wbuf.write_double(obj[0]) + wbuf.write_double(obj[1]) + wbuf.write_double(obj[2]) + + +cdef line_decode(CodecContext settings, FRBuffer *buf): + cdef: + double A = hton.unpack_double(frb_read(buf, 8)) + double B = hton.unpack_double(frb_read(buf, 8)) + double C = hton.unpack_double(frb_read(buf, 8)) + + return pgproto_types.Line(A, B, C) + + +cdef lseg_encode(CodecContext settings, WriteBuffer wbuf, obj): + wbuf.write_int32(32) + _encode_points(wbuf, (obj[0], obj[1])) + + +cdef lseg_decode(CodecContext settings, FRBuffer *buf): + cdef: + double p1_x = hton.unpack_double(frb_read(buf, 8)) + double p1_y = hton.unpack_double(frb_read(buf, 8)) + double p2_x = hton.unpack_double(frb_read(buf, 8)) + double p2_y = hton.unpack_double(frb_read(buf, 8)) + + return pgproto_types.LineSegment((p1_x, p1_y), (p2_x, p2_y)) + + +cdef point_encode(CodecContext settings, WriteBuffer wbuf, obj): + wbuf.write_int32(16) + wbuf.write_double(obj[0]) + wbuf.write_double(obj[1]) + + +cdef point_decode(CodecContext settings, FRBuffer *buf): + cdef: + double x = hton.unpack_double(frb_read(buf, 8)) + double y = hton.unpack_double(frb_read(buf, 8)) + + return pgproto_types.Point(x, y) + + +cdef path_encode(CodecContext settings, WriteBuffer wbuf, obj): + cdef: + int8_t is_closed = 0 + ssize_t npts + ssize_t encoded_len + int32_t i + + if cpython.PyTuple_Check(obj): + is_closed = 1 + elif cpython.PyList_Check(obj): + is_closed = 0 + elif isinstance(obj, pgproto_types.Path): + is_closed = obj.is_closed + + npts = len(obj) + encoded_len = 1 + 4 + 16 * npts + if encoded_len > _MAXINT32: + raise ValueError('path value too long') + + wbuf.write_int32(encoded_len) + wbuf.write_byte(is_closed) + wbuf.write_int32(npts) + + _encode_points(wbuf, obj) + + +cdef path_decode(CodecContext settings, FRBuffer *buf): + cdef: + int8_t is_closed = (frb_read(buf, 1)[0]) + + return pgproto_types.Path(*_decode_points(buf), is_closed=is_closed == 1) + + +cdef poly_encode(CodecContext settings, WriteBuffer wbuf, obj): + cdef: + bint is_closed + ssize_t npts + ssize_t encoded_len + int32_t i + + npts = len(obj) + encoded_len = 4 + 16 * npts + if encoded_len > _MAXINT32: + raise ValueError('polygon value too long') + + wbuf.write_int32(encoded_len) + wbuf.write_int32(npts) + _encode_points(wbuf, obj) + + +cdef poly_decode(CodecContext settings, FRBuffer *buf): + return pgproto_types.Polygon(*_decode_points(buf)) + + +cdef circle_encode(CodecContext settings, WriteBuffer wbuf, obj): + wbuf.write_int32(24) + wbuf.write_double(obj[0][0]) + wbuf.write_double(obj[0][1]) + wbuf.write_double(obj[1]) + + +cdef circle_decode(CodecContext settings, FRBuffer *buf): + cdef: + double center_x = hton.unpack_double(frb_read(buf, 8)) + double center_y = hton.unpack_double(frb_read(buf, 8)) + double radius = hton.unpack_double(frb_read(buf, 8)) + + return pgproto_types.Circle((center_x, center_y), radius) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/hstore.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/hstore.pyx new file mode 100644 index 0000000..09051c7 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/hstore.pyx @@ -0,0 +1,73 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef hstore_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + char *str + ssize_t size + ssize_t count + object items + WriteBuffer item_buf = WriteBuffer.new() + + count = len(obj) + if count > _MAXINT32: + raise ValueError('hstore value is too large') + item_buf.write_int32(count) + + if hasattr(obj, 'items'): + items = obj.items() + else: + items = obj + + for k, v in items: + if k is None: + raise ValueError('null value not allowed in hstore key') + as_pg_string_and_size(settings, k, &str, &size) + item_buf.write_int32(size) + item_buf.write_cstr(str, size) + if v is None: + item_buf.write_int32(-1) + else: + as_pg_string_and_size(settings, v, &str, &size) + item_buf.write_int32(size) + item_buf.write_cstr(str, size) + + buf.write_int32(item_buf.len()) + buf.write_buffer(item_buf) + + +cdef hstore_decode(CodecContext settings, FRBuffer *buf): + cdef: + dict result + uint32_t elem_count + int32_t elem_len + uint32_t i + str k + str v + + result = {} + + elem_count = hton.unpack_int32(frb_read(buf, 4)) + if elem_count == 0: + return result + + for i in range(elem_count): + elem_len = hton.unpack_int32(frb_read(buf, 4)) + if elem_len < 0: + raise ValueError('null value not allowed in hstore key') + + k = decode_pg_string(settings, frb_read(buf, elem_len), elem_len) + + elem_len = hton.unpack_int32(frb_read(buf, 4)) + if elem_len < 0: + v = None + else: + v = decode_pg_string(settings, frb_read(buf, elem_len), elem_len) + + result[k] = v + + return result diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/int.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/int.pyx new file mode 100644 index 0000000..9997244 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/int.pyx @@ -0,0 +1,144 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef bool_encode(CodecContext settings, WriteBuffer buf, obj): + if not cpython.PyBool_Check(obj): + raise TypeError('a boolean is required (got type {})'.format( + type(obj).__name__)) + + buf.write_int32(1) + buf.write_byte(b'\x01' if obj is True else b'\x00') + + +cdef bool_decode(CodecContext settings, FRBuffer *buf): + return frb_read(buf, 1)[0] is b'\x01' + + +cdef int2_encode(CodecContext settings, WriteBuffer buf, obj): + cdef int overflow = 0 + cdef long val + + try: + if type(obj) is not int and hasattr(type(obj), '__int__'): + # Silence a Python warning about implicit __int__ + # conversion. + obj = int(obj) + val = cpython.PyLong_AsLong(obj) + except OverflowError: + overflow = 1 + + if overflow or val < INT16_MIN or val > INT16_MAX: + raise OverflowError('value out of int16 range') + + buf.write_int32(2) + buf.write_int16(val) + + +cdef int2_decode(CodecContext settings, FRBuffer *buf): + return cpython.PyLong_FromLong(hton.unpack_int16(frb_read(buf, 2))) + + +cdef int4_encode(CodecContext settings, WriteBuffer buf, obj): + cdef int overflow = 0 + cdef long val = 0 + + try: + if type(obj) is not int and hasattr(type(obj), '__int__'): + # Silence a Python warning about implicit __int__ + # conversion. + obj = int(obj) + val = cpython.PyLong_AsLong(obj) + except OverflowError: + overflow = 1 + + # "long" and "long long" have the same size for x86_64, need an extra check + if overflow or (sizeof(val) > 4 and (val < INT32_MIN or val > INT32_MAX)): + raise OverflowError('value out of int32 range') + + buf.write_int32(4) + buf.write_int32(val) + + +cdef int4_decode(CodecContext settings, FRBuffer *buf): + return cpython.PyLong_FromLong(hton.unpack_int32(frb_read(buf, 4))) + + +cdef uint4_encode(CodecContext settings, WriteBuffer buf, obj): + cdef int overflow = 0 + cdef unsigned long val = 0 + + try: + if type(obj) is not int and hasattr(type(obj), '__int__'): + # Silence a Python warning about implicit __int__ + # conversion. + obj = int(obj) + val = cpython.PyLong_AsUnsignedLong(obj) + except OverflowError: + overflow = 1 + + # "long" and "long long" have the same size for x86_64, need an extra check + if overflow or (sizeof(val) > 4 and val > UINT32_MAX): + raise OverflowError('value out of uint32 range') + + buf.write_int32(4) + buf.write_int32(val) + + +cdef uint4_decode(CodecContext settings, FRBuffer *buf): + return cpython.PyLong_FromUnsignedLong( + hton.unpack_int32(frb_read(buf, 4))) + + +cdef int8_encode(CodecContext settings, WriteBuffer buf, obj): + cdef int overflow = 0 + cdef long long val + + try: + if type(obj) is not int and hasattr(type(obj), '__int__'): + # Silence a Python warning about implicit __int__ + # conversion. + obj = int(obj) + val = cpython.PyLong_AsLongLong(obj) + except OverflowError: + overflow = 1 + + # Just in case for systems with "long long" bigger than 8 bytes + if overflow or (sizeof(val) > 8 and (val < INT64_MIN or val > INT64_MAX)): + raise OverflowError('value out of int64 range') + + buf.write_int32(8) + buf.write_int64(val) + + +cdef int8_decode(CodecContext settings, FRBuffer *buf): + return cpython.PyLong_FromLongLong(hton.unpack_int64(frb_read(buf, 8))) + + +cdef uint8_encode(CodecContext settings, WriteBuffer buf, obj): + cdef int overflow = 0 + cdef unsigned long long val = 0 + + try: + if type(obj) is not int and hasattr(type(obj), '__int__'): + # Silence a Python warning about implicit __int__ + # conversion. + obj = int(obj) + val = cpython.PyLong_AsUnsignedLongLong(obj) + except OverflowError: + overflow = 1 + + # Just in case for systems with "long long" bigger than 8 bytes + if overflow or (sizeof(val) > 8 and val > UINT64_MAX): + raise OverflowError('value out of uint64 range') + + buf.write_int32(8) + buf.write_int64(val) + + +cdef uint8_decode(CodecContext settings, FRBuffer *buf): + return cpython.PyLong_FromUnsignedLongLong( + hton.unpack_int64(frb_read(buf, 8))) \ No newline at end of file diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/json.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/json.pyx new file mode 100644 index 0000000..97e6916 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/json.pyx @@ -0,0 +1,57 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef jsonb_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + char *str + ssize_t size + + if settings.is_encoding_json(): + obj = settings.get_json_encoder().encode(obj) + + as_pg_string_and_size(settings, obj, &str, &size) + + if size > 0x7fffffff - 1: + raise ValueError('string too long') + + buf.write_int32(size + 1) + buf.write_byte(1) # JSONB format version + buf.write_cstr(str, size) + + +cdef jsonb_decode(CodecContext settings, FRBuffer *buf): + cdef uint8_t format = (frb_read(buf, 1)[0]) + + if format != 1: + raise ValueError('unexpected JSONB format: {}'.format(format)) + + rv = text_decode(settings, buf) + + if settings.is_decoding_json(): + rv = settings.get_json_decoder().decode(rv) + + return rv + + +cdef json_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + char *str + ssize_t size + + if settings.is_encoding_json(): + obj = settings.get_json_encoder().encode(obj) + + text_encode(settings, buf, obj) + + +cdef json_decode(CodecContext settings, FRBuffer *buf): + rv = text_decode(settings, buf) + + if settings.is_decoding_json(): + rv = settings.get_json_decoder().decode(rv) + + return rv diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/jsonpath.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/jsonpath.pyx new file mode 100644 index 0000000..610b30d --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/jsonpath.pyx @@ -0,0 +1,29 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef jsonpath_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + char *str + ssize_t size + + as_pg_string_and_size(settings, obj, &str, &size) + + if size > 0x7fffffff - 1: + raise ValueError('string too long') + + buf.write_int32(size + 1) + buf.write_byte(1) # jsonpath format version + buf.write_cstr(str, size) + + +cdef jsonpath_decode(CodecContext settings, FRBuffer *buf): + cdef uint8_t format = (frb_read(buf, 1)[0]) + + if format != 1: + raise ValueError('unexpected jsonpath format: {}'.format(format)) + + return text_decode(settings, buf) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/misc.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/misc.pyx new file mode 100644 index 0000000..99b19c9 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/misc.pyx @@ -0,0 +1,16 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef void_encode(CodecContext settings, WriteBuffer buf, obj): + # Void is zero bytes + buf.write_int32(0) + + +cdef void_decode(CodecContext settings, FRBuffer *buf): + # Do nothing; void will be passed as NULL so this function + # will never be called. + pass diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/network.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/network.pyx new file mode 100644 index 0000000..730c947 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/network.pyx @@ -0,0 +1,139 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import ipaddress + + +# defined in postgresql/src/include/inet.h +# +DEF PGSQL_AF_INET = 2 # AF_INET +DEF PGSQL_AF_INET6 = 3 # AF_INET + 1 + + +_ipaddr = ipaddress.ip_address +_ipiface = ipaddress.ip_interface +_ipnet = ipaddress.ip_network + + +cdef inline uint8_t _ip_max_prefix_len(int32_t family): + # Maximum number of bits in the network prefix of the specified + # IP protocol version. + if family == PGSQL_AF_INET: + return 32 + else: + return 128 + + +cdef inline int32_t _ip_addr_len(int32_t family): + # Length of address in bytes for the specified IP protocol version. + if family == PGSQL_AF_INET: + return 4 + else: + return 16 + + +cdef inline int8_t _ver_to_family(int32_t version): + if version == 4: + return PGSQL_AF_INET + else: + return PGSQL_AF_INET6 + + +cdef inline _net_encode(WriteBuffer buf, int8_t family, uint32_t bits, + int8_t is_cidr, bytes addr): + + cdef: + char *addrbytes + ssize_t addrlen + + cpython.PyBytes_AsStringAndSize(addr, &addrbytes, &addrlen) + + buf.write_int32(4 + addrlen) + buf.write_byte(family) + buf.write_byte(bits) + buf.write_byte(is_cidr) + buf.write_byte(addrlen) + buf.write_cstr(addrbytes, addrlen) + + +cdef net_decode(CodecContext settings, FRBuffer *buf, bint as_cidr): + cdef: + int32_t family = frb_read(buf, 1)[0] + uint8_t bits = frb_read(buf, 1)[0] + int prefix_len + int32_t is_cidr = frb_read(buf, 1)[0] + int32_t addrlen = frb_read(buf, 1)[0] + bytes addr + uint8_t max_prefix_len = _ip_max_prefix_len(family) + + if is_cidr != as_cidr: + raise ValueError('unexpected CIDR flag set in non-cidr value') + + if family != PGSQL_AF_INET and family != PGSQL_AF_INET6: + raise ValueError('invalid address family in "{}" value'.format( + 'cidr' if is_cidr else 'inet' + )) + + max_prefix_len = _ip_max_prefix_len(family) + + if bits > max_prefix_len: + raise ValueError('invalid network prefix length in "{}" value'.format( + 'cidr' if is_cidr else 'inet' + )) + + if addrlen != _ip_addr_len(family): + raise ValueError('invalid address length in "{}" value'.format( + 'cidr' if is_cidr else 'inet' + )) + + addr = cpython.PyBytes_FromStringAndSize(frb_read(buf, addrlen), addrlen) + + if as_cidr or bits != max_prefix_len: + prefix_len = cpython.PyLong_FromLong(bits) + + if as_cidr: + return _ipnet((addr, prefix_len)) + else: + return _ipiface((addr, prefix_len)) + else: + return _ipaddr(addr) + + +cdef cidr_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + object ipnet + int8_t family + + ipnet = _ipnet(obj) + family = _ver_to_family(ipnet.version) + _net_encode(buf, family, ipnet.prefixlen, 1, ipnet.network_address.packed) + + +cdef cidr_decode(CodecContext settings, FRBuffer *buf): + return net_decode(settings, buf, True) + + +cdef inet_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + object ipaddr + int8_t family + + try: + ipaddr = _ipaddr(obj) + except ValueError: + # PostgreSQL accepts *both* CIDR and host values + # for the host datatype. + ipaddr = _ipiface(obj) + family = _ver_to_family(ipaddr.version) + _net_encode(buf, family, ipaddr.network.prefixlen, 1, ipaddr.packed) + else: + family = _ver_to_family(ipaddr.version) + _net_encode(buf, family, _ip_max_prefix_len(family), 0, ipaddr.packed) + + +cdef inet_decode(CodecContext settings, FRBuffer *buf): + return net_decode(settings, buf, False) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/numeric.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/numeric.pyx new file mode 100644 index 0000000..b75d096 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/numeric.pyx @@ -0,0 +1,356 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from libc.math cimport abs, log10 +from libc.stdio cimport snprintf + +import decimal + +# defined in postgresql/src/backend/utils/adt/numeric.c +DEF DEC_DIGITS = 4 +DEF MAX_DSCALE = 0x3FFF +DEF NUMERIC_POS = 0x0000 +DEF NUMERIC_NEG = 0x4000 +DEF NUMERIC_NAN = 0xC000 +DEF NUMERIC_PINF = 0xD000 +DEF NUMERIC_NINF = 0xF000 + +_Dec = decimal.Decimal + + +cdef numeric_encode_text(CodecContext settings, WriteBuffer buf, obj): + text_encode(settings, buf, str(obj)) + + +cdef numeric_decode_text(CodecContext settings, FRBuffer *buf): + return _Dec(text_decode(settings, buf)) + + +cdef numeric_encode_binary(CodecContext settings, WriteBuffer buf, obj): + cdef: + object dec + object dt + int64_t exponent + int64_t i + int64_t j + tuple pydigits + int64_t num_pydigits + int16_t pgdigit + int64_t num_pgdigits + int16_t dscale + int64_t dweight + int64_t weight + uint16_t sign + int64_t padding_size = 0 + + if isinstance(obj, _Dec): + dec = obj + else: + dec = _Dec(obj) + + dt = dec.as_tuple() + + if dt.exponent == 'n' or dt.exponent == 'N': + # NaN + sign = NUMERIC_NAN + num_pgdigits = 0 + weight = 0 + dscale = 0 + elif dt.exponent == 'F': + # Infinity + if dt.sign: + sign = NUMERIC_NINF + else: + sign = NUMERIC_PINF + num_pgdigits = 0 + weight = 0 + dscale = 0 + else: + exponent = dt.exponent + if exponent < 0 and -exponent > MAX_DSCALE: + raise ValueError( + 'cannot encode Decimal value into numeric: ' + 'exponent is too small') + + if dt.sign: + sign = NUMERIC_NEG + else: + sign = NUMERIC_POS + + pydigits = dt.digits + num_pydigits = len(pydigits) + + dweight = num_pydigits + exponent - 1 + if dweight >= 0: + weight = (dweight + DEC_DIGITS) // DEC_DIGITS - 1 + else: + weight = -((-dweight - 1) // DEC_DIGITS + 1) + + if weight > 2 ** 16 - 1: + raise ValueError( + 'cannot encode Decimal value into numeric: ' + 'exponent is too large') + + padding_size = \ + (weight + 1) * DEC_DIGITS - (dweight + 1) + num_pgdigits = \ + (num_pydigits + padding_size + DEC_DIGITS - 1) // DEC_DIGITS + + if num_pgdigits > 2 ** 16 - 1: + raise ValueError( + 'cannot encode Decimal value into numeric: ' + 'number of digits is too large') + + # Pad decimal digits to provide room for correct Postgres + # digit alignment in the digit computation loop. + pydigits = (0,) * DEC_DIGITS + pydigits + (0,) * DEC_DIGITS + + if exponent < 0: + if -exponent > MAX_DSCALE: + raise ValueError( + 'cannot encode Decimal value into numeric: ' + 'exponent is too small') + dscale = -exponent + else: + dscale = 0 + + buf.write_int32(2 + 2 + 2 + 2 + 2 * num_pgdigits) + buf.write_int16(num_pgdigits) + buf.write_int16(weight) + buf.write_int16(sign) + buf.write_int16(dscale) + + j = DEC_DIGITS - padding_size + + for i in range(num_pgdigits): + pgdigit = (pydigits[j] * 1000 + pydigits[j + 1] * 100 + + pydigits[j + 2] * 10 + pydigits[j + 3]) + j += DEC_DIGITS + buf.write_int16(pgdigit) + + +# The decoding strategy here is to form a string representation of +# the numeric var, as it is faster than passing an iterable of digits. +# For this reason the below code is pure overhead and is ~25% slower +# than the simple text decoder above. That said, we need the binary +# decoder to support binary COPY with numeric values. +cdef numeric_decode_binary_ex( + CodecContext settings, + FRBuffer *buf, + bint trail_fract_zero, +): + cdef: + uint16_t num_pgdigits = hton.unpack_int16(frb_read(buf, 2)) + int16_t weight = hton.unpack_int16(frb_read(buf, 2)) + uint16_t sign = hton.unpack_int16(frb_read(buf, 2)) + uint16_t dscale = hton.unpack_int16(frb_read(buf, 2)) + int16_t pgdigit0 + ssize_t i + int16_t pgdigit + object pydigits + ssize_t num_pydigits + ssize_t actual_num_pydigits + ssize_t buf_size + int64_t exponent + int64_t abs_exponent + ssize_t exponent_chars + ssize_t front_padding = 0 + ssize_t num_fract_digits + ssize_t trailing_fract_zeros_adj + char smallbuf[_NUMERIC_DECODER_SMALLBUF_SIZE] + char *charbuf + char *bufptr + bint buf_allocated = False + + if sign == NUMERIC_NAN: + # Not-a-number + return _Dec('NaN') + elif sign == NUMERIC_PINF: + # +Infinity + return _Dec('Infinity') + elif sign == NUMERIC_NINF: + # -Infinity + return _Dec('-Infinity') + + if num_pgdigits == 0: + # Zero + return _Dec('0e-' + str(dscale)) + + pgdigit0 = hton.unpack_int16(frb_read(buf, 2)) + if weight >= 0: + if pgdigit0 < 10: + front_padding = 3 + elif pgdigit0 < 100: + front_padding = 2 + elif pgdigit0 < 1000: + front_padding = 1 + + # The number of fractional decimal digits actually encoded in + # base-DEC_DEIGITS digits sent by Postgres. + num_fract_digits = (num_pgdigits - weight - 1) * DEC_DIGITS + + # The trailing zero adjustment necessary to obtain exactly + # dscale number of fractional digits in output. May be negative, + # which indicates that trailing zeros in the last input digit + # should be discarded. + trailing_fract_zeros_adj = dscale - num_fract_digits + + # Maximum possible number of decimal digits in base 10. + # The actual number might be up to 3 digits smaller due to + # leading zeros in first input digit. + num_pydigits = num_pgdigits * DEC_DIGITS + if trailing_fract_zeros_adj > 0: + num_pydigits += trailing_fract_zeros_adj + + # Exponent. + exponent = (weight + 1) * DEC_DIGITS - front_padding + abs_exponent = abs(exponent) + if abs_exponent != 0: + # Number of characters required to render absolute exponent value + # in decimal. + exponent_chars = log10(abs_exponent) + 1 + else: + exponent_chars = 0 + + # Output buffer size. + buf_size = ( + 1 + # sign + 1 + # leading zero + 1 + # decimal dot + num_pydigits + # digits + 1 + # possible trailing zero padding + 2 + # exponent indicator (E-,E+) + exponent_chars + # exponent + 1 # null terminator char + ) + + if buf_size > _NUMERIC_DECODER_SMALLBUF_SIZE: + charbuf = cpython.PyMem_Malloc(buf_size) + buf_allocated = True + else: + charbuf = smallbuf + + try: + bufptr = charbuf + + if sign == NUMERIC_NEG: + bufptr[0] = b'-' + bufptr += 1 + + bufptr[0] = b'0' + bufptr[1] = b'.' + bufptr += 2 + + if weight >= 0: + bufptr = _unpack_digit_stripping_lzeros(bufptr, pgdigit0) + else: + bufptr = _unpack_digit(bufptr, pgdigit0) + + for i in range(1, num_pgdigits): + pgdigit = hton.unpack_int16(frb_read(buf, 2)) + bufptr = _unpack_digit(bufptr, pgdigit) + + if dscale: + if trailing_fract_zeros_adj > 0: + for i in range(trailing_fract_zeros_adj): + bufptr[i] = b'0' + + # If display scale is _less_ than the number of rendered digits, + # trailing_fract_zeros_adj will be negative and this will strip + # the excess trailing zeros. + bufptr += trailing_fract_zeros_adj + + if trail_fract_zero: + # Check if the number of rendered digits matches the exponent, + # and if so, add another trailing zero, so the result always + # appears with a decimal point. + actual_num_pydigits = bufptr - charbuf - 2 + if sign == NUMERIC_NEG: + actual_num_pydigits -= 1 + + if actual_num_pydigits == abs_exponent: + bufptr[0] = b'0' + bufptr += 1 + + if exponent != 0: + bufptr[0] = b'E' + if exponent < 0: + bufptr[1] = b'-' + else: + bufptr[1] = b'+' + bufptr += 2 + snprintf(bufptr, exponent_chars + 1, '%d', + abs_exponent) + bufptr += exponent_chars + + bufptr[0] = 0 + + pydigits = cpythonx.PyUnicode_FromString(charbuf) + + return _Dec(pydigits) + + finally: + if buf_allocated: + cpython.PyMem_Free(charbuf) + + +cdef numeric_decode_binary(CodecContext settings, FRBuffer *buf): + return numeric_decode_binary_ex(settings, buf, False) + + +cdef inline char *_unpack_digit_stripping_lzeros(char *buf, int64_t pgdigit): + cdef: + int64_t d + bint significant + + d = pgdigit // 1000 + significant = (d > 0) + if significant: + pgdigit -= d * 1000 + buf[0] = (d + b'0') + buf += 1 + + d = pgdigit // 100 + significant |= (d > 0) + if significant: + pgdigit -= d * 100 + buf[0] = (d + b'0') + buf += 1 + + d = pgdigit // 10 + significant |= (d > 0) + if significant: + pgdigit -= d * 10 + buf[0] = (d + b'0') + buf += 1 + + buf[0] = (pgdigit + b'0') + buf += 1 + + return buf + + +cdef inline char *_unpack_digit(char *buf, int64_t pgdigit): + cdef: + int64_t d + + d = pgdigit // 1000 + pgdigit -= d * 1000 + buf[0] = (d + b'0') + + d = pgdigit // 100 + pgdigit -= d * 100 + buf[1] = (d + b'0') + + d = pgdigit // 10 + pgdigit -= d * 10 + buf[2] = (d + b'0') + + buf[3] = (pgdigit + b'0') + buf += 4 + + return buf diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/pg_snapshot.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/pg_snapshot.pyx new file mode 100644 index 0000000..d96107c --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/pg_snapshot.pyx @@ -0,0 +1,63 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef pg_snapshot_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + ssize_t nxip + uint64_t xmin + uint64_t xmax + int i + WriteBuffer xip_buf = WriteBuffer.new() + + if not (cpython.PyTuple_Check(obj) or cpython.PyList_Check(obj)): + raise TypeError( + 'list or tuple expected (got type {})'.format(type(obj))) + + if len(obj) != 3: + raise ValueError( + 'invalid number of elements in txid_snapshot tuple, expecting 4') + + nxip = len(obj[2]) + if nxip > _MAXINT32: + raise ValueError('txid_snapshot value is too long') + + xmin = obj[0] + xmax = obj[1] + + for i in range(nxip): + xip_buf.write_int64( + cpython.PyLong_AsUnsignedLongLong(obj[2][i])) + + buf.write_int32(20 + xip_buf.len()) + + buf.write_int32(nxip) + buf.write_int64(xmin) + buf.write_int64(xmax) + buf.write_buffer(xip_buf) + + +cdef pg_snapshot_decode(CodecContext settings, FRBuffer *buf): + cdef: + int32_t nxip + uint64_t xmin + uint64_t xmax + tuple xip_tup + int32_t i + object xip + + nxip = hton.unpack_int32(frb_read(buf, 4)) + xmin = hton.unpack_int64(frb_read(buf, 8)) + xmax = hton.unpack_int64(frb_read(buf, 8)) + + xip_tup = cpython.PyTuple_New(nxip) + for i in range(nxip): + xip = cpython.PyLong_FromUnsignedLongLong( + hton.unpack_int64(frb_read(buf, 8))) + cpython.Py_INCREF(xip) + cpython.PyTuple_SET_ITEM(xip_tup, i, xip) + + return (xmin, xmax, xip_tup) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/text.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/text.pyx new file mode 100644 index 0000000..79f375d --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/text.pyx @@ -0,0 +1,48 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef inline as_pg_string_and_size( + CodecContext settings, obj, char **cstr, ssize_t *size): + + if not cpython.PyUnicode_Check(obj): + raise TypeError('expected str, got {}'.format(type(obj).__name__)) + + if settings.is_encoding_utf8(): + cstr[0] = cpythonx.PyUnicode_AsUTF8AndSize(obj, size) + else: + encoded = settings.get_text_codec().encode(obj)[0] + cpython.PyBytes_AsStringAndSize(encoded, cstr, size) + + if size[0] > 0x7fffffff: + raise ValueError('string too long') + + +cdef text_encode(CodecContext settings, WriteBuffer buf, obj): + cdef: + char *str + ssize_t size + + as_pg_string_and_size(settings, obj, &str, &size) + + buf.write_int32(size) + buf.write_cstr(str, size) + + +cdef inline decode_pg_string(CodecContext settings, const char* data, + ssize_t len): + + if settings.is_encoding_utf8(): + # decode UTF-8 in strict mode + return cpython.PyUnicode_DecodeUTF8(data, len, NULL) + else: + bytes = cpython.PyBytes_FromStringAndSize(data, len) + return settings.get_text_codec().decode(bytes)[0] + + +cdef text_decode(CodecContext settings, FRBuffer *buf): + cdef ssize_t buf_len = buf.len + return decode_pg_string(settings, frb_read_all(buf), buf_len) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/tid.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/tid.pyx new file mode 100644 index 0000000..b39bddc --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/tid.pyx @@ -0,0 +1,51 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef tid_encode(CodecContext settings, WriteBuffer buf, obj): + cdef int overflow = 0 + cdef unsigned long block, offset + + if not (cpython.PyTuple_Check(obj) or cpython.PyList_Check(obj)): + raise TypeError( + 'list or tuple expected (got type {})'.format(type(obj))) + + if len(obj) != 2: + raise ValueError( + 'invalid number of elements in tid tuple, expecting 2') + + try: + block = cpython.PyLong_AsUnsignedLong(obj[0]) + except OverflowError: + overflow = 1 + + # "long" and "long long" have the same size for x86_64, need an extra check + if overflow or (sizeof(block) > 4 and block > UINT32_MAX): + raise OverflowError('tuple id block value out of uint32 range') + + try: + offset = cpython.PyLong_AsUnsignedLong(obj[1]) + overflow = 0 + except OverflowError: + overflow = 1 + + if overflow or offset > 65535: + raise OverflowError('tuple id offset value out of uint16 range') + + buf.write_int32(6) + buf.write_int32(block) + buf.write_int16(offset) + + +cdef tid_decode(CodecContext settings, FRBuffer *buf): + cdef: + uint32_t block + uint16_t offset + + block = hton.unpack_int32(frb_read(buf, 4)) + offset = hton.unpack_int16(frb_read(buf, 2)) + + return (block, offset) diff --git a/env/Lib/site-packages/asyncpg/pgproto/codecs/uuid.pyx b/env/Lib/site-packages/asyncpg/pgproto/codecs/uuid.pyx new file mode 100644 index 0000000..0bc4567 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/codecs/uuid.pyx @@ -0,0 +1,27 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef uuid_encode(CodecContext settings, WriteBuffer wbuf, obj): + cdef: + char buf[16] + + if type(obj) is pg_UUID: + wbuf.write_int32(16) + wbuf.write_cstr((obj)._data, 16) + elif cpython.PyUnicode_Check(obj): + pg_uuid_bytes_from_str(obj, buf) + wbuf.write_int32(16) + wbuf.write_cstr(buf, 16) + else: + bytea_encode(settings, wbuf, obj.bytes) + + +cdef uuid_decode(CodecContext settings, FRBuffer *buf): + if buf.len != 16: + raise TypeError( + f'cannot decode UUID, expected 16 bytes, got {buf.len}') + return pg_uuid_from_buf(frb_read_all(buf)) diff --git a/env/Lib/site-packages/asyncpg/pgproto/consts.pxi b/env/Lib/site-packages/asyncpg/pgproto/consts.pxi new file mode 100644 index 0000000..dbce085 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/consts.pxi @@ -0,0 +1,12 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +DEF _BUFFER_INITIAL_SIZE = 1024 +DEF _BUFFER_MAX_GROW = 65536 +DEF _BUFFER_FREELIST_SIZE = 256 +DEF _MAXINT32 = 2**31 - 1 +DEF _NUMERIC_DECODER_SMALLBUF_SIZE = 256 diff --git a/env/Lib/site-packages/asyncpg/pgproto/cpythonx.pxd b/env/Lib/site-packages/asyncpg/pgproto/cpythonx.pxd new file mode 100644 index 0000000..7b4f4f3 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/cpythonx.pxd @@ -0,0 +1,23 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from cpython cimport Py_buffer + +cdef extern from "Python.h": + int PyUnicode_1BYTE_KIND + + int PyByteArray_CheckExact(object) + int PyByteArray_Resize(object, ssize_t) except -1 + object PyByteArray_FromStringAndSize(const char *, ssize_t) + char* PyByteArray_AsString(object) + + object PyUnicode_FromString(const char *u) + const char* PyUnicode_AsUTF8AndSize( + object unicode, ssize_t *size) except NULL + + object PyUnicode_FromKindAndData( + int kind, const void *buffer, Py_ssize_t size) diff --git a/env/Lib/site-packages/asyncpg/pgproto/debug.pxd b/env/Lib/site-packages/asyncpg/pgproto/debug.pxd new file mode 100644 index 0000000..5e59ec1 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/debug.pxd @@ -0,0 +1,10 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef extern from "debug.h": + + cdef int PG_DEBUG diff --git a/env/Lib/site-packages/asyncpg/pgproto/frb.pxd b/env/Lib/site-packages/asyncpg/pgproto/frb.pxd new file mode 100644 index 0000000..9ff8d10 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/frb.pxd @@ -0,0 +1,48 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef: + + struct FRBuffer: + const char* buf + ssize_t len + + inline ssize_t frb_get_len(FRBuffer *frb): + return frb.len + + inline void frb_set_len(FRBuffer *frb, ssize_t new_len): + frb.len = new_len + + inline void frb_init(FRBuffer *frb, const char *buf, ssize_t len): + frb.buf = buf + frb.len = len + + inline const char* frb_read(FRBuffer *frb, ssize_t n) except NULL: + cdef const char *result + + frb_check(frb, n) + + result = frb.buf + frb.buf += n + frb.len -= n + + return result + + inline const char* frb_read_all(FRBuffer *frb): + cdef const char *result + result = frb.buf + frb.buf += frb.len + frb.len = 0 + return result + + inline FRBuffer *frb_slice_from(FRBuffer *frb, + FRBuffer* source, ssize_t len): + frb.buf = frb_read(source, len) + frb.len = len + return frb + + object frb_check(FRBuffer *frb, ssize_t n) diff --git a/env/Lib/site-packages/asyncpg/pgproto/frb.pyx b/env/Lib/site-packages/asyncpg/pgproto/frb.pyx new file mode 100644 index 0000000..f11f6b9 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/frb.pyx @@ -0,0 +1,12 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef object frb_check(FRBuffer *frb, ssize_t n): + if n > frb.len: + raise AssertionError( + f'insufficient data in buffer: requested {n} ' + f'remaining {frb.len}') diff --git a/env/Lib/site-packages/asyncpg/pgproto/hton.pxd b/env/Lib/site-packages/asyncpg/pgproto/hton.pxd new file mode 100644 index 0000000..9b73abc --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/hton.pxd @@ -0,0 +1,24 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from libc.stdint cimport int16_t, int32_t, uint16_t, uint32_t, int64_t, uint64_t + + +cdef extern from "./hton.h": + cdef void pack_int16(char *buf, int16_t x); + cdef void pack_int32(char *buf, int32_t x); + cdef void pack_int64(char *buf, int64_t x); + cdef void pack_float(char *buf, float f); + cdef void pack_double(char *buf, double f); + cdef int16_t unpack_int16(const char *buf); + cdef uint16_t unpack_uint16(const char *buf); + cdef int32_t unpack_int32(const char *buf); + cdef uint32_t unpack_uint32(const char *buf); + cdef int64_t unpack_int64(const char *buf); + cdef uint64_t unpack_uint64(const char *buf); + cdef float unpack_float(const char *buf); + cdef double unpack_double(const char *buf); diff --git a/env/Lib/site-packages/asyncpg/pgproto/pgproto.cp311-win_amd64.pyd b/env/Lib/site-packages/asyncpg/pgproto/pgproto.cp311-win_amd64.pyd new file mode 100644 index 0000000..d0150ec Binary files /dev/null and b/env/Lib/site-packages/asyncpg/pgproto/pgproto.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/asyncpg/pgproto/pgproto.pxd b/env/Lib/site-packages/asyncpg/pgproto/pgproto.pxd new file mode 100644 index 0000000..ee9ec45 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/pgproto.pxd @@ -0,0 +1,19 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cimport cython +cimport cpython + +from libc.stdint cimport int16_t, int32_t, uint16_t, uint32_t, int64_t, uint64_t + + +include "./consts.pxi" +include "./frb.pxd" +include "./buffer.pxd" + + +include "./codecs/__init__.pxd" diff --git a/env/Lib/site-packages/asyncpg/pgproto/pgproto.pyx b/env/Lib/site-packages/asyncpg/pgproto/pgproto.pyx new file mode 100644 index 0000000..b880b7e --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/pgproto.pyx @@ -0,0 +1,49 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cimport cython +cimport cpython + +from . cimport cpythonx + +from libc.stdint cimport int8_t, uint8_t, int16_t, uint16_t, \ + int32_t, uint32_t, int64_t, uint64_t, \ + INT16_MIN, INT16_MAX, INT32_MIN, INT32_MAX, \ + UINT32_MAX, INT64_MIN, INT64_MAX, UINT64_MAX + + +from . cimport hton +from . cimport tohex + +from .debug cimport PG_DEBUG +from . import types as pgproto_types + + +include "./consts.pxi" +include "./frb.pyx" +include "./buffer.pyx" +include "./uuid.pyx" + +include "./codecs/context.pyx" + +include "./codecs/bytea.pyx" +include "./codecs/text.pyx" + +include "./codecs/datetime.pyx" +include "./codecs/float.pyx" +include "./codecs/int.pyx" +include "./codecs/json.pyx" +include "./codecs/jsonpath.pyx" +include "./codecs/uuid.pyx" +include "./codecs/numeric.pyx" +include "./codecs/bits.pyx" +include "./codecs/geometry.pyx" +include "./codecs/hstore.pyx" +include "./codecs/misc.pyx" +include "./codecs/network.pyx" +include "./codecs/tid.pyx" +include "./codecs/pg_snapshot.pyx" diff --git a/env/Lib/site-packages/asyncpg/pgproto/tohex.pxd b/env/Lib/site-packages/asyncpg/pgproto/tohex.pxd new file mode 100644 index 0000000..12fda84 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/tohex.pxd @@ -0,0 +1,10 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef extern from "./tohex.h": + cdef void uuid_to_str(const char *source, char *dest) + cdef void uuid_to_hex(const char *source, char *dest) diff --git a/env/Lib/site-packages/asyncpg/pgproto/types.py b/env/Lib/site-packages/asyncpg/pgproto/types.py new file mode 100644 index 0000000..9ed0e9b --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/types.py @@ -0,0 +1,423 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import builtins +import sys +import typing + +if sys.version_info >= (3, 8): + from typing import Literal, SupportsIndex +else: + from typing_extensions import Literal, SupportsIndex + + +__all__ = ( + 'BitString', 'Point', 'Path', 'Polygon', + 'Box', 'Line', 'LineSegment', 'Circle', +) + +_BitString = typing.TypeVar('_BitString', bound='BitString') +_BitOrderType = Literal['big', 'little'] + + +class BitString: + """Immutable representation of PostgreSQL `bit` and `varbit` types.""" + + __slots__ = '_bytes', '_bitlength' + + def __init__(self, + bitstring: typing.Optional[builtins.bytes] = None) -> None: + if not bitstring: + self._bytes = bytes() + self._bitlength = 0 + else: + bytelen = len(bitstring) // 8 + 1 + bytes_ = bytearray(bytelen) + byte = 0 + byte_pos = 0 + bit_pos = 0 + + for i, bit in enumerate(bitstring): + if bit == ' ': # type: ignore + continue + bit = int(bit) + if bit != 0 and bit != 1: + raise ValueError( + 'invalid bit value at position {}'.format(i)) + + byte |= bit << (8 - bit_pos - 1) + bit_pos += 1 + if bit_pos == 8: + bytes_[byte_pos] = byte + byte = 0 + byte_pos += 1 + bit_pos = 0 + + if bit_pos != 0: + bytes_[byte_pos] = byte + + bitlen = byte_pos * 8 + bit_pos + bytelen = byte_pos + (1 if bit_pos else 0) + + self._bytes = bytes(bytes_[:bytelen]) + self._bitlength = bitlen + + @classmethod + def frombytes(cls: typing.Type[_BitString], + bytes_: typing.Optional[builtins.bytes] = None, + bitlength: typing.Optional[int] = None) -> _BitString: + if bitlength is None: + if bytes_ is None: + bytes_ = bytes() + bitlength = 0 + else: + bitlength = len(bytes_) * 8 + else: + if bytes_ is None: + bytes_ = bytes(bitlength // 8 + 1) + bitlength = bitlength + else: + bytes_len = len(bytes_) * 8 + + if bytes_len == 0 and bitlength != 0: + raise ValueError('invalid bit length specified') + + if bytes_len != 0 and bitlength == 0: + raise ValueError('invalid bit length specified') + + if bitlength < bytes_len - 8: + raise ValueError('invalid bit length specified') + + if bitlength > bytes_len: + raise ValueError('invalid bit length specified') + + result = cls() + result._bytes = bytes_ + result._bitlength = bitlength + + return result + + @property + def bytes(self) -> builtins.bytes: + return self._bytes + + def as_string(self) -> str: + s = '' + + for i in range(self._bitlength): + s += str(self._getitem(i)) + if i % 4 == 3: + s += ' ' + + return s.strip() + + def to_int(self, bitorder: _BitOrderType = 'big', + *, signed: bool = False) -> int: + """Interpret the BitString as a Python int. + Acts similarly to int.from_bytes. + + :param bitorder: + Determines the bit order used to interpret the BitString. By + default, this function uses Postgres conventions for casting bits + to ints. If bitorder is 'big', the most significant bit is at the + start of the string (this is the same as the default). If bitorder + is 'little', the most significant bit is at the end of the string. + + :param bool signed: + Determines whether two's complement is used to interpret the + BitString. If signed is False, the returned value is always + non-negative. + + :return int: An integer representing the BitString. Information about + the BitString's exact length is lost. + + .. versionadded:: 0.18.0 + """ + x = int.from_bytes(self._bytes, byteorder='big') + x >>= -self._bitlength % 8 + if bitorder == 'big': + pass + elif bitorder == 'little': + x = int(bin(x)[:1:-1].ljust(self._bitlength, '0'), 2) + else: + raise ValueError("bitorder must be either 'big' or 'little'") + + if signed and self._bitlength > 0 and x & (1 << (self._bitlength - 1)): + x -= 1 << self._bitlength + return x + + @classmethod + def from_int(cls: typing.Type[_BitString], x: int, length: int, + bitorder: _BitOrderType = 'big', *, signed: bool = False) \ + -> _BitString: + """Represent the Python int x as a BitString. + Acts similarly to int.to_bytes. + + :param int x: + An integer to represent. Negative integers are represented in two's + complement form, unless the argument signed is False, in which case + negative integers raise an OverflowError. + + :param int length: + The length of the resulting BitString. An OverflowError is raised + if the integer is not representable in this many bits. + + :param bitorder: + Determines the bit order used in the BitString representation. By + default, this function uses Postgres conventions for casting ints + to bits. If bitorder is 'big', the most significant bit is at the + start of the string (this is the same as the default). If bitorder + is 'little', the most significant bit is at the end of the string. + + :param bool signed: + Determines whether two's complement is used in the BitString + representation. If signed is False and a negative integer is given, + an OverflowError is raised. + + :return BitString: A BitString representing the input integer, in the + form specified by the other input args. + + .. versionadded:: 0.18.0 + """ + # Exception types are by analogy to int.to_bytes + if length < 0: + raise ValueError("length argument must be non-negative") + elif length < x.bit_length(): + raise OverflowError("int too big to convert") + + if x < 0: + if not signed: + raise OverflowError("can't convert negative int to unsigned") + x &= (1 << length) - 1 + + if bitorder == 'big': + pass + elif bitorder == 'little': + x = int(bin(x)[:1:-1].ljust(length, '0'), 2) + else: + raise ValueError("bitorder must be either 'big' or 'little'") + + x <<= (-length % 8) + bytes_ = x.to_bytes((length + 7) // 8, byteorder='big') + return cls.frombytes(bytes_, length) + + def __repr__(self) -> str: + return ''.format(self.as_string()) + + __str__: typing.Callable[['BitString'], str] = __repr__ + + def __eq__(self, other: object) -> bool: + if not isinstance(other, BitString): + return NotImplemented + + return (self._bytes == other._bytes and + self._bitlength == other._bitlength) + + def __hash__(self) -> int: + return hash((self._bytes, self._bitlength)) + + def _getitem(self, i: int) -> int: + byte = self._bytes[i // 8] + shift = 8 - i % 8 - 1 + return (byte >> shift) & 0x1 + + def __getitem__(self, i: int) -> int: + if isinstance(i, slice): + raise NotImplementedError('BitString does not support slices') + + if i >= self._bitlength: + raise IndexError('index out of range') + + return self._getitem(i) + + def __len__(self) -> int: + return self._bitlength + + +class Point(typing.Tuple[float, float]): + """Immutable representation of PostgreSQL `point` type.""" + + __slots__ = () + + def __new__(cls, + x: typing.Union[typing.SupportsFloat, + SupportsIndex, + typing.Text, + builtins.bytes, + builtins.bytearray], + y: typing.Union[typing.SupportsFloat, + SupportsIndex, + typing.Text, + builtins.bytes, + builtins.bytearray]) -> 'Point': + return super().__new__(cls, + typing.cast(typing.Any, (float(x), float(y)))) + + def __repr__(self) -> str: + return '{}.{}({})'.format( + type(self).__module__, + type(self).__name__, + tuple.__repr__(self) + ) + + @property + def x(self) -> float: + return self[0] + + @property + def y(self) -> float: + return self[1] + + +class Box(typing.Tuple[Point, Point]): + """Immutable representation of PostgreSQL `box` type.""" + + __slots__ = () + + def __new__(cls, high: typing.Sequence[float], + low: typing.Sequence[float]) -> 'Box': + return super().__new__(cls, + typing.cast(typing.Any, (Point(*high), + Point(*low)))) + + def __repr__(self) -> str: + return '{}.{}({})'.format( + type(self).__module__, + type(self).__name__, + tuple.__repr__(self) + ) + + @property + def high(self) -> Point: + return self[0] + + @property + def low(self) -> Point: + return self[1] + + +class Line(typing.Tuple[float, float, float]): + """Immutable representation of PostgreSQL `line` type.""" + + __slots__ = () + + def __new__(cls, A: float, B: float, C: float) -> 'Line': + return super().__new__(cls, typing.cast(typing.Any, (A, B, C))) + + @property + def A(self) -> float: + return self[0] + + @property + def B(self) -> float: + return self[1] + + @property + def C(self) -> float: + return self[2] + + +class LineSegment(typing.Tuple[Point, Point]): + """Immutable representation of PostgreSQL `lseg` type.""" + + __slots__ = () + + def __new__(cls, p1: typing.Sequence[float], + p2: typing.Sequence[float]) -> 'LineSegment': + return super().__new__(cls, + typing.cast(typing.Any, (Point(*p1), + Point(*p2)))) + + def __repr__(self) -> str: + return '{}.{}({})'.format( + type(self).__module__, + type(self).__name__, + tuple.__repr__(self) + ) + + @property + def p1(self) -> Point: + return self[0] + + @property + def p2(self) -> Point: + return self[1] + + +class Path: + """Immutable representation of PostgreSQL `path` type.""" + + __slots__ = '_is_closed', 'points' + + points: typing.Tuple[Point, ...] + + def __init__(self, *points: typing.Sequence[float], + is_closed: bool = False) -> None: + self.points = tuple(Point(*p) for p in points) + self._is_closed = is_closed + + @property + def is_closed(self) -> bool: + return self._is_closed + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Path): + return NotImplemented + + return (self.points == other.points and + self._is_closed == other._is_closed) + + def __hash__(self) -> int: + return hash((self.points, self.is_closed)) + + def __iter__(self) -> typing.Iterator[Point]: + return iter(self.points) + + def __len__(self) -> int: + return len(self.points) + + @typing.overload + def __getitem__(self, i: int) -> Point: + ... + + @typing.overload + def __getitem__(self, i: slice) -> typing.Tuple[Point, ...]: + ... + + def __getitem__(self, i: typing.Union[int, slice]) \ + -> typing.Union[Point, typing.Tuple[Point, ...]]: + return self.points[i] + + def __contains__(self, point: object) -> bool: + return point in self.points + + +class Polygon(Path): + """Immutable representation of PostgreSQL `polygon` type.""" + + __slots__ = () + + def __init__(self, *points: typing.Sequence[float]) -> None: + # polygon is always closed + super().__init__(*points, is_closed=True) + + +class Circle(typing.Tuple[Point, float]): + """Immutable representation of PostgreSQL `circle` type.""" + + __slots__ = () + + def __new__(cls, center: Point, radius: float) -> 'Circle': + return super().__new__(cls, typing.cast(typing.Any, (center, radius))) + + @property + def center(self) -> Point: + return self[0] + + @property + def radius(self) -> float: + return self[1] diff --git a/env/Lib/site-packages/asyncpg/pgproto/uuid.pyx b/env/Lib/site-packages/asyncpg/pgproto/uuid.pyx new file mode 100644 index 0000000..52900ff --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pgproto/uuid.pyx @@ -0,0 +1,353 @@ +import functools +import uuid + +cimport cython +cimport cpython + +from libc.stdint cimport uint8_t, int8_t +from libc.string cimport memcpy, memcmp + + +cdef extern from "Python.h": + int PyUnicode_1BYTE_KIND + const char* PyUnicode_AsUTF8AndSize( + object unicode, Py_ssize_t *size) except NULL + object PyUnicode_FromKindAndData( + int kind, const void *buffer, Py_ssize_t size) + + +cdef extern from "./tohex.h": + cdef void uuid_to_str(const char *source, char *dest) + cdef void uuid_to_hex(const char *source, char *dest) + + +# A more efficient UUID type implementation +# (6-7x faster than the starndard uuid.UUID): +# +# -= Benchmark results (less is better): =- +# +# std_UUID(bytes): 1.2368 +# c_UUID(bytes): * 0.1645 (7.52x) +# object(): 0.1483 +# +# std_UUID(str): 1.8038 +# c_UUID(str): * 0.2313 (7.80x) +# +# str(std_UUID()): 1.4625 +# str(c_UUID()): * 0.2681 (5.46x) +# str(object()): 0.5975 +# +# std_UUID().bytes: 0.3508 +# c_UUID().bytes: * 0.1068 (3.28x) +# +# std_UUID().int: 0.0871 +# c_UUID().int: * 0.0856 +# +# std_UUID().hex: 0.4871 +# c_UUID().hex: * 0.1405 +# +# hash(std_UUID()): 0.3635 +# hash(c_UUID()): * 0.1564 (2.32x) +# +# dct[std_UUID()]: 0.3319 +# dct[c_UUID()]: * 0.1570 (2.11x) +# +# std_UUID() ==: 0.3478 +# c_UUID() ==: * 0.0915 (3.80x) + + +cdef char _hextable[256] +_hextable[:] = [ + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, + -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1 +] + + +cdef std_UUID = uuid.UUID + + +cdef pg_uuid_bytes_from_str(str u, char *out): + cdef: + const char *orig_buf + Py_ssize_t size + unsigned char ch + uint8_t acc, part, acc_set + int i, j + + orig_buf = PyUnicode_AsUTF8AndSize(u, &size) + if size > 36 or size < 32: + raise ValueError( + f'invalid UUID {u!r}: ' + f'length must be between 32..36 characters, got {size}') + + acc_set = 0 + j = 0 + for i in range(size): + ch = orig_buf[i] + if ch == b'-': + continue + + part = _hextable[ch] + if part == -1: + if ch >= 0x20 and ch <= 0x7e: + raise ValueError( + f'invalid UUID {u!r}: unexpected character {chr(ch)!r}') + else: + raise ValueError('invalid UUID {u!r}: unexpected character') + + if acc_set: + acc |= part + out[j] = acc + acc_set = 0 + j += 1 + else: + acc = (part << 4) + acc_set = 1 + + if j > 16 or (j == 16 and acc_set): + raise ValueError( + f'invalid UUID {u!r}: decodes to more than 16 bytes') + + if j != 16: + raise ValueError( + f'invalid UUID {u!r}: decodes to less than 16 bytes') + + +cdef class __UUIDReplaceMe: + pass + + +cdef pg_uuid_from_buf(const char *buf): + cdef: + UUID u = UUID.__new__(UUID) + memcpy(u._data, buf, 16) + return u + + +@cython.final +@cython.no_gc_clear +cdef class UUID(__UUIDReplaceMe): + + cdef: + char _data[16] + object _int + object _hash + object __weakref__ + + def __cinit__(self): + self._int = None + self._hash = None + + def __init__(self, inp): + cdef: + char *buf + Py_ssize_t size + + if cpython.PyBytes_Check(inp): + cpython.PyBytes_AsStringAndSize(inp, &buf, &size) + if size != 16: + raise ValueError(f'16 bytes were expected, got {size}') + memcpy(self._data, buf, 16) + + elif cpython.PyUnicode_Check(inp): + pg_uuid_bytes_from_str(inp, self._data) + else: + raise TypeError(f'a bytes or str object expected, got {inp!r}') + + @property + def bytes(self): + return cpython.PyBytes_FromStringAndSize(self._data, 16) + + @property + def int(self): + if self._int is None: + # The cache is important because `self.int` can be + # used multiple times by __hash__ etc. + self._int = int.from_bytes(self.bytes, 'big') + return self._int + + @property + def is_safe(self): + return uuid.SafeUUID.unknown + + def __str__(self): + cdef char out[36] + uuid_to_str(self._data, out) + return PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, out, 36) + + @property + def hex(self): + cdef char out[32] + uuid_to_hex(self._data, out) + return PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, out, 32) + + def __repr__(self): + return f"UUID('{self}')" + + def __reduce__(self): + return (type(self), (self.bytes,)) + + def __eq__(self, other): + if type(other) is UUID: + return memcmp(self._data, (other)._data, 16) == 0 + if isinstance(other, std_UUID): + return self.int == other.int + return NotImplemented + + def __ne__(self, other): + if type(other) is UUID: + return memcmp(self._data, (other)._data, 16) != 0 + if isinstance(other, std_UUID): + return self.int != other.int + return NotImplemented + + def __lt__(self, other): + if type(other) is UUID: + return memcmp(self._data, (other)._data, 16) < 0 + if isinstance(other, std_UUID): + return self.int < other.int + return NotImplemented + + def __gt__(self, other): + if type(other) is UUID: + return memcmp(self._data, (other)._data, 16) > 0 + if isinstance(other, std_UUID): + return self.int > other.int + return NotImplemented + + def __le__(self, other): + if type(other) is UUID: + return memcmp(self._data, (other)._data, 16) <= 0 + if isinstance(other, std_UUID): + return self.int <= other.int + return NotImplemented + + def __ge__(self, other): + if type(other) is UUID: + return memcmp(self._data, (other)._data, 16) >= 0 + if isinstance(other, std_UUID): + return self.int >= other.int + return NotImplemented + + def __hash__(self): + # In EdgeDB every schema object has a uuid and there are + # huge hash-maps of them. We want UUID.__hash__ to be + # as fast as possible. + if self._hash is not None: + return self._hash + + self._hash = hash(self.int) + return self._hash + + def __int__(self): + return self.int + + @property + def bytes_le(self): + bytes = self.bytes + return (bytes[4-1::-1] + bytes[6-1:4-1:-1] + bytes[8-1:6-1:-1] + + bytes[8:]) + + @property + def fields(self): + return (self.time_low, self.time_mid, self.time_hi_version, + self.clock_seq_hi_variant, self.clock_seq_low, self.node) + + @property + def time_low(self): + return self.int >> 96 + + @property + def time_mid(self): + return (self.int >> 80) & 0xffff + + @property + def time_hi_version(self): + return (self.int >> 64) & 0xffff + + @property + def clock_seq_hi_variant(self): + return (self.int >> 56) & 0xff + + @property + def clock_seq_low(self): + return (self.int >> 48) & 0xff + + @property + def time(self): + return (((self.time_hi_version & 0x0fff) << 48) | + (self.time_mid << 32) | self.time_low) + + @property + def clock_seq(self): + return (((self.clock_seq_hi_variant & 0x3f) << 8) | + self.clock_seq_low) + + @property + def node(self): + return self.int & 0xffffffffffff + + @property + def urn(self): + return 'urn:uuid:' + str(self) + + @property + def variant(self): + if not self.int & (0x8000 << 48): + return uuid.RESERVED_NCS + elif not self.int & (0x4000 << 48): + return uuid.RFC_4122 + elif not self.int & (0x2000 << 48): + return uuid.RESERVED_MICROSOFT + else: + return uuid.RESERVED_FUTURE + + @property + def version(self): + # The version bits are only meaningful for RFC 4122 UUIDs. + if self.variant == uuid.RFC_4122: + return int((self.int >> 76) & 0xf) + + +# +# In order for `isinstance(pgproto.UUID, uuid.UUID)` to work, +# patch __bases__ and __mro__ by injecting `uuid.UUID`. +# +# We apply brute-force here because the following pattern stopped +# working with Python 3.8: +# +# cdef class OurUUID: +# ... +# +# class UUID(OurUUID, uuid.UUID): +# ... +# +# With Python 3.8 it now produces +# +# "TypeError: multiple bases have instance lay-out conflict" +# +# error. Maybe it's possible to fix this some other way, but +# the best solution possible would be to just contribute our +# faster UUID to the standard library and not have this problem +# at all. For now this hack is pretty safe and should be +# compatible with future Pythons for long enough. +# +assert UUID.__bases__[0] is __UUIDReplaceMe +assert UUID.__mro__[1] is __UUIDReplaceMe +cpython.Py_INCREF(std_UUID) +cpython.PyTuple_SET_ITEM(UUID.__bases__, 0, std_UUID) +cpython.Py_INCREF(std_UUID) +cpython.PyTuple_SET_ITEM(UUID.__mro__, 1, std_UUID) +# + + +cdef pg_UUID = UUID diff --git a/env/Lib/site-packages/asyncpg/pool.py b/env/Lib/site-packages/asyncpg/pool.py new file mode 100644 index 0000000..06e698d --- /dev/null +++ b/env/Lib/site-packages/asyncpg/pool.py @@ -0,0 +1,1130 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import asyncio +import functools +import inspect +import logging +import time +import warnings + +from . import compat +from . import connection +from . import exceptions +from . import protocol + + +logger = logging.getLogger(__name__) + + +class PoolConnectionProxyMeta(type): + + def __new__(mcls, name, bases, dct, *, wrap=False): + if wrap: + for attrname in dir(connection.Connection): + if attrname.startswith('_') or attrname in dct: + continue + + meth = getattr(connection.Connection, attrname) + if not inspect.isfunction(meth): + continue + + wrapper = mcls._wrap_connection_method(attrname) + wrapper = functools.update_wrapper(wrapper, meth) + dct[attrname] = wrapper + + if '__doc__' not in dct: + dct['__doc__'] = connection.Connection.__doc__ + + return super().__new__(mcls, name, bases, dct) + + @staticmethod + def _wrap_connection_method(meth_name): + def call_con_method(self, *args, **kwargs): + # This method will be owned by PoolConnectionProxy class. + if self._con is None: + raise exceptions.InterfaceError( + 'cannot call Connection.{}(): ' + 'connection has been released back to the pool'.format( + meth_name)) + + meth = getattr(self._con.__class__, meth_name) + return meth(self._con, *args, **kwargs) + + return call_con_method + + +class PoolConnectionProxy(connection._ConnectionProxy, + metaclass=PoolConnectionProxyMeta, + wrap=True): + + __slots__ = ('_con', '_holder') + + def __init__(self, holder: 'PoolConnectionHolder', + con: connection.Connection): + self._con = con + self._holder = holder + con._set_proxy(self) + + def __getattr__(self, attr): + # Proxy all unresolved attributes to the wrapped Connection object. + return getattr(self._con, attr) + + def _detach(self) -> connection.Connection: + if self._con is None: + return + + con, self._con = self._con, None + con._set_proxy(None) + return con + + def __repr__(self): + if self._con is None: + return '<{classname} [released] {id:#x}>'.format( + classname=self.__class__.__name__, id=id(self)) + else: + return '<{classname} {con!r} {id:#x}>'.format( + classname=self.__class__.__name__, con=self._con, id=id(self)) + + +class PoolConnectionHolder: + + __slots__ = ('_con', '_pool', '_loop', '_proxy', + '_max_queries', '_setup', + '_max_inactive_time', '_in_use', + '_inactive_callback', '_timeout', + '_generation') + + def __init__(self, pool, *, max_queries, setup, max_inactive_time): + + self._pool = pool + self._con = None + self._proxy = None + + self._max_queries = max_queries + self._max_inactive_time = max_inactive_time + self._setup = setup + self._inactive_callback = None + self._in_use = None # type: asyncio.Future + self._timeout = None + self._generation = None + + def is_connected(self): + return self._con is not None and not self._con.is_closed() + + def is_idle(self): + return not self._in_use + + async def connect(self): + if self._con is not None: + raise exceptions.InternalClientError( + 'PoolConnectionHolder.connect() called while another ' + 'connection already exists') + + self._con = await self._pool._get_new_connection() + self._generation = self._pool._generation + self._maybe_cancel_inactive_callback() + self._setup_inactive_callback() + + async def acquire(self) -> PoolConnectionProxy: + if self._con is None or self._con.is_closed(): + self._con = None + await self.connect() + + elif self._generation != self._pool._generation: + # Connections have been expired, re-connect the holder. + self._pool._loop.create_task( + self._con.close(timeout=self._timeout)) + self._con = None + await self.connect() + + self._maybe_cancel_inactive_callback() + + self._proxy = proxy = PoolConnectionProxy(self, self._con) + + if self._setup is not None: + try: + await self._setup(proxy) + except (Exception, asyncio.CancelledError) as ex: + # If a user-defined `setup` function fails, we don't + # know if the connection is safe for re-use, hence + # we close it. A new connection will be created + # when `acquire` is called again. + try: + # Use `close()` to close the connection gracefully. + # An exception in `setup` isn't necessarily caused + # by an IO or a protocol error. close() will + # do the necessary cleanup via _release_on_close(). + await self._con.close() + finally: + raise ex + + self._in_use = self._pool._loop.create_future() + + return proxy + + async def release(self, timeout): + if self._in_use is None: + raise exceptions.InternalClientError( + 'PoolConnectionHolder.release() called on ' + 'a free connection holder') + + if self._con.is_closed(): + # When closing, pool connections perform the necessary + # cleanup, so we don't have to do anything else here. + return + + self._timeout = None + + if self._con._protocol.queries_count >= self._max_queries: + # The connection has reached its maximum utilization limit, + # so close it. Connection.close() will call _release(). + await self._con.close(timeout=timeout) + return + + if self._generation != self._pool._generation: + # The connection has expired because it belongs to + # an older generation (Pool.expire_connections() has + # been called.) + await self._con.close(timeout=timeout) + return + + try: + budget = timeout + + if self._con._protocol._is_cancelling(): + # If the connection is in cancellation state, + # wait for the cancellation + started = time.monotonic() + await compat.wait_for( + self._con._protocol._wait_for_cancellation(), + budget) + if budget is not None: + budget -= time.monotonic() - started + + await self._con.reset(timeout=budget) + except (Exception, asyncio.CancelledError) as ex: + # If the `reset` call failed, terminate the connection. + # A new one will be created when `acquire` is called + # again. + try: + # An exception in `reset` is most likely caused by + # an IO error, so terminate the connection. + self._con.terminate() + finally: + raise ex + + # Free this connection holder and invalidate the + # connection proxy. + self._release() + + # Rearm the connection inactivity timer. + self._setup_inactive_callback() + + async def wait_until_released(self): + if self._in_use is None: + return + else: + await self._in_use + + async def close(self): + if self._con is not None: + # Connection.close() will call _release_on_close() to + # finish holder cleanup. + await self._con.close() + + def terminate(self): + if self._con is not None: + # Connection.terminate() will call _release_on_close() to + # finish holder cleanup. + self._con.terminate() + + def _setup_inactive_callback(self): + if self._inactive_callback is not None: + raise exceptions.InternalClientError( + 'pool connection inactivity timer already exists') + + if self._max_inactive_time: + self._inactive_callback = self._pool._loop.call_later( + self._max_inactive_time, self._deactivate_inactive_connection) + + def _maybe_cancel_inactive_callback(self): + if self._inactive_callback is not None: + self._inactive_callback.cancel() + self._inactive_callback = None + + def _deactivate_inactive_connection(self): + if self._in_use is not None: + raise exceptions.InternalClientError( + 'attempting to deactivate an acquired connection') + + if self._con is not None: + # The connection is idle and not in use, so it's fine to + # use terminate() instead of close(). + self._con.terminate() + # Must call clear_connection, because _deactivate_connection + # is called when the connection is *not* checked out, and + # so terminate() above will not call the below. + self._release_on_close() + + def _release_on_close(self): + self._maybe_cancel_inactive_callback() + self._release() + self._con = None + + def _release(self): + """Release this connection holder.""" + if self._in_use is None: + # The holder is not checked out. + return + + if not self._in_use.done(): + self._in_use.set_result(None) + self._in_use = None + + # Deinitialize the connection proxy. All subsequent + # operations on it will fail. + if self._proxy is not None: + self._proxy._detach() + self._proxy = None + + # Put ourselves back to the pool queue. + self._pool._queue.put_nowait(self) + + +class Pool: + """A connection pool. + + Connection pool can be used to manage a set of connections to the database. + Connections are first acquired from the pool, then used, and then released + back to the pool. Once a connection is released, it's reset to close all + open cursors and other resources *except* prepared statements. + + Pools are created by calling :func:`~asyncpg.pool.create_pool`. + """ + + __slots__ = ( + '_queue', '_loop', '_minsize', '_maxsize', + '_init', '_connect_args', '_connect_kwargs', + '_holders', '_initialized', '_initializing', '_closing', + '_closed', '_connection_class', '_record_class', '_generation', + '_setup', '_max_queries', '_max_inactive_connection_lifetime' + ) + + def __init__(self, *connect_args, + min_size, + max_size, + max_queries, + max_inactive_connection_lifetime, + setup, + init, + loop, + connection_class, + record_class, + **connect_kwargs): + + if len(connect_args) > 1: + warnings.warn( + "Passing multiple positional arguments to asyncpg.Pool " + "constructor is deprecated and will be removed in " + "asyncpg 0.17.0. The non-deprecated form is " + "asyncpg.Pool(, **kwargs)", + DeprecationWarning, stacklevel=2) + + if loop is None: + loop = asyncio.get_event_loop() + self._loop = loop + + if max_size <= 0: + raise ValueError('max_size is expected to be greater than zero') + + if min_size < 0: + raise ValueError( + 'min_size is expected to be greater or equal to zero') + + if min_size > max_size: + raise ValueError('min_size is greater than max_size') + + if max_queries <= 0: + raise ValueError('max_queries is expected to be greater than zero') + + if max_inactive_connection_lifetime < 0: + raise ValueError( + 'max_inactive_connection_lifetime is expected to be greater ' + 'or equal to zero') + + if not issubclass(connection_class, connection.Connection): + raise TypeError( + 'connection_class is expected to be a subclass of ' + 'asyncpg.Connection, got {!r}'.format(connection_class)) + + if not issubclass(record_class, protocol.Record): + raise TypeError( + 'record_class is expected to be a subclass of ' + 'asyncpg.Record, got {!r}'.format(record_class)) + + self._minsize = min_size + self._maxsize = max_size + + self._holders = [] + self._initialized = False + self._initializing = False + self._queue = None + + self._connection_class = connection_class + self._record_class = record_class + + self._closing = False + self._closed = False + self._generation = 0 + self._init = init + self._connect_args = connect_args + self._connect_kwargs = connect_kwargs + + self._setup = setup + self._max_queries = max_queries + self._max_inactive_connection_lifetime = \ + max_inactive_connection_lifetime + + async def _async__init__(self): + if self._initialized: + return + if self._initializing: + raise exceptions.InterfaceError( + 'pool is being initialized in another task') + if self._closed: + raise exceptions.InterfaceError('pool is closed') + self._initializing = True + try: + await self._initialize() + return self + finally: + self._initializing = False + self._initialized = True + + async def _initialize(self): + self._queue = asyncio.LifoQueue(maxsize=self._maxsize) + for _ in range(self._maxsize): + ch = PoolConnectionHolder( + self, + max_queries=self._max_queries, + max_inactive_time=self._max_inactive_connection_lifetime, + setup=self._setup) + + self._holders.append(ch) + self._queue.put_nowait(ch) + + if self._minsize: + # Since we use a LIFO queue, the first items in the queue will be + # the last ones in `self._holders`. We want to pre-connect the + # first few connections in the queue, therefore we want to walk + # `self._holders` in reverse. + + # Connect the first connection holder in the queue so that + # any connection issues are visible early. + first_ch = self._holders[-1] # type: PoolConnectionHolder + await first_ch.connect() + + if self._minsize > 1: + connect_tasks = [] + for i, ch in enumerate(reversed(self._holders[:-1])): + # `minsize - 1` because we already have first_ch + if i >= self._minsize - 1: + break + connect_tasks.append(ch.connect()) + + await asyncio.gather(*connect_tasks) + + def is_closing(self): + """Return ``True`` if the pool is closing or is closed. + + .. versionadded:: 0.28.0 + """ + return self._closed or self._closing + + def get_size(self): + """Return the current number of connections in this pool. + + .. versionadded:: 0.25.0 + """ + return sum(h.is_connected() for h in self._holders) + + def get_min_size(self): + """Return the minimum number of connections in this pool. + + .. versionadded:: 0.25.0 + """ + return self._minsize + + def get_max_size(self): + """Return the maximum allowed number of connections in this pool. + + .. versionadded:: 0.25.0 + """ + return self._maxsize + + def get_idle_size(self): + """Return the current number of idle connections in this pool. + + .. versionadded:: 0.25.0 + """ + return sum(h.is_connected() and h.is_idle() for h in self._holders) + + def set_connect_args(self, dsn=None, **connect_kwargs): + r"""Set the new connection arguments for this pool. + + The new connection arguments will be used for all subsequent + new connection attempts. Existing connections will remain until + they expire. Use :meth:`Pool.expire_connections() + ` to expedite the connection + expiry. + + :param str dsn: + Connection arguments specified using as a single string in + the following format: + ``postgres://user:pass@host:port/database?option=value``. + + :param \*\*connect_kwargs: + Keyword arguments for the :func:`~asyncpg.connection.connect` + function. + + .. versionadded:: 0.16.0 + """ + + self._connect_args = [dsn] + self._connect_kwargs = connect_kwargs + + async def _get_new_connection(self): + con = await connection.connect( + *self._connect_args, + loop=self._loop, + connection_class=self._connection_class, + record_class=self._record_class, + **self._connect_kwargs, + ) + + if self._init is not None: + try: + await self._init(con) + except (Exception, asyncio.CancelledError) as ex: + # If a user-defined `init` function fails, we don't + # know if the connection is safe for re-use, hence + # we close it. A new connection will be created + # when `acquire` is called again. + try: + # Use `close()` to close the connection gracefully. + # An exception in `init` isn't necessarily caused + # by an IO or a protocol error. close() will + # do the necessary cleanup via _release_on_close(). + await con.close() + finally: + raise ex + + return con + + async def execute(self, query: str, *args, timeout: float=None) -> str: + """Execute an SQL command (or commands). + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.execute() `. + + .. versionadded:: 0.10.0 + """ + async with self.acquire() as con: + return await con.execute(query, *args, timeout=timeout) + + async def executemany(self, command: str, args, *, timeout: float=None): + """Execute an SQL *command* for each sequence of arguments in *args*. + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.executemany() + `. + + .. versionadded:: 0.10.0 + """ + async with self.acquire() as con: + return await con.executemany(command, args, timeout=timeout) + + async def fetch( + self, + query, + *args, + timeout=None, + record_class=None + ) -> list: + """Run a query and return the results as a list of :class:`Record`. + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.fetch() `. + + .. versionadded:: 0.10.0 + """ + async with self.acquire() as con: + return await con.fetch( + query, + *args, + timeout=timeout, + record_class=record_class + ) + + async def fetchval(self, query, *args, column=0, timeout=None): + """Run a query and return a value in the first row. + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.fetchval() + `. + + .. versionadded:: 0.10.0 + """ + async with self.acquire() as con: + return await con.fetchval( + query, *args, column=column, timeout=timeout) + + async def fetchrow(self, query, *args, timeout=None, record_class=None): + """Run a query and return the first row. + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.fetchrow() `. + + .. versionadded:: 0.10.0 + """ + async with self.acquire() as con: + return await con.fetchrow( + query, + *args, + timeout=timeout, + record_class=record_class + ) + + async def copy_from_table( + self, + table_name, + *, + output, + columns=None, + schema_name=None, + timeout=None, + format=None, + oids=None, + delimiter=None, + null=None, + header=None, + quote=None, + escape=None, + force_quote=None, + encoding=None + ): + """Copy table contents to a file or file-like object. + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.copy_from_table() + `. + + .. versionadded:: 0.24.0 + """ + async with self.acquire() as con: + return await con.copy_from_table( + table_name, + output=output, + columns=columns, + schema_name=schema_name, + timeout=timeout, + format=format, + oids=oids, + delimiter=delimiter, + null=null, + header=header, + quote=quote, + escape=escape, + force_quote=force_quote, + encoding=encoding + ) + + async def copy_from_query( + self, + query, + *args, + output, + timeout=None, + format=None, + oids=None, + delimiter=None, + null=None, + header=None, + quote=None, + escape=None, + force_quote=None, + encoding=None + ): + """Copy the results of a query to a file or file-like object. + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.copy_from_query() + `. + + .. versionadded:: 0.24.0 + """ + async with self.acquire() as con: + return await con.copy_from_query( + query, + *args, + output=output, + timeout=timeout, + format=format, + oids=oids, + delimiter=delimiter, + null=null, + header=header, + quote=quote, + escape=escape, + force_quote=force_quote, + encoding=encoding + ) + + async def copy_to_table( + self, + table_name, + *, + source, + columns=None, + schema_name=None, + timeout=None, + format=None, + oids=None, + freeze=None, + delimiter=None, + null=None, + header=None, + quote=None, + escape=None, + force_quote=None, + force_not_null=None, + force_null=None, + encoding=None, + where=None + ): + """Copy data to the specified table. + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.copy_to_table() + `. + + .. versionadded:: 0.24.0 + """ + async with self.acquire() as con: + return await con.copy_to_table( + table_name, + source=source, + columns=columns, + schema_name=schema_name, + timeout=timeout, + format=format, + oids=oids, + freeze=freeze, + delimiter=delimiter, + null=null, + header=header, + quote=quote, + escape=escape, + force_quote=force_quote, + force_not_null=force_not_null, + force_null=force_null, + encoding=encoding, + where=where + ) + + async def copy_records_to_table( + self, + table_name, + *, + records, + columns=None, + schema_name=None, + timeout=None, + where=None + ): + """Copy a list of records to the specified table using binary COPY. + + Pool performs this operation using one of its connections. Other than + that, it behaves identically to + :meth:`Connection.copy_records_to_table() + `. + + .. versionadded:: 0.24.0 + """ + async with self.acquire() as con: + return await con.copy_records_to_table( + table_name, + records=records, + columns=columns, + schema_name=schema_name, + timeout=timeout, + where=where + ) + + def acquire(self, *, timeout=None): + """Acquire a database connection from the pool. + + :param float timeout: A timeout for acquiring a Connection. + :return: An instance of :class:`~asyncpg.connection.Connection`. + + Can be used in an ``await`` expression or with an ``async with`` block. + + .. code-block:: python + + async with pool.acquire() as con: + await con.execute(...) + + Or: + + .. code-block:: python + + con = await pool.acquire() + try: + await con.execute(...) + finally: + await pool.release(con) + """ + return PoolAcquireContext(self, timeout) + + async def _acquire(self, timeout): + async def _acquire_impl(): + ch = await self._queue.get() # type: PoolConnectionHolder + try: + proxy = await ch.acquire() # type: PoolConnectionProxy + except (Exception, asyncio.CancelledError): + self._queue.put_nowait(ch) + raise + else: + # Record the timeout, as we will apply it by default + # in release(). + ch._timeout = timeout + return proxy + + if self._closing: + raise exceptions.InterfaceError('pool is closing') + self._check_init() + + if timeout is None: + return await _acquire_impl() + else: + return await compat.wait_for( + _acquire_impl(), timeout=timeout) + + async def release(self, connection, *, timeout=None): + """Release a database connection back to the pool. + + :param Connection connection: + A :class:`~asyncpg.connection.Connection` object to release. + :param float timeout: + A timeout for releasing the connection. If not specified, defaults + to the timeout provided in the corresponding call to the + :meth:`Pool.acquire() ` method. + + .. versionchanged:: 0.14.0 + Added the *timeout* parameter. + """ + if (type(connection) is not PoolConnectionProxy or + connection._holder._pool is not self): + raise exceptions.InterfaceError( + 'Pool.release() received invalid connection: ' + '{connection!r} is not a member of this pool'.format( + connection=connection)) + + if connection._con is None: + # Already released, do nothing. + return + + self._check_init() + + # Let the connection do its internal housekeeping when its released. + connection._con._on_release() + + ch = connection._holder + if timeout is None: + timeout = ch._timeout + + # Use asyncio.shield() to guarantee that task cancellation + # does not prevent the connection from being returned to the + # pool properly. + return await asyncio.shield(ch.release(timeout)) + + async def close(self): + """Attempt to gracefully close all connections in the pool. + + Wait until all pool connections are released, close them and + shut down the pool. If any error (including cancellation) occurs + in ``close()`` the pool will terminate by calling + :meth:`Pool.terminate() `. + + It is advisable to use :func:`python:asyncio.wait_for` to set + a timeout. + + .. versionchanged:: 0.16.0 + ``close()`` now waits until all pool connections are released + before closing them and the pool. Errors raised in ``close()`` + will cause immediate pool termination. + """ + if self._closed: + return + self._check_init() + + self._closing = True + + warning_callback = None + try: + warning_callback = self._loop.call_later( + 60, self._warn_on_long_close) + + release_coros = [ + ch.wait_until_released() for ch in self._holders] + await asyncio.gather(*release_coros) + + close_coros = [ + ch.close() for ch in self._holders] + await asyncio.gather(*close_coros) + + except (Exception, asyncio.CancelledError): + self.terminate() + raise + + finally: + if warning_callback is not None: + warning_callback.cancel() + self._closed = True + self._closing = False + + def _warn_on_long_close(self): + logger.warning('Pool.close() is taking over 60 seconds to complete. ' + 'Check if you have any unreleased connections left. ' + 'Use asyncio.wait_for() to set a timeout for ' + 'Pool.close().') + + def terminate(self): + """Terminate all connections in the pool.""" + if self._closed: + return + self._check_init() + for ch in self._holders: + ch.terminate() + self._closed = True + + async def expire_connections(self): + """Expire all currently open connections. + + Cause all currently open connections to get replaced on the + next :meth:`~asyncpg.pool.Pool.acquire()` call. + + .. versionadded:: 0.16.0 + """ + self._generation += 1 + + def _check_init(self): + if not self._initialized: + if self._initializing: + raise exceptions.InterfaceError( + 'pool is being initialized, but not yet ready: ' + 'likely there is a race between creating a pool and ' + 'using it') + raise exceptions.InterfaceError('pool is not initialized') + if self._closed: + raise exceptions.InterfaceError('pool is closed') + + def _drop_statement_cache(self): + # Drop statement cache for all connections in the pool. + for ch in self._holders: + if ch._con is not None: + ch._con._drop_local_statement_cache() + + def _drop_type_cache(self): + # Drop type codec cache for all connections in the pool. + for ch in self._holders: + if ch._con is not None: + ch._con._drop_local_type_cache() + + def __await__(self): + return self._async__init__().__await__() + + async def __aenter__(self): + await self._async__init__() + return self + + async def __aexit__(self, *exc): + await self.close() + + +class PoolAcquireContext: + + __slots__ = ('timeout', 'connection', 'done', 'pool') + + def __init__(self, pool, timeout): + self.pool = pool + self.timeout = timeout + self.connection = None + self.done = False + + async def __aenter__(self): + if self.connection is not None or self.done: + raise exceptions.InterfaceError('a connection is already acquired') + self.connection = await self.pool._acquire(self.timeout) + return self.connection + + async def __aexit__(self, *exc): + self.done = True + con = self.connection + self.connection = None + await self.pool.release(con) + + def __await__(self): + self.done = True + return self.pool._acquire(self.timeout).__await__() + + +def create_pool(dsn=None, *, + min_size=10, + max_size=10, + max_queries=50000, + max_inactive_connection_lifetime=300.0, + setup=None, + init=None, + loop=None, + connection_class=connection.Connection, + record_class=protocol.Record, + **connect_kwargs): + r"""Create a connection pool. + + Can be used either with an ``async with`` block: + + .. code-block:: python + + async with asyncpg.create_pool(user='postgres', + command_timeout=60) as pool: + await pool.fetch('SELECT 1') + + Or to perform multiple operations on a single connection: + + .. code-block:: python + + async with asyncpg.create_pool(user='postgres', + command_timeout=60) as pool: + async with pool.acquire() as con: + await con.execute(''' + CREATE TABLE names ( + id serial PRIMARY KEY, + name VARCHAR (255) NOT NULL) + ''') + await con.fetch('SELECT 1') + + Or directly with ``await`` (not recommended): + + .. code-block:: python + + pool = await asyncpg.create_pool(user='postgres', command_timeout=60) + con = await pool.acquire() + try: + await con.fetch('SELECT 1') + finally: + await pool.release(con) + + .. warning:: + Prepared statements and cursors returned by + :meth:`Connection.prepare() ` + and :meth:`Connection.cursor() ` + become invalid once the connection is released. Likewise, all + notification and log listeners are removed, and ``asyncpg`` will + issue a warning if there are any listener callbacks registered on a + connection that is being released to the pool. + + :param str dsn: + Connection arguments specified using as a single string in + the following format: + ``postgres://user:pass@host:port/database?option=value``. + + :param \*\*connect_kwargs: + Keyword arguments for the :func:`~asyncpg.connection.connect` + function. + + :param Connection connection_class: + The class to use for connections. Must be a subclass of + :class:`~asyncpg.connection.Connection`. + + :param type record_class: + If specified, the class to use for records returned by queries on + the connections in this pool. Must be a subclass of + :class:`~asyncpg.Record`. + + :param int min_size: + Number of connection the pool will be initialized with. + + :param int max_size: + Max number of connections in the pool. + + :param int max_queries: + Number of queries after a connection is closed and replaced + with a new connection. + + :param float max_inactive_connection_lifetime: + Number of seconds after which inactive connections in the + pool will be closed. Pass ``0`` to disable this mechanism. + + :param coroutine setup: + A coroutine to prepare a connection right before it is returned + from :meth:`Pool.acquire() `. An example use + case would be to automatically set up notifications listeners for + all connections of a pool. + + :param coroutine init: + A coroutine to initialize a connection when it is created. + An example use case would be to setup type codecs with + :meth:`Connection.set_builtin_type_codec() <\ + asyncpg.connection.Connection.set_builtin_type_codec>` + or :meth:`Connection.set_type_codec() <\ + asyncpg.connection.Connection.set_type_codec>`. + + :param loop: + An asyncio event loop instance. If ``None``, the default + event loop will be used. + + :return: An instance of :class:`~asyncpg.pool.Pool`. + + .. versionchanged:: 0.10.0 + An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any + attempted operation on a released connection. + + .. versionchanged:: 0.13.0 + An :exc:`~asyncpg.exceptions.InterfaceError` will be raised on any + attempted operation on a prepared statement or a cursor created + on a connection that has been released to the pool. + + .. versionchanged:: 0.13.0 + An :exc:`~asyncpg.exceptions.InterfaceWarning` will be produced + if there are any active listeners (added via + :meth:`Connection.add_listener() + ` + or :meth:`Connection.add_log_listener() + `) present on the + connection at the moment of its release to the pool. + + .. versionchanged:: 0.22.0 + Added the *record_class* parameter. + """ + return Pool( + dsn, + connection_class=connection_class, + record_class=record_class, + min_size=min_size, max_size=max_size, + max_queries=max_queries, loop=loop, setup=setup, init=init, + max_inactive_connection_lifetime=max_inactive_connection_lifetime, + **connect_kwargs) diff --git a/env/Lib/site-packages/asyncpg/prepared_stmt.py b/env/Lib/site-packages/asyncpg/prepared_stmt.py new file mode 100644 index 0000000..8e241d6 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/prepared_stmt.py @@ -0,0 +1,259 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import json + +from . import connresource +from . import cursor +from . import exceptions + + +class PreparedStatement(connresource.ConnectionResource): + """A representation of a prepared statement.""" + + __slots__ = ('_state', '_query', '_last_status') + + def __init__(self, connection, query, state): + super().__init__(connection) + self._state = state + self._query = query + state.attach() + self._last_status = None + + @connresource.guarded + def get_name(self) -> str: + """Return the name of this prepared statement. + + .. versionadded:: 0.25.0 + """ + return self._state.name + + @connresource.guarded + def get_query(self) -> str: + """Return the text of the query for this prepared statement. + + Example:: + + stmt = await connection.prepare('SELECT $1::int') + assert stmt.get_query() == "SELECT $1::int" + """ + return self._query + + @connresource.guarded + def get_statusmsg(self) -> str: + """Return the status of the executed command. + + Example:: + + stmt = await connection.prepare('CREATE TABLE mytab (a int)') + await stmt.fetch() + assert stmt.get_statusmsg() == "CREATE TABLE" + """ + if self._last_status is None: + return self._last_status + return self._last_status.decode() + + @connresource.guarded + def get_parameters(self): + """Return a description of statement parameters types. + + :return: A tuple of :class:`asyncpg.types.Type`. + + Example:: + + stmt = await connection.prepare('SELECT ($1::int, $2::text)') + print(stmt.get_parameters()) + + # Will print: + # (Type(oid=23, name='int4', kind='scalar', schema='pg_catalog'), + # Type(oid=25, name='text', kind='scalar', schema='pg_catalog')) + """ + return self._state._get_parameters() + + @connresource.guarded + def get_attributes(self): + """Return a description of relation attributes (columns). + + :return: A tuple of :class:`asyncpg.types.Attribute`. + + Example:: + + st = await self.con.prepare(''' + SELECT typname, typnamespace FROM pg_type + ''') + print(st.get_attributes()) + + # Will print: + # (Attribute( + # name='typname', + # type=Type(oid=19, name='name', kind='scalar', + # schema='pg_catalog')), + # Attribute( + # name='typnamespace', + # type=Type(oid=26, name='oid', kind='scalar', + # schema='pg_catalog'))) + """ + return self._state._get_attributes() + + @connresource.guarded + def cursor(self, *args, prefetch=None, + timeout=None) -> cursor.CursorFactory: + """Return a *cursor factory* for the prepared statement. + + :param args: Query arguments. + :param int prefetch: The number of rows the *cursor iterator* + will prefetch (defaults to ``50``.) + :param float timeout: Optional timeout in seconds. + + :return: A :class:`~cursor.CursorFactory` object. + """ + return cursor.CursorFactory( + self._connection, + self._query, + self._state, + args, + prefetch, + timeout, + self._state.record_class, + ) + + @connresource.guarded + async def explain(self, *args, analyze=False): + """Return the execution plan of the statement. + + :param args: Query arguments. + :param analyze: If ``True``, the statement will be executed and + the run time statitics added to the return value. + + :return: An object representing the execution plan. This value + is actually a deserialized JSON output of the SQL + ``EXPLAIN`` command. + """ + query = 'EXPLAIN (FORMAT JSON, VERBOSE' + if analyze: + query += ', ANALYZE) ' + else: + query += ') ' + query += self._state.query + + if analyze: + # From PostgreSQL docs: + # Important: Keep in mind that the statement is actually + # executed when the ANALYZE option is used. Although EXPLAIN + # will discard any output that a SELECT would return, other + # side effects of the statement will happen as usual. If you + # wish to use EXPLAIN ANALYZE on an INSERT, UPDATE, DELETE, + # CREATE TABLE AS, or EXECUTE statement without letting the + # command affect your data, use this approach: + # BEGIN; + # EXPLAIN ANALYZE ...; + # ROLLBACK; + tr = self._connection.transaction() + await tr.start() + try: + data = await self._connection.fetchval(query, *args) + finally: + await tr.rollback() + else: + data = await self._connection.fetchval(query, *args) + + return json.loads(data) + + @connresource.guarded + async def fetch(self, *args, timeout=None): + r"""Execute the statement and return a list of :class:`Record` objects. + + :param str query: Query text + :param args: Query arguments + :param float timeout: Optional timeout value in seconds. + + :return: A list of :class:`Record` instances. + """ + data = await self.__bind_execute(args, 0, timeout) + return data + + @connresource.guarded + async def fetchval(self, *args, column=0, timeout=None): + """Execute the statement and return a value in the first row. + + :param args: Query arguments. + :param int column: Numeric index within the record of the value to + return (defaults to 0). + :param float timeout: Optional timeout value in seconds. + If not specified, defaults to the value of + ``command_timeout`` argument to the ``Connection`` + instance constructor. + + :return: The value of the specified column of the first record. + """ + data = await self.__bind_execute(args, 1, timeout) + if not data: + return None + return data[0][column] + + @connresource.guarded + async def fetchrow(self, *args, timeout=None): + """Execute the statement and return the first row. + + :param str query: Query text + :param args: Query arguments + :param float timeout: Optional timeout value in seconds. + + :return: The first row as a :class:`Record` instance. + """ + data = await self.__bind_execute(args, 1, timeout) + if not data: + return None + return data[0] + + @connresource.guarded + async def executemany(self, args, *, timeout: float=None): + """Execute the statement for each sequence of arguments in *args*. + + :param args: An iterable containing sequences of arguments. + :param float timeout: Optional timeout value in seconds. + :return None: This method discards the results of the operations. + + .. versionadded:: 0.22.0 + """ + return await self.__do_execute( + lambda protocol: protocol.bind_execute_many( + self._state, args, '', timeout)) + + async def __do_execute(self, executor): + protocol = self._connection._protocol + try: + return await executor(protocol) + except exceptions.OutdatedSchemaCacheError: + await self._connection.reload_schema_state() + # We can not find all manually created prepared statements, so just + # drop known cached ones in the `self._connection`. + # Other manually created prepared statements will fail and + # invalidate themselves (unfortunately, clearing caches again). + self._state.mark_closed() + raise + + async def __bind_execute(self, args, limit, timeout): + data, status, _ = await self.__do_execute( + lambda protocol: protocol.bind_execute( + self._state, args, '', limit, True, timeout)) + self._last_status = status + return data + + def _check_open(self, meth_name): + if self._state.closed: + raise exceptions.InterfaceError( + 'cannot call PreparedStmt.{}(): ' + 'the prepared statement is closed'.format(meth_name)) + + def _check_conn_validity(self, meth_name): + self._check_open(meth_name) + super()._check_conn_validity(meth_name) + + def __del__(self): + self._state.detach() + self._connection._maybe_gc_stmt(self._state) diff --git a/env/Lib/site-packages/asyncpg/protocol/__init__.py b/env/Lib/site-packages/asyncpg/protocol/__init__.py new file mode 100644 index 0000000..8b3e06a --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/__init__.py @@ -0,0 +1,9 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + +# flake8: NOQA + +from .protocol import Protocol, Record, NO_TIMEOUT, BUILTIN_TYPE_NAME_MAP diff --git a/env/Lib/site-packages/asyncpg/protocol/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/asyncpg/protocol/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..25174af Binary files /dev/null and b/env/Lib/site-packages/asyncpg/protocol/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/__init__.py b/env/Lib/site-packages/asyncpg/protocol/codecs/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/asyncpg/protocol/codecs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..dce00a0 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/protocol/codecs/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/array.pyx b/env/Lib/site-packages/asyncpg/protocol/codecs/array.pyx new file mode 100644 index 0000000..f8f9b8d --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/codecs/array.pyx @@ -0,0 +1,875 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from collections.abc import (Iterable as IterableABC, + Mapping as MappingABC, + Sized as SizedABC) + +from asyncpg import exceptions + + +DEF ARRAY_MAXDIM = 6 # defined in postgresql/src/includes/c.h + +# "NULL" +cdef Py_UCS4 *APG_NULL = [0x004E, 0x0055, 0x004C, 0x004C, 0x0000] + + +ctypedef object (*encode_func_ex)(ConnectionSettings settings, + WriteBuffer buf, + object obj, + const void *arg) + + +ctypedef object (*decode_func_ex)(ConnectionSettings settings, + FRBuffer *buf, + const void *arg) + + +cdef inline bint _is_trivial_container(object obj): + return cpython.PyUnicode_Check(obj) or cpython.PyBytes_Check(obj) or \ + cpythonx.PyByteArray_Check(obj) or cpythonx.PyMemoryView_Check(obj) + + +cdef inline _is_array_iterable(object obj): + return ( + isinstance(obj, IterableABC) and + isinstance(obj, SizedABC) and + not _is_trivial_container(obj) and + not isinstance(obj, MappingABC) + ) + + +cdef inline _is_sub_array_iterable(object obj): + # Sub-arrays have a specialized check, because we treat + # nested tuples as records. + return _is_array_iterable(obj) and not cpython.PyTuple_Check(obj) + + +cdef _get_array_shape(object obj, int32_t *dims, int32_t *ndims): + cdef: + ssize_t mylen = len(obj) + ssize_t elemlen = -2 + object it + + if mylen > _MAXINT32: + raise ValueError('too many elements in array value') + + if ndims[0] > ARRAY_MAXDIM: + raise ValueError( + 'number of array dimensions ({}) exceed the maximum expected ({})'. + format(ndims[0], ARRAY_MAXDIM)) + + dims[ndims[0] - 1] = mylen + + for elem in obj: + if _is_sub_array_iterable(elem): + if elemlen == -2: + elemlen = len(elem) + if elemlen > _MAXINT32: + raise ValueError('too many elements in array value') + ndims[0] += 1 + _get_array_shape(elem, dims, ndims) + else: + if len(elem) != elemlen: + raise ValueError('non-homogeneous array') + else: + if elemlen >= 0: + raise ValueError('non-homogeneous array') + else: + elemlen = -1 + + +cdef _write_array_data(ConnectionSettings settings, object obj, int32_t ndims, + int32_t dim, WriteBuffer elem_data, + encode_func_ex encoder, const void *encoder_arg): + if dim < ndims - 1: + for item in obj: + _write_array_data(settings, item, ndims, dim + 1, elem_data, + encoder, encoder_arg) + else: + for item in obj: + if item is None: + elem_data.write_int32(-1) + else: + try: + encoder(settings, elem_data, item, encoder_arg) + except TypeError as e: + raise ValueError( + 'invalid array element: {}'.format(e.args[0])) from None + + +cdef inline array_encode(ConnectionSettings settings, WriteBuffer buf, + object obj, uint32_t elem_oid, + encode_func_ex encoder, const void *encoder_arg): + cdef: + WriteBuffer elem_data + int32_t dims[ARRAY_MAXDIM] + int32_t ndims = 1 + int32_t i + + if not _is_array_iterable(obj): + raise TypeError( + 'a sized iterable container expected (got type {!r})'.format( + type(obj).__name__)) + + _get_array_shape(obj, dims, &ndims) + + elem_data = WriteBuffer.new() + + if ndims > 1: + _write_array_data(settings, obj, ndims, 0, elem_data, + encoder, encoder_arg) + else: + for i, item in enumerate(obj): + if item is None: + elem_data.write_int32(-1) + else: + try: + encoder(settings, elem_data, item, encoder_arg) + except TypeError as e: + raise ValueError( + 'invalid array element at index {}: {}'.format( + i, e.args[0])) from None + + buf.write_int32(12 + 8 * ndims + elem_data.len()) + # Number of dimensions + buf.write_int32(ndims) + # flags + buf.write_int32(0) + # element type + buf.write_int32(elem_oid) + # upper / lower bounds + for i in range(ndims): + buf.write_int32(dims[i]) + buf.write_int32(1) + # element data + buf.write_buffer(elem_data) + + +cdef _write_textarray_data(ConnectionSettings settings, object obj, + int32_t ndims, int32_t dim, WriteBuffer array_data, + encode_func_ex encoder, const void *encoder_arg, + Py_UCS4 typdelim): + cdef: + ssize_t i = 0 + int8_t delim = typdelim + WriteBuffer elem_data + Py_buffer pybuf + const char *elem_str + char ch + ssize_t elem_len + ssize_t quoted_elem_len + bint need_quoting + + array_data.write_byte(b'{') + + if dim < ndims - 1: + for item in obj: + if i > 0: + array_data.write_byte(delim) + array_data.write_byte(b' ') + _write_textarray_data(settings, item, ndims, dim + 1, array_data, + encoder, encoder_arg, typdelim) + i += 1 + else: + for item in obj: + elem_data = WriteBuffer.new() + + if i > 0: + array_data.write_byte(delim) + array_data.write_byte(b' ') + + if item is None: + array_data.write_bytes(b'NULL') + i += 1 + continue + else: + try: + encoder(settings, elem_data, item, encoder_arg) + except TypeError as e: + raise ValueError( + 'invalid array element: {}'.format( + e.args[0])) from None + + # element string length (first four bytes are the encoded length.) + elem_len = elem_data.len() - 4 + + if elem_len == 0: + # Empty string + array_data.write_bytes(b'""') + else: + cpython.PyObject_GetBuffer( + elem_data, &pybuf, cpython.PyBUF_SIMPLE) + + elem_str = (pybuf.buf) + 4 + + try: + if not apg_strcasecmp_char(elem_str, b'NULL'): + array_data.write_byte(b'"') + array_data.write_cstr(elem_str, 4) + array_data.write_byte(b'"') + else: + quoted_elem_len = elem_len + need_quoting = False + + for i in range(elem_len): + ch = elem_str[i] + if ch == b'"' or ch == b'\\': + # Quotes and backslashes need escaping. + quoted_elem_len += 1 + need_quoting = True + elif (ch == b'{' or ch == b'}' or ch == delim or + apg_ascii_isspace(ch)): + need_quoting = True + + if need_quoting: + array_data.write_byte(b'"') + + if quoted_elem_len == elem_len: + array_data.write_cstr(elem_str, elem_len) + else: + # Escaping required. + for i in range(elem_len): + ch = elem_str[i] + if ch == b'"' or ch == b'\\': + array_data.write_byte(b'\\') + array_data.write_byte(ch) + + array_data.write_byte(b'"') + else: + array_data.write_cstr(elem_str, elem_len) + finally: + cpython.PyBuffer_Release(&pybuf) + + i += 1 + + array_data.write_byte(b'}') + + +cdef inline textarray_encode(ConnectionSettings settings, WriteBuffer buf, + object obj, encode_func_ex encoder, + const void *encoder_arg, Py_UCS4 typdelim): + cdef: + WriteBuffer array_data + int32_t dims[ARRAY_MAXDIM] + int32_t ndims = 1 + int32_t i + + if not _is_array_iterable(obj): + raise TypeError( + 'a sized iterable container expected (got type {!r})'.format( + type(obj).__name__)) + + _get_array_shape(obj, dims, &ndims) + + array_data = WriteBuffer.new() + _write_textarray_data(settings, obj, ndims, 0, array_data, + encoder, encoder_arg, typdelim) + buf.write_int32(array_data.len()) + buf.write_buffer(array_data) + + +cdef inline array_decode(ConnectionSettings settings, FRBuffer *buf, + decode_func_ex decoder, const void *decoder_arg): + cdef: + int32_t ndims = hton.unpack_int32(frb_read(buf, 4)) + int32_t flags = hton.unpack_int32(frb_read(buf, 4)) + uint32_t elem_oid = hton.unpack_int32(frb_read(buf, 4)) + list result + int i + int32_t elem_len + int32_t elem_count = 1 + FRBuffer elem_buf + int32_t dims[ARRAY_MAXDIM] + Codec elem_codec + + if ndims == 0: + return [] + + if ndims > ARRAY_MAXDIM: + raise exceptions.ProtocolError( + 'number of array dimensions ({}) exceed the maximum expected ({})'. + format(ndims, ARRAY_MAXDIM)) + elif ndims < 0: + raise exceptions.ProtocolError( + 'unexpected array dimensions value: {}'.format(ndims)) + + for i in range(ndims): + dims[i] = hton.unpack_int32(frb_read(buf, 4)) + if dims[i] < 0: + raise exceptions.ProtocolError( + 'unexpected array dimension size: {}'.format(dims[i])) + # Ignore the lower bound information + frb_read(buf, 4) + + if ndims == 1: + # Fast path for flat arrays + elem_count = dims[0] + result = cpython.PyList_New(elem_count) + + for i in range(elem_count): + elem_len = hton.unpack_int32(frb_read(buf, 4)) + if elem_len == -1: + elem = None + else: + frb_slice_from(&elem_buf, buf, elem_len) + elem = decoder(settings, &elem_buf, decoder_arg) + + cpython.Py_INCREF(elem) + cpython.PyList_SET_ITEM(result, i, elem) + + else: + result = _nested_array_decode(settings, buf, + decoder, decoder_arg, ndims, dims, + &elem_buf) + + return result + + +cdef _nested_array_decode(ConnectionSettings settings, + FRBuffer *buf, + decode_func_ex decoder, + const void *decoder_arg, + int32_t ndims, int32_t *dims, + FRBuffer *elem_buf): + + cdef: + int32_t elem_len + int64_t i, j + int64_t array_len = 1 + object elem, stride + # An array of pointers to lists for each current array level. + void *strides[ARRAY_MAXDIM] + # An array of current positions at each array level. + int32_t indexes[ARRAY_MAXDIM] + + for i in range(ndims): + array_len *= dims[i] + indexes[i] = 0 + strides[i] = NULL + + if array_len == 0: + # A multidimensional array with a zero-sized dimension? + return [] + + elif array_len < 0: + # Array length overflow + raise exceptions.ProtocolError('array length overflow') + + for i in range(array_len): + # Decode the element. + elem_len = hton.unpack_int32(frb_read(buf, 4)) + if elem_len == -1: + elem = None + else: + elem = decoder(settings, + frb_slice_from(elem_buf, buf, elem_len), + decoder_arg) + + # Take an explicit reference for PyList_SET_ITEM in the below + # loop expects this. + cpython.Py_INCREF(elem) + + # Iterate over array dimentions and put the element in + # the correctly nested sublist. + for j in reversed(range(ndims)): + if indexes[j] == 0: + # Allocate the list for this array level. + stride = cpython.PyList_New(dims[j]) + + strides[j] = stride + # Take an explicit reference for PyList_SET_ITEM below + # expects this. + cpython.Py_INCREF(stride) + + stride = strides[j] + cpython.PyList_SET_ITEM(stride, indexes[j], elem) + indexes[j] += 1 + + if indexes[j] == dims[j] and j != 0: + # This array level is full, continue the + # ascent in the dimensions so that this level + # sublist will be appened to the parent list. + elem = stride + # Reset the index, this will cause the + # new list to be allocated on the next + # iteration on this array axis. + indexes[j] = 0 + else: + break + + stride = strides[0] + # Since each element in strides has a refcount of 1, + # returning strides[0] will increment it to 2, so + # balance that. + cpython.Py_DECREF(stride) + return stride + + +cdef textarray_decode(ConnectionSettings settings, FRBuffer *buf, + decode_func_ex decoder, const void *decoder_arg, + Py_UCS4 typdelim): + cdef: + Py_UCS4 *array_text + str s + + # Make a copy of array data since we will be mutating it for + # the purposes of element decoding. + s = pgproto.text_decode(settings, buf) + array_text = cpythonx.PyUnicode_AsUCS4Copy(s) + + try: + return _textarray_decode( + settings, array_text, decoder, decoder_arg, typdelim) + except ValueError as e: + raise exceptions.ProtocolError( + 'malformed array literal {!r}: {}'.format(s, e.args[0])) + finally: + cpython.PyMem_Free(array_text) + + +cdef _textarray_decode(ConnectionSettings settings, + Py_UCS4 *array_text, + decode_func_ex decoder, + const void *decoder_arg, + Py_UCS4 typdelim): + + cdef: + bytearray array_bytes + list result + list new_stride + Py_UCS4 *ptr + int32_t ndims = 0 + int32_t ubound = 0 + int32_t lbound = 0 + int32_t dims[ARRAY_MAXDIM] + int32_t inferred_dims[ARRAY_MAXDIM] + int32_t inferred_ndims = 0 + void *strides[ARRAY_MAXDIM] + int32_t indexes[ARRAY_MAXDIM] + int32_t nest_level = 0 + int32_t item_level = 0 + bint end_of_array = False + + bint end_of_item = False + bint has_quoting = False + bint strip_spaces = False + bint in_quotes = False + Py_UCS4 *item_start + Py_UCS4 *item_ptr + Py_UCS4 *item_end + + int i + object item + str item_text + FRBuffer item_buf + char *pg_item_str + ssize_t pg_item_len + + ptr = array_text + + while True: + while apg_ascii_isspace(ptr[0]): + ptr += 1 + + if ptr[0] != '[': + # Finished parsing dimensions spec. + break + + ptr += 1 # '[' + + if ndims > ARRAY_MAXDIM: + raise ValueError( + 'number of array dimensions ({}) exceed the ' + 'maximum expected ({})'.format(ndims, ARRAY_MAXDIM)) + + ptr = apg_parse_int32(ptr, &ubound) + if ptr == NULL: + raise ValueError('missing array dimension value') + + if ptr[0] == ':': + ptr += 1 + lbound = ubound + + # [lower:upper] spec. We disregard the lbound for decoding. + ptr = apg_parse_int32(ptr, &ubound) + if ptr == NULL: + raise ValueError('missing array dimension value') + else: + lbound = 1 + + if ptr[0] != ']': + raise ValueError('missing \']\' after array dimensions') + + ptr += 1 # ']' + + dims[ndims] = ubound - lbound + 1 + ndims += 1 + + if ndims != 0: + # If dimensions were given, the '=' token is expected. + if ptr[0] != '=': + raise ValueError('missing \'=\' after array dimensions') + + ptr += 1 # '=' + + # Skip any whitespace after the '=', whitespace + # before was consumed in the above loop. + while apg_ascii_isspace(ptr[0]): + ptr += 1 + + # Infer the dimensions from the brace structure in the + # array literal body, and check that it matches the explicit + # spec. This also validates that the array literal is sane. + _infer_array_dims(ptr, typdelim, inferred_dims, &inferred_ndims) + + if inferred_ndims != ndims: + raise ValueError( + 'specified array dimensions do not match array content') + + for i in range(ndims): + if inferred_dims[i] != dims[i]: + raise ValueError( + 'specified array dimensions do not match array content') + else: + # Infer the dimensions from the brace structure in the array literal + # body. This also validates that the array literal is sane. + _infer_array_dims(ptr, typdelim, dims, &ndims) + + while not end_of_array: + # We iterate over the literal character by character + # and modify the string in-place removing the array-specific + # quoting and determining the boundaries of each element. + end_of_item = has_quoting = in_quotes = False + strip_spaces = True + + # Pointers to array element start, end, and the current pointer + # tracking the position where characters are written when + # escaping is folded. + item_start = item_end = item_ptr = ptr + item_level = 0 + + while not end_of_item: + if ptr[0] == '"': + in_quotes = not in_quotes + if in_quotes: + strip_spaces = False + else: + item_end = item_ptr + has_quoting = True + + elif ptr[0] == '\\': + # Quoted character, collapse the backslash. + ptr += 1 + has_quoting = True + item_ptr[0] = ptr[0] + item_ptr += 1 + strip_spaces = False + item_end = item_ptr + + elif in_quotes: + # Consume the string until we see the closing quote. + item_ptr[0] = ptr[0] + item_ptr += 1 + + elif ptr[0] == '{': + # Nesting level increase. + nest_level += 1 + + indexes[nest_level - 1] = 0 + new_stride = cpython.PyList_New(dims[nest_level - 1]) + strides[nest_level - 1] = \ + (new_stride) + + if nest_level > 1: + cpython.Py_INCREF(new_stride) + cpython.PyList_SET_ITEM( + strides[nest_level - 2], + indexes[nest_level - 2], + new_stride) + else: + result = new_stride + + elif ptr[0] == '}': + if item_level == 0: + # Make sure we keep track of which nesting + # level the item belongs to, as the loop + # will continue to consume closing braces + # until the delimiter or the end of input. + item_level = nest_level + + nest_level -= 1 + + if nest_level == 0: + end_of_array = end_of_item = True + + elif ptr[0] == typdelim: + # Array element delimiter, + end_of_item = True + if item_level == 0: + item_level = nest_level + + elif apg_ascii_isspace(ptr[0]): + if not strip_spaces: + item_ptr[0] = ptr[0] + item_ptr += 1 + # Ignore the leading literal whitespace. + + else: + item_ptr[0] = ptr[0] + item_ptr += 1 + strip_spaces = False + item_end = item_ptr + + ptr += 1 + + # end while not end_of_item + + if item_end == item_start: + # Empty array + continue + + item_end[0] = '\0' + + if not has_quoting and apg_strcasecmp(item_start, APG_NULL) == 0: + # NULL element. + item = None + else: + # XXX: find a way to avoid the redundant encode/decode + # cycle here. + item_text = cpythonx.PyUnicode_FromKindAndData( + cpythonx.PyUnicode_4BYTE_KIND, + item_start, + item_end - item_start) + + # Prepare the element buffer and call the text decoder + # for the element type. + pgproto.as_pg_string_and_size( + settings, item_text, &pg_item_str, &pg_item_len) + frb_init(&item_buf, pg_item_str, pg_item_len) + item = decoder(settings, &item_buf, decoder_arg) + + # Place the decoded element in the array. + cpython.Py_INCREF(item) + cpython.PyList_SET_ITEM( + strides[item_level - 1], + indexes[item_level - 1], + item) + + if nest_level > 0: + indexes[nest_level - 1] += 1 + + return result + + +cdef enum _ArrayParseState: + APS_START = 1 + APS_STRIDE_STARTED = 2 + APS_STRIDE_DONE = 3 + APS_STRIDE_DELIMITED = 4 + APS_ELEM_STARTED = 5 + APS_ELEM_DELIMITED = 6 + + +cdef _UnexpectedCharacter(const Py_UCS4 *array_text, const Py_UCS4 *ptr): + return ValueError('unexpected character {!r} at position {}'.format( + cpython.PyUnicode_FromOrdinal(ptr[0]), ptr - array_text + 1)) + + +cdef _infer_array_dims(const Py_UCS4 *array_text, + Py_UCS4 typdelim, + int32_t *dims, + int32_t *ndims): + cdef: + const Py_UCS4 *ptr = array_text + int i + int nest_level = 0 + bint end_of_array = False + bint end_of_item = False + bint in_quotes = False + bint array_is_empty = True + int stride_len[ARRAY_MAXDIM] + int prev_stride_len[ARRAY_MAXDIM] + _ArrayParseState parse_state = APS_START + + for i in range(ARRAY_MAXDIM): + dims[i] = prev_stride_len[i] = 0 + stride_len[i] = 1 + + while not end_of_array: + end_of_item = False + + while not end_of_item: + if ptr[0] == '\0': + raise ValueError('unexpected end of string') + + elif ptr[0] == '"': + if (parse_state not in (APS_STRIDE_STARTED, + APS_ELEM_DELIMITED) and + not (parse_state == APS_ELEM_STARTED and in_quotes)): + raise _UnexpectedCharacter(array_text, ptr) + + in_quotes = not in_quotes + if in_quotes: + parse_state = APS_ELEM_STARTED + array_is_empty = False + + elif ptr[0] == '\\': + if parse_state not in (APS_STRIDE_STARTED, + APS_ELEM_STARTED, + APS_ELEM_DELIMITED): + raise _UnexpectedCharacter(array_text, ptr) + + parse_state = APS_ELEM_STARTED + array_is_empty = False + + if ptr[1] != '\0': + ptr += 1 + else: + raise ValueError('unexpected end of string') + + elif in_quotes: + # Ignore everything inside the quotes. + pass + + elif ptr[0] == '{': + if parse_state not in (APS_START, + APS_STRIDE_STARTED, + APS_STRIDE_DELIMITED): + raise _UnexpectedCharacter(array_text, ptr) + + parse_state = APS_STRIDE_STARTED + if nest_level >= ARRAY_MAXDIM: + raise ValueError( + 'number of array dimensions ({}) exceed the ' + 'maximum expected ({})'.format( + nest_level, ARRAY_MAXDIM)) + + dims[nest_level] = 0 + nest_level += 1 + if ndims[0] < nest_level: + ndims[0] = nest_level + + elif ptr[0] == '}': + if (parse_state not in (APS_ELEM_STARTED, APS_STRIDE_DONE) and + not (nest_level == 1 and + parse_state == APS_STRIDE_STARTED)): + raise _UnexpectedCharacter(array_text, ptr) + + parse_state = APS_STRIDE_DONE + + if nest_level == 0: + raise _UnexpectedCharacter(array_text, ptr) + + nest_level -= 1 + + if (prev_stride_len[nest_level] != 0 and + stride_len[nest_level] != prev_stride_len[nest_level]): + raise ValueError( + 'inconsistent sub-array dimensions' + ' at position {}'.format( + ptr - array_text + 1)) + + prev_stride_len[nest_level] = stride_len[nest_level] + stride_len[nest_level] = 1 + if nest_level == 0: + end_of_array = end_of_item = True + else: + dims[nest_level - 1] += 1 + + elif ptr[0] == typdelim: + if parse_state not in (APS_ELEM_STARTED, APS_STRIDE_DONE): + raise _UnexpectedCharacter(array_text, ptr) + + if parse_state == APS_STRIDE_DONE: + parse_state = APS_STRIDE_DELIMITED + else: + parse_state = APS_ELEM_DELIMITED + end_of_item = True + stride_len[nest_level - 1] += 1 + + elif not apg_ascii_isspace(ptr[0]): + if parse_state not in (APS_STRIDE_STARTED, + APS_ELEM_STARTED, + APS_ELEM_DELIMITED): + raise _UnexpectedCharacter(array_text, ptr) + + parse_state = APS_ELEM_STARTED + array_is_empty = False + + if not end_of_item: + ptr += 1 + + if not array_is_empty: + dims[ndims[0] - 1] += 1 + + ptr += 1 + + # only whitespace is allowed after the closing brace + while ptr[0] != '\0': + if not apg_ascii_isspace(ptr[0]): + raise _UnexpectedCharacter(array_text, ptr) + + ptr += 1 + + if array_is_empty: + ndims[0] = 0 + + +cdef uint4_encode_ex(ConnectionSettings settings, WriteBuffer buf, object obj, + const void *arg): + return pgproto.uint4_encode(settings, buf, obj) + + +cdef uint4_decode_ex(ConnectionSettings settings, FRBuffer *buf, + const void *arg): + return pgproto.uint4_decode(settings, buf) + + +cdef arrayoid_encode(ConnectionSettings settings, WriteBuffer buf, items): + array_encode(settings, buf, items, OIDOID, + &uint4_encode_ex, NULL) + + +cdef arrayoid_decode(ConnectionSettings settings, FRBuffer *buf): + return array_decode(settings, buf, &uint4_decode_ex, NULL) + + +cdef text_encode_ex(ConnectionSettings settings, WriteBuffer buf, object obj, + const void *arg): + return pgproto.text_encode(settings, buf, obj) + + +cdef text_decode_ex(ConnectionSettings settings, FRBuffer *buf, + const void *arg): + return pgproto.text_decode(settings, buf) + + +cdef arraytext_encode(ConnectionSettings settings, WriteBuffer buf, items): + array_encode(settings, buf, items, TEXTOID, + &text_encode_ex, NULL) + + +cdef arraytext_decode(ConnectionSettings settings, FRBuffer *buf): + return array_decode(settings, buf, &text_decode_ex, NULL) + + +cdef init_array_codecs(): + # oid[] and text[] are registered as core codecs + # to make type introspection query work + # + register_core_codec(_OIDOID, + &arrayoid_encode, + &arrayoid_decode, + PG_FORMAT_BINARY) + + register_core_codec(_TEXTOID, + &arraytext_encode, + &arraytext_decode, + PG_FORMAT_BINARY) + +init_array_codecs() diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/base.pxd b/env/Lib/site-packages/asyncpg/protocol/codecs/base.pxd new file mode 100644 index 0000000..1cfed83 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/codecs/base.pxd @@ -0,0 +1,187 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +ctypedef object (*encode_func)(ConnectionSettings settings, + WriteBuffer buf, + object obj) + +ctypedef object (*decode_func)(ConnectionSettings settings, + FRBuffer *buf) + +ctypedef object (*codec_encode_func)(Codec codec, + ConnectionSettings settings, + WriteBuffer buf, + object obj) + +ctypedef object (*codec_decode_func)(Codec codec, + ConnectionSettings settings, + FRBuffer *buf) + + +cdef enum CodecType: + CODEC_UNDEFINED = 0 + CODEC_C = 1 + CODEC_PY = 2 + CODEC_ARRAY = 3 + CODEC_COMPOSITE = 4 + CODEC_RANGE = 5 + CODEC_MULTIRANGE = 6 + + +cdef enum ServerDataFormat: + PG_FORMAT_ANY = -1 + PG_FORMAT_TEXT = 0 + PG_FORMAT_BINARY = 1 + + +cdef enum ClientExchangeFormat: + PG_XFORMAT_OBJECT = 1 + PG_XFORMAT_TUPLE = 2 + + +cdef class Codec: + cdef: + uint32_t oid + + str name + str schema + str kind + + CodecType type + ServerDataFormat format + ClientExchangeFormat xformat + + encode_func c_encoder + decode_func c_decoder + Codec base_codec + + object py_encoder + object py_decoder + + # arrays + Codec element_codec + Py_UCS4 element_delimiter + + # composite types + tuple element_type_oids + object element_names + object record_desc + list element_codecs + + # Pointers to actual encoder/decoder functions for this codec + codec_encode_func encoder + codec_decode_func decoder + + cdef init(self, str name, str schema, str kind, + CodecType type, ServerDataFormat format, + ClientExchangeFormat xformat, + encode_func c_encoder, decode_func c_decoder, + Codec base_codec, + object py_encoder, object py_decoder, + Codec element_codec, tuple element_type_oids, + object element_names, list element_codecs, + Py_UCS4 element_delimiter) + + cdef encode_scalar(self, ConnectionSettings settings, WriteBuffer buf, + object obj) + + cdef encode_array(self, ConnectionSettings settings, WriteBuffer buf, + object obj) + + cdef encode_array_text(self, ConnectionSettings settings, WriteBuffer buf, + object obj) + + cdef encode_range(self, ConnectionSettings settings, WriteBuffer buf, + object obj) + + cdef encode_multirange(self, ConnectionSettings settings, WriteBuffer buf, + object obj) + + cdef encode_composite(self, ConnectionSettings settings, WriteBuffer buf, + object obj) + + cdef encode_in_python(self, ConnectionSettings settings, WriteBuffer buf, + object obj) + + cdef decode_scalar(self, ConnectionSettings settings, FRBuffer *buf) + + cdef decode_array(self, ConnectionSettings settings, FRBuffer *buf) + + cdef decode_array_text(self, ConnectionSettings settings, FRBuffer *buf) + + cdef decode_range(self, ConnectionSettings settings, FRBuffer *buf) + + cdef decode_multirange(self, ConnectionSettings settings, FRBuffer *buf) + + cdef decode_composite(self, ConnectionSettings settings, FRBuffer *buf) + + cdef decode_in_python(self, ConnectionSettings settings, FRBuffer *buf) + + cdef inline encode(self, + ConnectionSettings settings, + WriteBuffer buf, + object obj) + + cdef inline decode(self, ConnectionSettings settings, FRBuffer *buf) + + cdef has_encoder(self) + cdef has_decoder(self) + cdef is_binary(self) + + cdef inline Codec copy(self) + + @staticmethod + cdef Codec new_array_codec(uint32_t oid, + str name, + str schema, + Codec element_codec, + Py_UCS4 element_delimiter) + + @staticmethod + cdef Codec new_range_codec(uint32_t oid, + str name, + str schema, + Codec element_codec) + + @staticmethod + cdef Codec new_multirange_codec(uint32_t oid, + str name, + str schema, + Codec element_codec) + + @staticmethod + cdef Codec new_composite_codec(uint32_t oid, + str name, + str schema, + ServerDataFormat format, + list element_codecs, + tuple element_type_oids, + object element_names) + + @staticmethod + cdef Codec new_python_codec(uint32_t oid, + str name, + str schema, + str kind, + object encoder, + object decoder, + encode_func c_encoder, + decode_func c_decoder, + Codec base_codec, + ServerDataFormat format, + ClientExchangeFormat xformat) + + +cdef class DataCodecConfig: + cdef: + dict _derived_type_codecs + dict _custom_type_codecs + + cdef inline Codec get_codec(self, uint32_t oid, ServerDataFormat format, + bint ignore_custom_codec=*) + cdef inline Codec get_custom_codec(self, uint32_t oid, + ServerDataFormat format) diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/base.pyx b/env/Lib/site-packages/asyncpg/protocol/codecs/base.pyx new file mode 100644 index 0000000..c269e37 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/codecs/base.pyx @@ -0,0 +1,895 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from collections.abc import Mapping as MappingABC + +import asyncpg +from asyncpg import exceptions + + +cdef void* binary_codec_map[(MAXSUPPORTEDOID + 1) * 2] +cdef void* text_codec_map[(MAXSUPPORTEDOID + 1) * 2] +cdef dict EXTRA_CODECS = {} + + +@cython.final +cdef class Codec: + + def __cinit__(self, uint32_t oid): + self.oid = oid + self.type = CODEC_UNDEFINED + + cdef init( + self, + str name, + str schema, + str kind, + CodecType type, + ServerDataFormat format, + ClientExchangeFormat xformat, + encode_func c_encoder, + decode_func c_decoder, + Codec base_codec, + object py_encoder, + object py_decoder, + Codec element_codec, + tuple element_type_oids, + object element_names, + list element_codecs, + Py_UCS4 element_delimiter, + ): + + self.name = name + self.schema = schema + self.kind = kind + self.type = type + self.format = format + self.xformat = xformat + self.c_encoder = c_encoder + self.c_decoder = c_decoder + self.base_codec = base_codec + self.py_encoder = py_encoder + self.py_decoder = py_decoder + self.element_codec = element_codec + self.element_type_oids = element_type_oids + self.element_codecs = element_codecs + self.element_delimiter = element_delimiter + self.element_names = element_names + + if base_codec is not None: + if c_encoder != NULL or c_decoder != NULL: + raise exceptions.InternalClientError( + 'base_codec is mutually exclusive with c_encoder/c_decoder' + ) + + if element_names is not None: + self.record_desc = record.ApgRecordDesc_New( + element_names, tuple(element_names)) + else: + self.record_desc = None + + if type == CODEC_C: + self.encoder = &self.encode_scalar + self.decoder = &self.decode_scalar + elif type == CODEC_ARRAY: + if format == PG_FORMAT_BINARY: + self.encoder = &self.encode_array + self.decoder = &self.decode_array + else: + self.encoder = &self.encode_array_text + self.decoder = &self.decode_array_text + elif type == CODEC_RANGE: + if format != PG_FORMAT_BINARY: + raise exceptions.UnsupportedClientFeatureError( + 'cannot decode type "{}"."{}": text encoding of ' + 'range types is not supported'.format(schema, name)) + self.encoder = &self.encode_range + self.decoder = &self.decode_range + elif type == CODEC_MULTIRANGE: + if format != PG_FORMAT_BINARY: + raise exceptions.UnsupportedClientFeatureError( + 'cannot decode type "{}"."{}": text encoding of ' + 'range types is not supported'.format(schema, name)) + self.encoder = &self.encode_multirange + self.decoder = &self.decode_multirange + elif type == CODEC_COMPOSITE: + if format != PG_FORMAT_BINARY: + raise exceptions.UnsupportedClientFeatureError( + 'cannot decode type "{}"."{}": text encoding of ' + 'composite types is not supported'.format(schema, name)) + self.encoder = &self.encode_composite + self.decoder = &self.decode_composite + elif type == CODEC_PY: + self.encoder = &self.encode_in_python + self.decoder = &self.decode_in_python + else: + raise exceptions.InternalClientError( + 'unexpected codec type: {}'.format(type)) + + cdef Codec copy(self): + cdef Codec codec + + codec = Codec(self.oid) + codec.init(self.name, self.schema, self.kind, + self.type, self.format, self.xformat, + self.c_encoder, self.c_decoder, self.base_codec, + self.py_encoder, self.py_decoder, + self.element_codec, + self.element_type_oids, self.element_names, + self.element_codecs, self.element_delimiter) + + return codec + + cdef encode_scalar(self, ConnectionSettings settings, WriteBuffer buf, + object obj): + self.c_encoder(settings, buf, obj) + + cdef encode_array(self, ConnectionSettings settings, WriteBuffer buf, + object obj): + array_encode(settings, buf, obj, self.element_codec.oid, + codec_encode_func_ex, + (self.element_codec)) + + cdef encode_array_text(self, ConnectionSettings settings, WriteBuffer buf, + object obj): + return textarray_encode(settings, buf, obj, + codec_encode_func_ex, + (self.element_codec), + self.element_delimiter) + + cdef encode_range(self, ConnectionSettings settings, WriteBuffer buf, + object obj): + range_encode(settings, buf, obj, self.element_codec.oid, + codec_encode_func_ex, + (self.element_codec)) + + cdef encode_multirange(self, ConnectionSettings settings, WriteBuffer buf, + object obj): + multirange_encode(settings, buf, obj, self.element_codec.oid, + codec_encode_func_ex, + (self.element_codec)) + + cdef encode_composite(self, ConnectionSettings settings, WriteBuffer buf, + object obj): + cdef: + WriteBuffer elem_data + int i + list elem_codecs = self.element_codecs + ssize_t count + ssize_t composite_size + tuple rec + + if isinstance(obj, MappingABC): + # Input is dict-like, form a tuple + composite_size = len(self.element_type_oids) + rec = cpython.PyTuple_New(composite_size) + + for i in range(composite_size): + cpython.Py_INCREF(None) + cpython.PyTuple_SET_ITEM(rec, i, None) + + for field in obj: + try: + i = self.element_names[field] + except KeyError: + raise ValueError( + '{!r} is not a valid element of composite ' + 'type {}'.format(field, self.name)) from None + + item = obj[field] + cpython.Py_INCREF(item) + cpython.PyTuple_SET_ITEM(rec, i, item) + + obj = rec + + count = len(obj) + if count > _MAXINT32: + raise ValueError('too many elements in composite type record') + + elem_data = WriteBuffer.new() + i = 0 + for item in obj: + elem_data.write_int32(self.element_type_oids[i]) + if item is None: + elem_data.write_int32(-1) + else: + (elem_codecs[i]).encode(settings, elem_data, item) + i += 1 + + record_encode_frame(settings, buf, elem_data, count) + + cdef encode_in_python(self, ConnectionSettings settings, WriteBuffer buf, + object obj): + data = self.py_encoder(obj) + if self.xformat == PG_XFORMAT_OBJECT: + if self.format == PG_FORMAT_BINARY: + pgproto.bytea_encode(settings, buf, data) + elif self.format == PG_FORMAT_TEXT: + pgproto.text_encode(settings, buf, data) + else: + raise exceptions.InternalClientError( + 'unexpected data format: {}'.format(self.format)) + elif self.xformat == PG_XFORMAT_TUPLE: + if self.base_codec is not None: + self.base_codec.encode(settings, buf, data) + else: + self.c_encoder(settings, buf, data) + else: + raise exceptions.InternalClientError( + 'unexpected exchange format: {}'.format(self.xformat)) + + cdef encode(self, ConnectionSettings settings, WriteBuffer buf, + object obj): + return self.encoder(self, settings, buf, obj) + + cdef decode_scalar(self, ConnectionSettings settings, FRBuffer *buf): + return self.c_decoder(settings, buf) + + cdef decode_array(self, ConnectionSettings settings, FRBuffer *buf): + return array_decode(settings, buf, codec_decode_func_ex, + (self.element_codec)) + + cdef decode_array_text(self, ConnectionSettings settings, + FRBuffer *buf): + return textarray_decode(settings, buf, codec_decode_func_ex, + (self.element_codec), + self.element_delimiter) + + cdef decode_range(self, ConnectionSettings settings, FRBuffer *buf): + return range_decode(settings, buf, codec_decode_func_ex, + (self.element_codec)) + + cdef decode_multirange(self, ConnectionSettings settings, FRBuffer *buf): + return multirange_decode(settings, buf, codec_decode_func_ex, + (self.element_codec)) + + cdef decode_composite(self, ConnectionSettings settings, + FRBuffer *buf): + cdef: + object result + ssize_t elem_count + ssize_t i + int32_t elem_len + uint32_t elem_typ + uint32_t received_elem_typ + Codec elem_codec + FRBuffer elem_buf + + elem_count = hton.unpack_int32(frb_read(buf, 4)) + if elem_count != len(self.element_type_oids): + raise exceptions.OutdatedSchemaCacheError( + 'unexpected number of attributes of composite type: ' + '{}, expected {}' + .format( + elem_count, + len(self.element_type_oids), + ), + schema=self.schema, + data_type=self.name, + ) + result = record.ApgRecord_New(asyncpg.Record, self.record_desc, elem_count) + for i in range(elem_count): + elem_typ = self.element_type_oids[i] + received_elem_typ = hton.unpack_int32(frb_read(buf, 4)) + + if received_elem_typ != elem_typ: + raise exceptions.OutdatedSchemaCacheError( + 'unexpected data type of composite type attribute {}: ' + '{!r}, expected {!r}' + .format( + i, + BUILTIN_TYPE_OID_MAP.get( + received_elem_typ, received_elem_typ), + BUILTIN_TYPE_OID_MAP.get( + elem_typ, elem_typ) + ), + schema=self.schema, + data_type=self.name, + position=i, + ) + + elem_len = hton.unpack_int32(frb_read(buf, 4)) + if elem_len == -1: + elem = None + else: + elem_codec = self.element_codecs[i] + elem = elem_codec.decode( + settings, frb_slice_from(&elem_buf, buf, elem_len)) + + cpython.Py_INCREF(elem) + record.ApgRecord_SET_ITEM(result, i, elem) + + return result + + cdef decode_in_python(self, ConnectionSettings settings, + FRBuffer *buf): + if self.xformat == PG_XFORMAT_OBJECT: + if self.format == PG_FORMAT_BINARY: + data = pgproto.bytea_decode(settings, buf) + elif self.format == PG_FORMAT_TEXT: + data = pgproto.text_decode(settings, buf) + else: + raise exceptions.InternalClientError( + 'unexpected data format: {}'.format(self.format)) + elif self.xformat == PG_XFORMAT_TUPLE: + if self.base_codec is not None: + data = self.base_codec.decode(settings, buf) + else: + data = self.c_decoder(settings, buf) + else: + raise exceptions.InternalClientError( + 'unexpected exchange format: {}'.format(self.xformat)) + + return self.py_decoder(data) + + cdef inline decode(self, ConnectionSettings settings, FRBuffer *buf): + return self.decoder(self, settings, buf) + + cdef inline has_encoder(self): + cdef Codec elem_codec + + if self.c_encoder is not NULL or self.py_encoder is not None: + return True + + elif ( + self.type == CODEC_ARRAY + or self.type == CODEC_RANGE + or self.type == CODEC_MULTIRANGE + ): + return self.element_codec.has_encoder() + + elif self.type == CODEC_COMPOSITE: + for elem_codec in self.element_codecs: + if not elem_codec.has_encoder(): + return False + return True + + else: + return False + + cdef has_decoder(self): + cdef Codec elem_codec + + if self.c_decoder is not NULL or self.py_decoder is not None: + return True + + elif ( + self.type == CODEC_ARRAY + or self.type == CODEC_RANGE + or self.type == CODEC_MULTIRANGE + ): + return self.element_codec.has_decoder() + + elif self.type == CODEC_COMPOSITE: + for elem_codec in self.element_codecs: + if not elem_codec.has_decoder(): + return False + return True + + else: + return False + + cdef is_binary(self): + return self.format == PG_FORMAT_BINARY + + def __repr__(self): + return ''.format( + self.oid, + 'NA' if self.element_codec is None else self.element_codec.oid, + has_core_codec(self.oid)) + + @staticmethod + cdef Codec new_array_codec(uint32_t oid, + str name, + str schema, + Codec element_codec, + Py_UCS4 element_delimiter): + cdef Codec codec + codec = Codec(oid) + codec.init(name, schema, 'array', CODEC_ARRAY, element_codec.format, + PG_XFORMAT_OBJECT, NULL, NULL, None, None, None, + element_codec, None, None, None, element_delimiter) + return codec + + @staticmethod + cdef Codec new_range_codec(uint32_t oid, + str name, + str schema, + Codec element_codec): + cdef Codec codec + codec = Codec(oid) + codec.init(name, schema, 'range', CODEC_RANGE, element_codec.format, + PG_XFORMAT_OBJECT, NULL, NULL, None, None, None, + element_codec, None, None, None, 0) + return codec + + @staticmethod + cdef Codec new_multirange_codec(uint32_t oid, + str name, + str schema, + Codec element_codec): + cdef Codec codec + codec = Codec(oid) + codec.init(name, schema, 'multirange', CODEC_MULTIRANGE, + element_codec.format, PG_XFORMAT_OBJECT, NULL, NULL, None, + None, None, element_codec, None, None, None, 0) + return codec + + @staticmethod + cdef Codec new_composite_codec(uint32_t oid, + str name, + str schema, + ServerDataFormat format, + list element_codecs, + tuple element_type_oids, + object element_names): + cdef Codec codec + codec = Codec(oid) + codec.init(name, schema, 'composite', CODEC_COMPOSITE, + format, PG_XFORMAT_OBJECT, NULL, NULL, None, None, None, + None, element_type_oids, element_names, element_codecs, 0) + return codec + + @staticmethod + cdef Codec new_python_codec(uint32_t oid, + str name, + str schema, + str kind, + object encoder, + object decoder, + encode_func c_encoder, + decode_func c_decoder, + Codec base_codec, + ServerDataFormat format, + ClientExchangeFormat xformat): + cdef Codec codec + codec = Codec(oid) + codec.init(name, schema, kind, CODEC_PY, format, xformat, + c_encoder, c_decoder, base_codec, encoder, decoder, + None, None, None, None, 0) + return codec + + +# Encode callback for arrays +cdef codec_encode_func_ex(ConnectionSettings settings, WriteBuffer buf, + object obj, const void *arg): + return (arg).encode(settings, buf, obj) + + +# Decode callback for arrays +cdef codec_decode_func_ex(ConnectionSettings settings, FRBuffer *buf, + const void *arg): + return (arg).decode(settings, buf) + + +cdef uint32_t pylong_as_oid(val) except? 0xFFFFFFFFl: + cdef: + int64_t oid = 0 + bint overflow = False + + try: + oid = cpython.PyLong_AsLongLong(val) + except OverflowError: + overflow = True + + if overflow or (oid < 0 or oid > UINT32_MAX): + raise OverflowError('OID value too large: {!r}'.format(val)) + + return val + + +cdef class DataCodecConfig: + def __init__(self, cache_key): + # Codec instance cache for derived types: + # composites, arrays, ranges, domains and their combinations. + self._derived_type_codecs = {} + # Codec instances set up by the user for the connection. + self._custom_type_codecs = {} + + def add_types(self, types): + cdef: + Codec elem_codec + list comp_elem_codecs + ServerDataFormat format + ServerDataFormat elem_format + bint has_text_elements + Py_UCS4 elem_delim + + for ti in types: + oid = ti['oid'] + + if self.get_codec(oid, PG_FORMAT_ANY) is not None: + continue + + name = ti['name'] + schema = ti['ns'] + array_element_oid = ti['elemtype'] + range_subtype_oid = ti['range_subtype'] + if ti['attrtypoids']: + comp_type_attrs = tuple(ti['attrtypoids']) + else: + comp_type_attrs = None + base_type = ti['basetype'] + + if array_element_oid: + # Array type (note, there is no separate 'kind' for arrays) + + # Canonicalize type name to "elemtype[]" + if name.startswith('_'): + name = name[1:] + name = '{}[]'.format(name) + + elem_codec = self.get_codec(array_element_oid, PG_FORMAT_ANY) + if elem_codec is None: + elem_codec = self.declare_fallback_codec( + array_element_oid, ti['elemtype_name'], schema) + + elem_delim = ti['elemdelim'][0] + + self._derived_type_codecs[oid, elem_codec.format] = \ + Codec.new_array_codec( + oid, name, schema, elem_codec, elem_delim) + + elif ti['kind'] == b'c': + # Composite type + + if not comp_type_attrs: + raise exceptions.InternalClientError( + f'type record missing field types for composite {oid}') + + comp_elem_codecs = [] + has_text_elements = False + + for typoid in comp_type_attrs: + elem_codec = self.get_codec(typoid, PG_FORMAT_ANY) + if elem_codec is None: + raise exceptions.InternalClientError( + f'no codec for composite attribute type {typoid}') + if elem_codec.format is PG_FORMAT_TEXT: + has_text_elements = True + comp_elem_codecs.append(elem_codec) + + element_names = collections.OrderedDict() + for i, attrname in enumerate(ti['attrnames']): + element_names[attrname] = i + + # If at least one element is text-encoded, we must + # encode the whole composite as text. + if has_text_elements: + elem_format = PG_FORMAT_TEXT + else: + elem_format = PG_FORMAT_BINARY + + self._derived_type_codecs[oid, elem_format] = \ + Codec.new_composite_codec( + oid, name, schema, elem_format, comp_elem_codecs, + comp_type_attrs, element_names) + + elif ti['kind'] == b'd': + # Domain type + + if not base_type: + raise exceptions.InternalClientError( + f'type record missing base type for domain {oid}') + + elem_codec = self.get_codec(base_type, PG_FORMAT_ANY) + if elem_codec is None: + elem_codec = self.declare_fallback_codec( + base_type, ti['basetype_name'], schema) + + self._derived_type_codecs[oid, elem_codec.format] = elem_codec + + elif ti['kind'] == b'r': + # Range type + + if not range_subtype_oid: + raise exceptions.InternalClientError( + f'type record missing base type for range {oid}') + + elem_codec = self.get_codec(range_subtype_oid, PG_FORMAT_ANY) + if elem_codec is None: + elem_codec = self.declare_fallback_codec( + range_subtype_oid, ti['range_subtype_name'], schema) + + self._derived_type_codecs[oid, elem_codec.format] = \ + Codec.new_range_codec(oid, name, schema, elem_codec) + + elif ti['kind'] == b'm': + # Multirange type + + if not range_subtype_oid: + raise exceptions.InternalClientError( + f'type record missing base type for multirange {oid}') + + elem_codec = self.get_codec(range_subtype_oid, PG_FORMAT_ANY) + if elem_codec is None: + elem_codec = self.declare_fallback_codec( + range_subtype_oid, ti['range_subtype_name'], schema) + + self._derived_type_codecs[oid, elem_codec.format] = \ + Codec.new_multirange_codec(oid, name, schema, elem_codec) + + elif ti['kind'] == b'e': + # Enum types are essentially text + self._set_builtin_type_codec(oid, name, schema, 'scalar', + TEXTOID, PG_FORMAT_ANY) + else: + self.declare_fallback_codec(oid, name, schema) + + def add_python_codec(self, typeoid, typename, typeschema, typekind, + typeinfos, encoder, decoder, format, xformat): + cdef: + Codec core_codec = None + encode_func c_encoder = NULL + decode_func c_decoder = NULL + Codec base_codec = None + uint32_t oid = pylong_as_oid(typeoid) + bint codec_set = False + + # Clear all previous overrides (this also clears type cache). + self.remove_python_codec(typeoid, typename, typeschema) + + if typeinfos: + self.add_types(typeinfos) + + if format == PG_FORMAT_ANY: + formats = (PG_FORMAT_TEXT, PG_FORMAT_BINARY) + else: + formats = (format,) + + for fmt in formats: + if xformat == PG_XFORMAT_TUPLE: + if typekind == "scalar": + core_codec = get_core_codec(oid, fmt, xformat) + if core_codec is None: + continue + c_encoder = core_codec.c_encoder + c_decoder = core_codec.c_decoder + elif typekind == "composite": + base_codec = self.get_codec(oid, fmt) + if base_codec is None: + continue + + self._custom_type_codecs[typeoid, fmt] = \ + Codec.new_python_codec(oid, typename, typeschema, typekind, + encoder, decoder, c_encoder, c_decoder, + base_codec, fmt, xformat) + codec_set = True + + if not codec_set: + raise exceptions.InterfaceError( + "{} type does not support the 'tuple' exchange format".format( + typename)) + + def remove_python_codec(self, typeoid, typename, typeschema): + for fmt in (PG_FORMAT_BINARY, PG_FORMAT_TEXT): + self._custom_type_codecs.pop((typeoid, fmt), None) + self.clear_type_cache() + + def _set_builtin_type_codec(self, typeoid, typename, typeschema, typekind, + alias_to, format=PG_FORMAT_ANY): + cdef: + Codec codec + Codec target_codec + uint32_t oid = pylong_as_oid(typeoid) + uint32_t alias_oid = 0 + bint codec_set = False + + if format == PG_FORMAT_ANY: + formats = (PG_FORMAT_BINARY, PG_FORMAT_TEXT) + else: + formats = (format,) + + if isinstance(alias_to, int): + alias_oid = pylong_as_oid(alias_to) + else: + alias_oid = BUILTIN_TYPE_NAME_MAP.get(alias_to, 0) + + for format in formats: + if alias_oid != 0: + target_codec = self.get_codec(alias_oid, format) + else: + target_codec = get_extra_codec(alias_to, format) + + if target_codec is None: + continue + + codec = target_codec.copy() + codec.oid = typeoid + codec.name = typename + codec.schema = typeschema + codec.kind = typekind + + self._custom_type_codecs[typeoid, format] = codec + codec_set = True + + if not codec_set: + if format == PG_FORMAT_BINARY: + codec_str = 'binary' + elif format == PG_FORMAT_TEXT: + codec_str = 'text' + else: + codec_str = 'text or binary' + + raise exceptions.InterfaceError( + f'cannot alias {typename} to {alias_to}: ' + f'there is no {codec_str} codec for {alias_to}') + + def set_builtin_type_codec(self, typeoid, typename, typeschema, typekind, + alias_to, format=PG_FORMAT_ANY): + self._set_builtin_type_codec(typeoid, typename, typeschema, typekind, + alias_to, format) + self.clear_type_cache() + + def clear_type_cache(self): + self._derived_type_codecs.clear() + + def declare_fallback_codec(self, uint32_t oid, str name, str schema): + cdef Codec codec + + if oid <= MAXBUILTINOID: + # This is a BKI type, for which asyncpg has no + # defined codec. This should only happen for newly + # added builtin types, for which this version of + # asyncpg is lacking support. + # + raise exceptions.UnsupportedClientFeatureError( + f'unhandled standard data type {name!r} (OID {oid})') + else: + # This is a non-BKI type, and as such, has no + # stable OID, so no possibility of a builtin codec. + # In this case, fallback to text format. Applications + # can avoid this by specifying a codec for this type + # using Connection.set_type_codec(). + # + self._set_builtin_type_codec(oid, name, schema, 'scalar', + TEXTOID, PG_FORMAT_TEXT) + + codec = self.get_codec(oid, PG_FORMAT_TEXT) + + return codec + + cdef inline Codec get_codec(self, uint32_t oid, ServerDataFormat format, + bint ignore_custom_codec=False): + cdef Codec codec + + if format == PG_FORMAT_ANY: + codec = self.get_codec( + oid, PG_FORMAT_BINARY, ignore_custom_codec) + if codec is None: + codec = self.get_codec( + oid, PG_FORMAT_TEXT, ignore_custom_codec) + return codec + else: + if not ignore_custom_codec: + codec = self.get_custom_codec(oid, PG_FORMAT_ANY) + if codec is not None: + if codec.format != format: + # The codec for this OID has been overridden by + # set_{builtin}_type_codec with a different format. + # We must respect that and not return a core codec. + return None + else: + return codec + + codec = get_core_codec(oid, format) + if codec is not None: + return codec + else: + try: + return self._derived_type_codecs[oid, format] + except KeyError: + return None + + cdef inline Codec get_custom_codec( + self, + uint32_t oid, + ServerDataFormat format + ): + cdef Codec codec + + if format == PG_FORMAT_ANY: + codec = self.get_custom_codec(oid, PG_FORMAT_BINARY) + if codec is None: + codec = self.get_custom_codec(oid, PG_FORMAT_TEXT) + else: + codec = self._custom_type_codecs.get((oid, format)) + + return codec + + +cdef inline Codec get_core_codec( + uint32_t oid, ServerDataFormat format, + ClientExchangeFormat xformat=PG_XFORMAT_OBJECT): + cdef: + void *ptr = NULL + + if oid > MAXSUPPORTEDOID: + return None + if format == PG_FORMAT_BINARY: + ptr = binary_codec_map[oid * xformat] + elif format == PG_FORMAT_TEXT: + ptr = text_codec_map[oid * xformat] + + if ptr is NULL: + return None + else: + return ptr + + +cdef inline Codec get_any_core_codec( + uint32_t oid, ServerDataFormat format, + ClientExchangeFormat xformat=PG_XFORMAT_OBJECT): + """A version of get_core_codec that accepts PG_FORMAT_ANY.""" + cdef: + Codec codec + + if format == PG_FORMAT_ANY: + codec = get_core_codec(oid, PG_FORMAT_BINARY, xformat) + if codec is None: + codec = get_core_codec(oid, PG_FORMAT_TEXT, xformat) + else: + codec = get_core_codec(oid, format, xformat) + + return codec + + +cdef inline int has_core_codec(uint32_t oid): + return binary_codec_map[oid] != NULL or text_codec_map[oid] != NULL + + +cdef register_core_codec(uint32_t oid, + encode_func encode, + decode_func decode, + ServerDataFormat format, + ClientExchangeFormat xformat=PG_XFORMAT_OBJECT): + + if oid > MAXSUPPORTEDOID: + raise exceptions.InternalClientError( + 'cannot register core codec for OID {}: it is greater ' + 'than MAXSUPPORTEDOID ({})'.format(oid, MAXSUPPORTEDOID)) + + cdef: + Codec codec + str name + str kind + + name = BUILTIN_TYPE_OID_MAP[oid] + kind = 'array' if oid in ARRAY_TYPES else 'scalar' + + codec = Codec(oid) + codec.init(name, 'pg_catalog', kind, CODEC_C, format, xformat, + encode, decode, None, None, None, None, None, None, None, 0) + cpython.Py_INCREF(codec) # immortalize + + if format == PG_FORMAT_BINARY: + binary_codec_map[oid * xformat] = codec + elif format == PG_FORMAT_TEXT: + text_codec_map[oid * xformat] = codec + else: + raise exceptions.InternalClientError( + 'invalid data format: {}'.format(format)) + + +cdef register_extra_codec(str name, + encode_func encode, + decode_func decode, + ServerDataFormat format): + cdef: + Codec codec + str kind + + kind = 'scalar' + + codec = Codec(INVALIDOID) + codec.init(name, None, kind, CODEC_C, format, PG_XFORMAT_OBJECT, + encode, decode, None, None, None, None, None, None, None, 0) + EXTRA_CODECS[name, format] = codec + + +cdef inline Codec get_extra_codec(str name, ServerDataFormat format): + return EXTRA_CODECS.get((name, format)) diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/pgproto.pyx b/env/Lib/site-packages/asyncpg/protocol/codecs/pgproto.pyx new file mode 100644 index 0000000..51d650d --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/codecs/pgproto.pyx @@ -0,0 +1,484 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef init_bits_codecs(): + register_core_codec(BITOID, + pgproto.bits_encode, + pgproto.bits_decode, + PG_FORMAT_BINARY) + + register_core_codec(VARBITOID, + pgproto.bits_encode, + pgproto.bits_decode, + PG_FORMAT_BINARY) + + +cdef init_bytea_codecs(): + register_core_codec(BYTEAOID, + pgproto.bytea_encode, + pgproto.bytea_decode, + PG_FORMAT_BINARY) + + register_core_codec(CHAROID, + pgproto.bytea_encode, + pgproto.bytea_decode, + PG_FORMAT_BINARY) + + +cdef init_datetime_codecs(): + register_core_codec(DATEOID, + pgproto.date_encode, + pgproto.date_decode, + PG_FORMAT_BINARY) + + register_core_codec(DATEOID, + pgproto.date_encode_tuple, + pgproto.date_decode_tuple, + PG_FORMAT_BINARY, + PG_XFORMAT_TUPLE) + + register_core_codec(TIMEOID, + pgproto.time_encode, + pgproto.time_decode, + PG_FORMAT_BINARY) + + register_core_codec(TIMEOID, + pgproto.time_encode_tuple, + pgproto.time_decode_tuple, + PG_FORMAT_BINARY, + PG_XFORMAT_TUPLE) + + register_core_codec(TIMETZOID, + pgproto.timetz_encode, + pgproto.timetz_decode, + PG_FORMAT_BINARY) + + register_core_codec(TIMETZOID, + pgproto.timetz_encode_tuple, + pgproto.timetz_decode_tuple, + PG_FORMAT_BINARY, + PG_XFORMAT_TUPLE) + + register_core_codec(TIMESTAMPOID, + pgproto.timestamp_encode, + pgproto.timestamp_decode, + PG_FORMAT_BINARY) + + register_core_codec(TIMESTAMPOID, + pgproto.timestamp_encode_tuple, + pgproto.timestamp_decode_tuple, + PG_FORMAT_BINARY, + PG_XFORMAT_TUPLE) + + register_core_codec(TIMESTAMPTZOID, + pgproto.timestamptz_encode, + pgproto.timestamptz_decode, + PG_FORMAT_BINARY) + + register_core_codec(TIMESTAMPTZOID, + pgproto.timestamp_encode_tuple, + pgproto.timestamp_decode_tuple, + PG_FORMAT_BINARY, + PG_XFORMAT_TUPLE) + + register_core_codec(INTERVALOID, + pgproto.interval_encode, + pgproto.interval_decode, + PG_FORMAT_BINARY) + + register_core_codec(INTERVALOID, + pgproto.interval_encode_tuple, + pgproto.interval_decode_tuple, + PG_FORMAT_BINARY, + PG_XFORMAT_TUPLE) + + # For obsolete abstime/reltime/tinterval, we do not bother to + # interpret the value, and simply return and pass it as text. + # + register_core_codec(ABSTIMEOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + register_core_codec(RELTIMEOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + register_core_codec(TINTERVALOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + +cdef init_float_codecs(): + register_core_codec(FLOAT4OID, + pgproto.float4_encode, + pgproto.float4_decode, + PG_FORMAT_BINARY) + + register_core_codec(FLOAT8OID, + pgproto.float8_encode, + pgproto.float8_decode, + PG_FORMAT_BINARY) + + +cdef init_geometry_codecs(): + register_core_codec(BOXOID, + pgproto.box_encode, + pgproto.box_decode, + PG_FORMAT_BINARY) + + register_core_codec(LINEOID, + pgproto.line_encode, + pgproto.line_decode, + PG_FORMAT_BINARY) + + register_core_codec(LSEGOID, + pgproto.lseg_encode, + pgproto.lseg_decode, + PG_FORMAT_BINARY) + + register_core_codec(POINTOID, + pgproto.point_encode, + pgproto.point_decode, + PG_FORMAT_BINARY) + + register_core_codec(PATHOID, + pgproto.path_encode, + pgproto.path_decode, + PG_FORMAT_BINARY) + + register_core_codec(POLYGONOID, + pgproto.poly_encode, + pgproto.poly_decode, + PG_FORMAT_BINARY) + + register_core_codec(CIRCLEOID, + pgproto.circle_encode, + pgproto.circle_decode, + PG_FORMAT_BINARY) + + +cdef init_hstore_codecs(): + register_extra_codec('pg_contrib.hstore', + pgproto.hstore_encode, + pgproto.hstore_decode, + PG_FORMAT_BINARY) + + +cdef init_json_codecs(): + register_core_codec(JSONOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_BINARY) + register_core_codec(JSONBOID, + pgproto.jsonb_encode, + pgproto.jsonb_decode, + PG_FORMAT_BINARY) + register_core_codec(JSONPATHOID, + pgproto.jsonpath_encode, + pgproto.jsonpath_decode, + PG_FORMAT_BINARY) + + +cdef init_int_codecs(): + + register_core_codec(BOOLOID, + pgproto.bool_encode, + pgproto.bool_decode, + PG_FORMAT_BINARY) + + register_core_codec(INT2OID, + pgproto.int2_encode, + pgproto.int2_decode, + PG_FORMAT_BINARY) + + register_core_codec(INT4OID, + pgproto.int4_encode, + pgproto.int4_decode, + PG_FORMAT_BINARY) + + register_core_codec(INT8OID, + pgproto.int8_encode, + pgproto.int8_decode, + PG_FORMAT_BINARY) + + +cdef init_pseudo_codecs(): + # Void type is returned by SELECT void_returning_function() + register_core_codec(VOIDOID, + pgproto.void_encode, + pgproto.void_decode, + PG_FORMAT_BINARY) + + # Unknown type, always decoded as text + register_core_codec(UNKNOWNOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + # OID and friends + oid_types = [ + OIDOID, XIDOID, CIDOID + ] + + for oid_type in oid_types: + register_core_codec(oid_type, + pgproto.uint4_encode, + pgproto.uint4_decode, + PG_FORMAT_BINARY) + + # 64-bit OID types + oid8_types = [ + XID8OID, + ] + + for oid_type in oid8_types: + register_core_codec(oid_type, + pgproto.uint8_encode, + pgproto.uint8_decode, + PG_FORMAT_BINARY) + + # reg* types -- these are really system catalog OIDs, but + # allow the catalog object name as an input. We could just + # decode these as OIDs, but handling them as text seems more + # useful. + # + reg_types = [ + REGPROCOID, REGPROCEDUREOID, REGOPEROID, REGOPERATOROID, + REGCLASSOID, REGTYPEOID, REGCONFIGOID, REGDICTIONARYOID, + REGNAMESPACEOID, REGROLEOID, REFCURSOROID, REGCOLLATIONOID, + ] + + for reg_type in reg_types: + register_core_codec(reg_type, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + # cstring type is used by Postgres' I/O functions + register_core_codec(CSTRINGOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_BINARY) + + # various system pseudotypes with no I/O + no_io_types = [ + ANYOID, TRIGGEROID, EVENT_TRIGGEROID, LANGUAGE_HANDLEROID, + FDW_HANDLEROID, TSM_HANDLEROID, INTERNALOID, OPAQUEOID, + ANYELEMENTOID, ANYNONARRAYOID, ANYCOMPATIBLEOID, + ANYCOMPATIBLEARRAYOID, ANYCOMPATIBLENONARRAYOID, + ANYCOMPATIBLERANGEOID, ANYCOMPATIBLEMULTIRANGEOID, + ANYRANGEOID, ANYMULTIRANGEOID, ANYARRAYOID, + PG_DDL_COMMANDOID, INDEX_AM_HANDLEROID, TABLE_AM_HANDLEROID, + ] + + register_core_codec(ANYENUMOID, + NULL, + pgproto.text_decode, + PG_FORMAT_TEXT) + + for no_io_type in no_io_types: + register_core_codec(no_io_type, + NULL, + NULL, + PG_FORMAT_BINARY) + + # ACL specification string + register_core_codec(ACLITEMOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + # Postgres' serialized expression tree type + register_core_codec(PG_NODE_TREEOID, + NULL, + pgproto.text_decode, + PG_FORMAT_TEXT) + + # pg_lsn type -- a pointer to a location in the XLOG. + register_core_codec(PG_LSNOID, + pgproto.int8_encode, + pgproto.int8_decode, + PG_FORMAT_BINARY) + + register_core_codec(SMGROID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + # pg_dependencies and pg_ndistinct are special types + # used in pg_statistic_ext columns. + register_core_codec(PG_DEPENDENCIESOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + register_core_codec(PG_NDISTINCTOID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + # pg_mcv_list is a special type used in pg_statistic_ext_data + # system catalog + register_core_codec(PG_MCV_LISTOID, + pgproto.bytea_encode, + pgproto.bytea_decode, + PG_FORMAT_BINARY) + + # These two are internal to BRIN index support and are unlikely + # to be sent, but since I/O functions for these exist, add decoders + # nonetheless. + register_core_codec(PG_BRIN_BLOOM_SUMMARYOID, + NULL, + pgproto.bytea_decode, + PG_FORMAT_BINARY) + + register_core_codec(PG_BRIN_MINMAX_MULTI_SUMMARYOID, + NULL, + pgproto.bytea_decode, + PG_FORMAT_BINARY) + + +cdef init_text_codecs(): + textoids = [ + NAMEOID, + BPCHAROID, + VARCHAROID, + TEXTOID, + XMLOID + ] + + for oid in textoids: + register_core_codec(oid, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_BINARY) + + register_core_codec(oid, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + +cdef init_tid_codecs(): + register_core_codec(TIDOID, + pgproto.tid_encode, + pgproto.tid_decode, + PG_FORMAT_BINARY) + + +cdef init_txid_codecs(): + register_core_codec(TXID_SNAPSHOTOID, + pgproto.pg_snapshot_encode, + pgproto.pg_snapshot_decode, + PG_FORMAT_BINARY) + + register_core_codec(PG_SNAPSHOTOID, + pgproto.pg_snapshot_encode, + pgproto.pg_snapshot_decode, + PG_FORMAT_BINARY) + + +cdef init_tsearch_codecs(): + ts_oids = [ + TSQUERYOID, + TSVECTOROID, + ] + + for oid in ts_oids: + register_core_codec(oid, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + register_core_codec(GTSVECTOROID, + NULL, + pgproto.text_decode, + PG_FORMAT_TEXT) + + +cdef init_uuid_codecs(): + register_core_codec(UUIDOID, + pgproto.uuid_encode, + pgproto.uuid_decode, + PG_FORMAT_BINARY) + + +cdef init_numeric_codecs(): + register_core_codec(NUMERICOID, + pgproto.numeric_encode_text, + pgproto.numeric_decode_text, + PG_FORMAT_TEXT) + + register_core_codec(NUMERICOID, + pgproto.numeric_encode_binary, + pgproto.numeric_decode_binary, + PG_FORMAT_BINARY) + + +cdef init_network_codecs(): + register_core_codec(CIDROID, + pgproto.cidr_encode, + pgproto.cidr_decode, + PG_FORMAT_BINARY) + + register_core_codec(INETOID, + pgproto.inet_encode, + pgproto.inet_decode, + PG_FORMAT_BINARY) + + register_core_codec(MACADDROID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + register_core_codec(MACADDR8OID, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + +cdef init_monetary_codecs(): + moneyoids = [ + MONEYOID, + ] + + for oid in moneyoids: + register_core_codec(oid, + pgproto.text_encode, + pgproto.text_decode, + PG_FORMAT_TEXT) + + +cdef init_all_pgproto_codecs(): + # Builtin types, in lexicographical order. + init_bits_codecs() + init_bytea_codecs() + init_datetime_codecs() + init_float_codecs() + init_geometry_codecs() + init_int_codecs() + init_json_codecs() + init_monetary_codecs() + init_network_codecs() + init_numeric_codecs() + init_text_codecs() + init_tid_codecs() + init_tsearch_codecs() + init_txid_codecs() + init_uuid_codecs() + + # Various pseudotypes and system types + init_pseudo_codecs() + + # contrib + init_hstore_codecs() + + +init_all_pgproto_codecs() diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/range.pyx b/env/Lib/site-packages/asyncpg/protocol/codecs/range.pyx new file mode 100644 index 0000000..1038c18 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/codecs/range.pyx @@ -0,0 +1,207 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from asyncpg import types as apg_types + +from collections.abc import Sequence as SequenceABC + +# defined in postgresql/src/include/utils/rangetypes.h +DEF RANGE_EMPTY = 0x01 # range is empty +DEF RANGE_LB_INC = 0x02 # lower bound is inclusive +DEF RANGE_UB_INC = 0x04 # upper bound is inclusive +DEF RANGE_LB_INF = 0x08 # lower bound is -infinity +DEF RANGE_UB_INF = 0x10 # upper bound is +infinity + + +cdef enum _RangeArgumentType: + _RANGE_ARGUMENT_INVALID = 0 + _RANGE_ARGUMENT_TUPLE = 1 + _RANGE_ARGUMENT_RANGE = 2 + + +cdef inline bint _range_has_lbound(uint8_t flags): + return not (flags & (RANGE_EMPTY | RANGE_LB_INF)) + + +cdef inline bint _range_has_ubound(uint8_t flags): + return not (flags & (RANGE_EMPTY | RANGE_UB_INF)) + + +cdef inline _RangeArgumentType _range_type(object obj): + if cpython.PyTuple_Check(obj) or cpython.PyList_Check(obj): + return _RANGE_ARGUMENT_TUPLE + elif isinstance(obj, apg_types.Range): + return _RANGE_ARGUMENT_RANGE + else: + return _RANGE_ARGUMENT_INVALID + + +cdef range_encode(ConnectionSettings settings, WriteBuffer buf, + object obj, uint32_t elem_oid, + encode_func_ex encoder, const void *encoder_arg): + cdef: + ssize_t obj_len + uint8_t flags = 0 + object lower = None + object upper = None + WriteBuffer bounds_data = WriteBuffer.new() + _RangeArgumentType arg_type = _range_type(obj) + + if arg_type == _RANGE_ARGUMENT_INVALID: + raise TypeError( + 'list, tuple or Range object expected (got type {})'.format( + type(obj))) + + elif arg_type == _RANGE_ARGUMENT_TUPLE: + obj_len = len(obj) + if obj_len == 2: + lower = obj[0] + upper = obj[1] + + if lower is None: + flags |= RANGE_LB_INF + + if upper is None: + flags |= RANGE_UB_INF + + flags |= RANGE_LB_INC | RANGE_UB_INC + + elif obj_len == 1: + lower = obj[0] + flags |= RANGE_LB_INC | RANGE_UB_INF + + elif obj_len == 0: + flags |= RANGE_EMPTY + + else: + raise ValueError( + 'expected 0, 1 or 2 elements in range (got {})'.format( + obj_len)) + + else: + if obj.isempty: + flags |= RANGE_EMPTY + else: + lower = obj.lower + upper = obj.upper + + if obj.lower_inc: + flags |= RANGE_LB_INC + elif lower is None: + flags |= RANGE_LB_INF + + if obj.upper_inc: + flags |= RANGE_UB_INC + elif upper is None: + flags |= RANGE_UB_INF + + if _range_has_lbound(flags): + encoder(settings, bounds_data, lower, encoder_arg) + + if _range_has_ubound(flags): + encoder(settings, bounds_data, upper, encoder_arg) + + buf.write_int32(1 + bounds_data.len()) + buf.write_byte(flags) + buf.write_buffer(bounds_data) + + +cdef range_decode(ConnectionSettings settings, FRBuffer *buf, + decode_func_ex decoder, const void *decoder_arg): + cdef: + uint8_t flags = frb_read(buf, 1)[0] + int32_t bound_len + object lower = None + object upper = None + FRBuffer bound_buf + + if _range_has_lbound(flags): + bound_len = hton.unpack_int32(frb_read(buf, 4)) + if bound_len == -1: + lower = None + else: + frb_slice_from(&bound_buf, buf, bound_len) + lower = decoder(settings, &bound_buf, decoder_arg) + + if _range_has_ubound(flags): + bound_len = hton.unpack_int32(frb_read(buf, 4)) + if bound_len == -1: + upper = None + else: + frb_slice_from(&bound_buf, buf, bound_len) + upper = decoder(settings, &bound_buf, decoder_arg) + + return apg_types.Range(lower=lower, upper=upper, + lower_inc=(flags & RANGE_LB_INC) != 0, + upper_inc=(flags & RANGE_UB_INC) != 0, + empty=(flags & RANGE_EMPTY) != 0) + + +cdef multirange_encode(ConnectionSettings settings, WriteBuffer buf, + object obj, uint32_t elem_oid, + encode_func_ex encoder, const void *encoder_arg): + cdef: + WriteBuffer elem_data + ssize_t elem_data_len + ssize_t elem_count + + if not isinstance(obj, SequenceABC): + raise TypeError( + 'expected a sequence (got type {!r})'.format(type(obj).__name__) + ) + + elem_data = WriteBuffer.new() + + for elem in obj: + range_encode(settings, elem_data, elem, elem_oid, encoder, encoder_arg) + + elem_count = len(obj) + if elem_count > INT32_MAX: + raise OverflowError(f'too many elements in multirange value') + + elem_data_len = elem_data.len() + if elem_data_len > INT32_MAX - 4: + raise OverflowError( + f'size of encoded multirange datum exceeds the maximum allowed' + f' {INT32_MAX - 4} bytes') + + # Datum length + buf.write_int32(4 + elem_data_len) + # Number of elements in multirange + buf.write_int32(elem_count) + buf.write_buffer(elem_data) + + +cdef multirange_decode(ConnectionSettings settings, FRBuffer *buf, + decode_func_ex decoder, const void *decoder_arg): + cdef: + int32_t nelems = hton.unpack_int32(frb_read(buf, 4)) + FRBuffer elem_buf + int32_t elem_len + int i + list result + + if nelems == 0: + return [] + + if nelems < 0: + raise exceptions.ProtocolError( + 'unexpected multirange size value: {}'.format(nelems)) + + result = cpython.PyList_New(nelems) + for i in range(nelems): + elem_len = hton.unpack_int32(frb_read(buf, 4)) + if elem_len == -1: + raise exceptions.ProtocolError( + 'unexpected NULL element in multirange value') + else: + frb_slice_from(&elem_buf, buf, elem_len) + elem = range_decode(settings, &elem_buf, decoder, decoder_arg) + cpython.Py_INCREF(elem) + cpython.PyList_SET_ITEM(result, i, elem) + + return result diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/record.pyx b/env/Lib/site-packages/asyncpg/protocol/codecs/record.pyx new file mode 100644 index 0000000..6446f2d --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/codecs/record.pyx @@ -0,0 +1,71 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from asyncpg import exceptions + + +cdef inline record_encode_frame(ConnectionSettings settings, WriteBuffer buf, + WriteBuffer elem_data, int32_t elem_count): + buf.write_int32(4 + elem_data.len()) + # attribute count + buf.write_int32(elem_count) + # encoded attribute data + buf.write_buffer(elem_data) + + +cdef anonymous_record_decode(ConnectionSettings settings, FRBuffer *buf): + cdef: + tuple result + ssize_t elem_count + ssize_t i + int32_t elem_len + uint32_t elem_typ + Codec elem_codec + FRBuffer elem_buf + + elem_count = hton.unpack_int32(frb_read(buf, 4)) + result = cpython.PyTuple_New(elem_count) + + for i in range(elem_count): + elem_typ = hton.unpack_int32(frb_read(buf, 4)) + elem_len = hton.unpack_int32(frb_read(buf, 4)) + + if elem_len == -1: + elem = None + else: + elem_codec = settings.get_data_codec(elem_typ) + if elem_codec is None or not elem_codec.has_decoder(): + raise exceptions.InternalClientError( + 'no decoder for composite type element in ' + 'position {} of type OID {}'.format(i, elem_typ)) + elem = elem_codec.decode(settings, + frb_slice_from(&elem_buf, buf, elem_len)) + + cpython.Py_INCREF(elem) + cpython.PyTuple_SET_ITEM(result, i, elem) + + return result + + +cdef anonymous_record_encode(ConnectionSettings settings, WriteBuffer buf, obj): + raise exceptions.UnsupportedClientFeatureError( + 'input of anonymous composite types is not supported', + hint=( + 'Consider declaring an explicit composite type and ' + 'using it to cast the argument.' + ), + detail='PostgreSQL does not implement anonymous composite type input.' + ) + + +cdef init_record_codecs(): + register_core_codec(RECORDOID, + anonymous_record_encode, + anonymous_record_decode, + PG_FORMAT_BINARY) + +init_record_codecs() diff --git a/env/Lib/site-packages/asyncpg/protocol/codecs/textutils.pyx b/env/Lib/site-packages/asyncpg/protocol/codecs/textutils.pyx new file mode 100644 index 0000000..dfaf29e --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/codecs/textutils.pyx @@ -0,0 +1,99 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef inline uint32_t _apg_tolower(uint32_t c): + if c >= 'A' and c <= 'Z': + return c + 'a' - 'A' + else: + return c + + +cdef int apg_strcasecmp(const Py_UCS4 *s1, const Py_UCS4 *s2): + cdef: + uint32_t c1 + uint32_t c2 + int i = 0 + + while True: + c1 = s1[i] + c2 = s2[i] + + if c1 != c2: + c1 = _apg_tolower(c1) + c2 = _apg_tolower(c2) + if c1 != c2: + return c1 - c2 + + if c1 == 0 or c2 == 0: + break + + i += 1 + + return 0 + + +cdef int apg_strcasecmp_char(const char *s1, const char *s2): + cdef: + uint8_t c1 + uint8_t c2 + int i = 0 + + while True: + c1 = s1[i] + c2 = s2[i] + + if c1 != c2: + c1 = _apg_tolower(c1) + c2 = _apg_tolower(c2) + if c1 != c2: + return c1 - c2 + + if c1 == 0 or c2 == 0: + break + + i += 1 + + return 0 + + +cdef inline bint apg_ascii_isspace(Py_UCS4 ch): + return ( + ch == ' ' or + ch == '\n' or + ch == '\r' or + ch == '\t' or + ch == '\v' or + ch == '\f' + ) + + +cdef Py_UCS4 *apg_parse_int32(Py_UCS4 *buf, int32_t *num): + cdef: + Py_UCS4 *p + int32_t n = 0 + int32_t neg = 0 + + if buf[0] == '-': + neg = 1 + buf += 1 + elif buf[0] == '+': + buf += 1 + + p = buf + while p[0] >= '0' and p[0] <= '9': + n = 10 * n - (p[0] - '0') + p += 1 + + if p == buf: + return NULL + + if not neg: + n = -n + + num[0] = n + + return p diff --git a/env/Lib/site-packages/asyncpg/protocol/consts.pxi b/env/Lib/site-packages/asyncpg/protocol/consts.pxi new file mode 100644 index 0000000..e1f8726 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/consts.pxi @@ -0,0 +1,12 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +DEF _MAXINT32 = 2**31 - 1 +DEF _COPY_BUFFER_SIZE = 524288 +DEF _COPY_SIGNATURE = b"PGCOPY\n\377\r\n\0" +DEF _EXECUTE_MANY_BUF_NUM = 4 +DEF _EXECUTE_MANY_BUF_SIZE = 32768 diff --git a/env/Lib/site-packages/asyncpg/protocol/coreproto.pxd b/env/Lib/site-packages/asyncpg/protocol/coreproto.pxd new file mode 100644 index 0000000..7ce4f57 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/coreproto.pxd @@ -0,0 +1,195 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +include "scram.pxd" + + +cdef enum ConnectionStatus: + CONNECTION_OK = 1 + CONNECTION_BAD = 2 + CONNECTION_STARTED = 3 # Waiting for connection to be made. + + +cdef enum ProtocolState: + PROTOCOL_IDLE = 0 + + PROTOCOL_FAILED = 1 + PROTOCOL_ERROR_CONSUME = 2 + PROTOCOL_CANCELLED = 3 + PROTOCOL_TERMINATING = 4 + + PROTOCOL_AUTH = 10 + PROTOCOL_PREPARE = 11 + PROTOCOL_BIND_EXECUTE = 12 + PROTOCOL_BIND_EXECUTE_MANY = 13 + PROTOCOL_CLOSE_STMT_PORTAL = 14 + PROTOCOL_SIMPLE_QUERY = 15 + PROTOCOL_EXECUTE = 16 + PROTOCOL_BIND = 17 + PROTOCOL_COPY_OUT = 18 + PROTOCOL_COPY_OUT_DATA = 19 + PROTOCOL_COPY_OUT_DONE = 20 + PROTOCOL_COPY_IN = 21 + PROTOCOL_COPY_IN_DATA = 22 + + +cdef enum AuthenticationMessage: + AUTH_SUCCESSFUL = 0 + AUTH_REQUIRED_KERBEROS = 2 + AUTH_REQUIRED_PASSWORD = 3 + AUTH_REQUIRED_PASSWORDMD5 = 5 + AUTH_REQUIRED_SCMCRED = 6 + AUTH_REQUIRED_GSS = 7 + AUTH_REQUIRED_GSS_CONTINUE = 8 + AUTH_REQUIRED_SSPI = 9 + AUTH_REQUIRED_SASL = 10 + AUTH_SASL_CONTINUE = 11 + AUTH_SASL_FINAL = 12 + + +AUTH_METHOD_NAME = { + AUTH_REQUIRED_KERBEROS: 'kerberosv5', + AUTH_REQUIRED_PASSWORD: 'password', + AUTH_REQUIRED_PASSWORDMD5: 'md5', + AUTH_REQUIRED_GSS: 'gss', + AUTH_REQUIRED_SASL: 'scram-sha-256', + AUTH_REQUIRED_SSPI: 'sspi', +} + + +cdef enum ResultType: + RESULT_OK = 1 + RESULT_FAILED = 2 + + +cdef enum TransactionStatus: + PQTRANS_IDLE = 0 # connection idle + PQTRANS_ACTIVE = 1 # command in progress + PQTRANS_INTRANS = 2 # idle, within transaction block + PQTRANS_INERROR = 3 # idle, within failed transaction + PQTRANS_UNKNOWN = 4 # cannot determine status + + +ctypedef object (*decode_row_method)(object, const char*, ssize_t) + + +cdef class CoreProtocol: + cdef: + ReadBuffer buffer + bint _skip_discard + bint _discard_data + + # executemany support data + object _execute_iter + str _execute_portal_name + str _execute_stmt_name + + ConnectionStatus con_status + ProtocolState state + TransactionStatus xact_status + + str encoding + + object transport + + # Instance of _ConnectionParameters + object con_params + # Instance of SCRAMAuthentication + SCRAMAuthentication scram + + readonly int32_t backend_pid + readonly int32_t backend_secret + + ## Result + ResultType result_type + object result + bytes result_param_desc + bytes result_row_desc + bytes result_status_msg + + # True - completed, False - suspended + bint result_execute_completed + + cpdef is_in_transaction(self) + cdef _process__auth(self, char mtype) + cdef _process__prepare(self, char mtype) + cdef _process__bind_execute(self, char mtype) + cdef _process__bind_execute_many(self, char mtype) + cdef _process__close_stmt_portal(self, char mtype) + cdef _process__simple_query(self, char mtype) + cdef _process__bind(self, char mtype) + cdef _process__copy_out(self, char mtype) + cdef _process__copy_out_data(self, char mtype) + cdef _process__copy_in(self, char mtype) + cdef _process__copy_in_data(self, char mtype) + + cdef _parse_msg_authentication(self) + cdef _parse_msg_parameter_status(self) + cdef _parse_msg_notification(self) + cdef _parse_msg_backend_key_data(self) + cdef _parse_msg_ready_for_query(self) + cdef _parse_data_msgs(self) + cdef _parse_copy_data_msgs(self) + cdef _parse_msg_error_response(self, is_error) + cdef _parse_msg_command_complete(self) + + cdef _write_copy_data_msg(self, object data) + cdef _write_copy_done_msg(self) + cdef _write_copy_fail_msg(self, str cause) + + cdef _auth_password_message_cleartext(self) + cdef _auth_password_message_md5(self, bytes salt) + cdef _auth_password_message_sasl_initial(self, list sasl_auth_methods) + cdef _auth_password_message_sasl_continue(self, bytes server_response) + + cdef _write(self, buf) + cdef _writelines(self, list buffers) + + cdef _read_server_messages(self) + + cdef _push_result(self) + cdef _reset_result(self) + cdef _set_state(self, ProtocolState new_state) + + cdef _ensure_connected(self) + + cdef WriteBuffer _build_parse_message(self, str stmt_name, str query) + cdef WriteBuffer _build_bind_message(self, str portal_name, + str stmt_name, + WriteBuffer bind_data) + cdef WriteBuffer _build_empty_bind_data(self) + cdef WriteBuffer _build_execute_message(self, str portal_name, + int32_t limit) + + + cdef _connect(self) + cdef _prepare_and_describe(self, str stmt_name, str query) + cdef _send_parse_message(self, str stmt_name, str query) + cdef _send_bind_message(self, str portal_name, str stmt_name, + WriteBuffer bind_data, int32_t limit) + cdef _bind_execute(self, str portal_name, str stmt_name, + WriteBuffer bind_data, int32_t limit) + cdef bint _bind_execute_many(self, str portal_name, str stmt_name, + object bind_data) + cdef bint _bind_execute_many_more(self, bint first=*) + cdef _bind_execute_many_fail(self, object error, bint first=*) + cdef _bind(self, str portal_name, str stmt_name, + WriteBuffer bind_data) + cdef _execute(self, str portal_name, int32_t limit) + cdef _close(self, str name, bint is_portal) + cdef _simple_query(self, str query) + cdef _copy_out(self, str copy_stmt) + cdef _copy_in(self, str copy_stmt) + cdef _terminate(self) + + cdef _decode_row(self, const char* buf, ssize_t buf_len) + + cdef _on_result(self) + cdef _on_notification(self, pid, channel, payload) + cdef _on_notice(self, parsed) + cdef _set_server_parameter(self, name, val) + cdef _on_connection_lost(self, exc) diff --git a/env/Lib/site-packages/asyncpg/protocol/coreproto.pyx b/env/Lib/site-packages/asyncpg/protocol/coreproto.pyx new file mode 100644 index 0000000..64afe93 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/coreproto.pyx @@ -0,0 +1,1153 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import hashlib + + +include "scram.pyx" + + +cdef class CoreProtocol: + + def __init__(self, con_params): + # type of `con_params` is `_ConnectionParameters` + self.buffer = ReadBuffer() + self.user = con_params.user + self.password = con_params.password + self.auth_msg = None + self.con_params = con_params + self.con_status = CONNECTION_BAD + self.state = PROTOCOL_IDLE + self.xact_status = PQTRANS_IDLE + self.encoding = 'utf-8' + # type of `scram` is `SCRAMAuthentcation` + self.scram = None + + self._reset_result() + + cpdef is_in_transaction(self): + # PQTRANS_INTRANS = idle, within transaction block + # PQTRANS_INERROR = idle, within failed transaction + return self.xact_status in (PQTRANS_INTRANS, PQTRANS_INERROR) + + cdef _read_server_messages(self): + cdef: + char mtype + ProtocolState state + pgproto.take_message_method take_message = \ + self.buffer.take_message + pgproto.get_message_type_method get_message_type= \ + self.buffer.get_message_type + + while take_message(self.buffer) == 1: + mtype = get_message_type(self.buffer) + state = self.state + + try: + if mtype == b'S': + # ParameterStatus + self._parse_msg_parameter_status() + + elif mtype == b'A': + # NotificationResponse + self._parse_msg_notification() + + elif mtype == b'N': + # 'N' - NoticeResponse + self._on_notice(self._parse_msg_error_response(False)) + + elif state == PROTOCOL_AUTH: + self._process__auth(mtype) + + elif state == PROTOCOL_PREPARE: + self._process__prepare(mtype) + + elif state == PROTOCOL_BIND_EXECUTE: + self._process__bind_execute(mtype) + + elif state == PROTOCOL_BIND_EXECUTE_MANY: + self._process__bind_execute_many(mtype) + + elif state == PROTOCOL_EXECUTE: + self._process__bind_execute(mtype) + + elif state == PROTOCOL_BIND: + self._process__bind(mtype) + + elif state == PROTOCOL_CLOSE_STMT_PORTAL: + self._process__close_stmt_portal(mtype) + + elif state == PROTOCOL_SIMPLE_QUERY: + self._process__simple_query(mtype) + + elif state == PROTOCOL_COPY_OUT: + self._process__copy_out(mtype) + + elif (state == PROTOCOL_COPY_OUT_DATA or + state == PROTOCOL_COPY_OUT_DONE): + self._process__copy_out_data(mtype) + + elif state == PROTOCOL_COPY_IN: + self._process__copy_in(mtype) + + elif state == PROTOCOL_COPY_IN_DATA: + self._process__copy_in_data(mtype) + + elif state == PROTOCOL_CANCELLED: + # discard all messages until the sync message + if mtype == b'E': + self._parse_msg_error_response(True) + elif mtype == b'Z': + self._parse_msg_ready_for_query() + self._push_result() + else: + self.buffer.discard_message() + + elif state == PROTOCOL_ERROR_CONSUME: + # Error in protocol (on asyncpg side); + # discard all messages until sync message + + if mtype == b'Z': + # Sync point, self to push the result + if self.result_type != RESULT_FAILED: + self.result_type = RESULT_FAILED + self.result = apg_exc.InternalClientError( + 'unknown error in protocol implementation') + + self._parse_msg_ready_for_query() + self._push_result() + + else: + self.buffer.discard_message() + + elif state == PROTOCOL_TERMINATING: + # The connection is being terminated. + # discard all messages until connection + # termination. + self.buffer.discard_message() + + else: + raise apg_exc.InternalClientError( + f'cannot process message {chr(mtype)!r}: ' + f'protocol is in an unexpected state {state!r}.') + + except Exception as ex: + self.result_type = RESULT_FAILED + self.result = ex + + if mtype == b'Z': + self._push_result() + else: + self.state = PROTOCOL_ERROR_CONSUME + + finally: + self.buffer.finish_message() + + cdef _process__auth(self, char mtype): + if mtype == b'R': + # Authentication... + try: + self._parse_msg_authentication() + except Exception as ex: + # Exception in authentication parsing code + # is usually either malformed authentication data + # or missing support for cryptographic primitives + # in the hashlib module. + self.result_type = RESULT_FAILED + self.result = apg_exc.InternalClientError( + f"unexpected error while performing authentication: {ex}") + self.result.__cause__ = ex + self.con_status = CONNECTION_BAD + self._push_result() + else: + if self.result_type != RESULT_OK: + self.con_status = CONNECTION_BAD + self._push_result() + + elif self.auth_msg is not None: + # Server wants us to send auth data, so do that. + self._write(self.auth_msg) + self.auth_msg = None + + elif mtype == b'K': + # BackendKeyData + self._parse_msg_backend_key_data() + + elif mtype == b'E': + # ErrorResponse + self.con_status = CONNECTION_BAD + self._parse_msg_error_response(True) + self._push_result() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self.con_status = CONNECTION_OK + self._push_result() + + cdef _process__prepare(self, char mtype): + if mtype == b't': + # Parameters description + self.result_param_desc = self.buffer.consume_message() + + elif mtype == b'1': + # ParseComplete + self.buffer.discard_message() + + elif mtype == b'T': + # Row description + self.result_row_desc = self.buffer.consume_message() + self._push_result() + + elif mtype == b'E': + # ErrorResponse + self._parse_msg_error_response(True) + # we don't send a sync during the parse/describe sequence + # but send a FLUSH instead. If an error happens we need to + # send a SYNC explicitly in order to mark the end of the transaction. + # this effectively clears the error and we then wait until we get a + # ready for new query message + self._write(SYNC_MESSAGE) + self.state = PROTOCOL_ERROR_CONSUME + + elif mtype == b'n': + # NoData + self.buffer.discard_message() + self._push_result() + + cdef _process__bind_execute(self, char mtype): + if mtype == b'D': + # DataRow + self._parse_data_msgs() + + elif mtype == b's': + # PortalSuspended + self.buffer.discard_message() + + elif mtype == b'C': + # CommandComplete + self.result_execute_completed = True + self._parse_msg_command_complete() + + elif mtype == b'E': + # ErrorResponse + self._parse_msg_error_response(True) + + elif mtype == b'1': + # ParseComplete, in case `_bind_execute()` is reparsing + self.buffer.discard_message() + + elif mtype == b'2': + # BindComplete + self.buffer.discard_message() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + elif mtype == b'I': + # EmptyQueryResponse + self.buffer.discard_message() + + cdef _process__bind_execute_many(self, char mtype): + cdef WriteBuffer buf + + if mtype == b'D': + # DataRow + self._parse_data_msgs() + + elif mtype == b's': + # PortalSuspended + self.buffer.discard_message() + + elif mtype == b'C': + # CommandComplete + self._parse_msg_command_complete() + + elif mtype == b'E': + # ErrorResponse + self._parse_msg_error_response(True) + + elif mtype == b'1': + # ParseComplete, in case `_bind_execute_many()` is reparsing + self.buffer.discard_message() + + elif mtype == b'2': + # BindComplete + self.buffer.discard_message() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + elif mtype == b'I': + # EmptyQueryResponse + self.buffer.discard_message() + + elif mtype == b'1': + # ParseComplete + self.buffer.discard_message() + + cdef _process__bind(self, char mtype): + if mtype == b'E': + # ErrorResponse + self._parse_msg_error_response(True) + + elif mtype == b'2': + # BindComplete + self.buffer.discard_message() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + cdef _process__close_stmt_portal(self, char mtype): + if mtype == b'E': + # ErrorResponse + self._parse_msg_error_response(True) + + elif mtype == b'3': + # CloseComplete + self.buffer.discard_message() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + cdef _process__simple_query(self, char mtype): + if mtype in {b'D', b'I', b'T'}: + # 'D' - DataRow + # 'I' - EmptyQueryResponse + # 'T' - RowDescription + self.buffer.discard_message() + + elif mtype == b'E': + # ErrorResponse + self._parse_msg_error_response(True) + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + elif mtype == b'C': + # CommandComplete + self._parse_msg_command_complete() + + else: + # We don't really care about COPY IN etc + self.buffer.discard_message() + + cdef _process__copy_out(self, char mtype): + if mtype == b'E': + self._parse_msg_error_response(True) + + elif mtype == b'H': + # CopyOutResponse + self._set_state(PROTOCOL_COPY_OUT_DATA) + self.buffer.discard_message() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + cdef _process__copy_out_data(self, char mtype): + if mtype == b'E': + self._parse_msg_error_response(True) + + elif mtype == b'd': + # CopyData + self._parse_copy_data_msgs() + + elif mtype == b'c': + # CopyDone + self.buffer.discard_message() + self._set_state(PROTOCOL_COPY_OUT_DONE) + + elif mtype == b'C': + # CommandComplete + self._parse_msg_command_complete() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + cdef _process__copy_in(self, char mtype): + if mtype == b'E': + self._parse_msg_error_response(True) + + elif mtype == b'G': + # CopyInResponse + self._set_state(PROTOCOL_COPY_IN_DATA) + self.buffer.discard_message() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + cdef _process__copy_in_data(self, char mtype): + if mtype == b'E': + self._parse_msg_error_response(True) + + elif mtype == b'C': + # CommandComplete + self._parse_msg_command_complete() + + elif mtype == b'Z': + # ReadyForQuery + self._parse_msg_ready_for_query() + self._push_result() + + cdef _parse_msg_command_complete(self): + cdef: + const char* cbuf + ssize_t cbuf_len + + cbuf = self.buffer.try_consume_message(&cbuf_len) + if cbuf != NULL and cbuf_len > 0: + msg = cpython.PyBytes_FromStringAndSize(cbuf, cbuf_len - 1) + else: + msg = self.buffer.read_null_str() + self.result_status_msg = msg + + cdef _parse_copy_data_msgs(self): + cdef: + ReadBuffer buf = self.buffer + + self.result = buf.consume_messages(b'd') + + # By this point we have consumed all CopyData messages + # in the inbound buffer. If there are no messages left + # in the buffer, we need to push the accumulated data + # out to the caller in anticipation of the new CopyData + # batch. If there _are_ non-CopyData messages left, + # we must not push the result here and let the + # _process__copy_out_data subprotocol do the job. + if not buf.take_message(): + self._on_result() + self.result = None + else: + # If there is a message in the buffer, put it back to + # be processed by the next protocol iteration. + buf.put_message() + + cdef _write_copy_data_msg(self, object data): + cdef: + WriteBuffer buf + object mview + Py_buffer *pybuf + + mview = cpythonx.PyMemoryView_GetContiguous( + data, cpython.PyBUF_READ, b'C') + + try: + pybuf = cpythonx.PyMemoryView_GET_BUFFER(mview) + + buf = WriteBuffer.new_message(b'd') + buf.write_cstr(pybuf.buf, pybuf.len) + buf.end_message() + finally: + mview.release() + + self._write(buf) + + cdef _write_copy_done_msg(self): + cdef: + WriteBuffer buf + + buf = WriteBuffer.new_message(b'c') + buf.end_message() + self._write(buf) + + cdef _write_copy_fail_msg(self, str cause): + cdef: + WriteBuffer buf + + buf = WriteBuffer.new_message(b'f') + buf.write_str(cause or '', self.encoding) + buf.end_message() + self._write(buf) + + cdef _parse_data_msgs(self): + cdef: + ReadBuffer buf = self.buffer + list rows + + decode_row_method decoder = self._decode_row + pgproto.try_consume_message_method try_consume_message = \ + buf.try_consume_message + pgproto.take_message_type_method take_message_type = \ + buf.take_message_type + + const char* cbuf + ssize_t cbuf_len + object row + bytes mem + + if PG_DEBUG: + if buf.get_message_type() != b'D': + raise apg_exc.InternalClientError( + '_parse_data_msgs: first message is not "D"') + + if self._discard_data: + while take_message_type(buf, b'D'): + buf.discard_message() + return + + if PG_DEBUG: + if type(self.result) is not list: + raise apg_exc.InternalClientError( + '_parse_data_msgs: result is not a list, but {!r}'. + format(self.result)) + + rows = self.result + while take_message_type(buf, b'D'): + cbuf = try_consume_message(buf, &cbuf_len) + if cbuf != NULL: + row = decoder(self, cbuf, cbuf_len) + else: + mem = buf.consume_message() + row = decoder( + self, + cpython.PyBytes_AS_STRING(mem), + cpython.PyBytes_GET_SIZE(mem)) + + cpython.PyList_Append(rows, row) + + cdef _parse_msg_backend_key_data(self): + self.backend_pid = self.buffer.read_int32() + self.backend_secret = self.buffer.read_int32() + + cdef _parse_msg_parameter_status(self): + name = self.buffer.read_null_str() + name = name.decode(self.encoding) + + val = self.buffer.read_null_str() + val = val.decode(self.encoding) + + self._set_server_parameter(name, val) + + cdef _parse_msg_notification(self): + pid = self.buffer.read_int32() + channel = self.buffer.read_null_str().decode(self.encoding) + payload = self.buffer.read_null_str().decode(self.encoding) + self._on_notification(pid, channel, payload) + + cdef _parse_msg_authentication(self): + cdef: + int32_t status + bytes md5_salt + list sasl_auth_methods + list unsupported_sasl_auth_methods + + status = self.buffer.read_int32() + + if status == AUTH_SUCCESSFUL: + # AuthenticationOk + self.result_type = RESULT_OK + + elif status == AUTH_REQUIRED_PASSWORD: + # AuthenticationCleartextPassword + self.result_type = RESULT_OK + self.auth_msg = self._auth_password_message_cleartext() + + elif status == AUTH_REQUIRED_PASSWORDMD5: + # AuthenticationMD5Password + # Note: MD5 salt is passed as a four-byte sequence + md5_salt = self.buffer.read_bytes(4) + self.auth_msg = self._auth_password_message_md5(md5_salt) + + elif status == AUTH_REQUIRED_SASL: + # AuthenticationSASL + # This requires making additional requests to the server in order + # to follow the SCRAM protocol defined in RFC 5802. + # get the SASL authentication methods that the server is providing + sasl_auth_methods = [] + unsupported_sasl_auth_methods = [] + # determine if the advertised authentication methods are supported, + # and if so, add them to the list + auth_method = self.buffer.read_null_str() + while auth_method: + if auth_method in SCRAMAuthentication.AUTHENTICATION_METHODS: + sasl_auth_methods.append(auth_method) + else: + unsupported_sasl_auth_methods.append(auth_method) + auth_method = self.buffer.read_null_str() + + # if none of the advertised authentication methods are supported, + # raise an error + # otherwise, initialize the SASL authentication exchange + if not sasl_auth_methods: + unsupported_sasl_auth_methods = [m.decode("ascii") + for m in unsupported_sasl_auth_methods] + self.result_type = RESULT_FAILED + self.result = apg_exc.InterfaceError( + 'unsupported SASL Authentication methods requested by the ' + 'server: {!r}'.format( + ", ".join(unsupported_sasl_auth_methods))) + else: + self.auth_msg = self._auth_password_message_sasl_initial( + sasl_auth_methods) + + elif status == AUTH_SASL_CONTINUE: + # AUTH_SASL_CONTINUE + # this requeires sending the second part of the SASL exchange, where + # the client parses information back from the server and determines + # if this is valid. + # The client builds a challenge response to the server + server_response = self.buffer.consume_message() + self.auth_msg = self._auth_password_message_sasl_continue( + server_response) + + elif status == AUTH_SASL_FINAL: + # AUTH_SASL_FINAL + server_response = self.buffer.consume_message() + if not self.scram.verify_server_final_message(server_response): + self.result_type = RESULT_FAILED + self.result = apg_exc.InterfaceError( + 'could not verify server signature for ' + 'SCRAM authentciation: scram-sha-256', + ) + + elif status in (AUTH_REQUIRED_KERBEROS, AUTH_REQUIRED_SCMCRED, + AUTH_REQUIRED_GSS, AUTH_REQUIRED_GSS_CONTINUE, + AUTH_REQUIRED_SSPI): + self.result_type = RESULT_FAILED + self.result = apg_exc.InterfaceError( + 'unsupported authentication method requested by the ' + 'server: {!r}'.format(AUTH_METHOD_NAME[status])) + + else: + self.result_type = RESULT_FAILED + self.result = apg_exc.InterfaceError( + 'unsupported authentication method requested by the ' + 'server: {}'.format(status)) + + if status not in [AUTH_SASL_CONTINUE, AUTH_SASL_FINAL]: + self.buffer.discard_message() + + cdef _auth_password_message_cleartext(self): + cdef: + WriteBuffer msg + + msg = WriteBuffer.new_message(b'p') + msg.write_bytestring(self.password.encode(self.encoding)) + msg.end_message() + + return msg + + cdef _auth_password_message_md5(self, bytes salt): + cdef: + WriteBuffer msg + + msg = WriteBuffer.new_message(b'p') + + # 'md5' + md5(md5(password + username) + salt)) + userpass = (self.password or '') + (self.user or '') + md5_1 = hashlib.md5(userpass.encode(self.encoding)).hexdigest() + md5_2 = hashlib.md5(md5_1.encode('ascii') + salt).hexdigest() + + msg.write_bytestring(b'md5' + md5_2.encode('ascii')) + msg.end_message() + + return msg + + cdef _auth_password_message_sasl_initial(self, list sasl_auth_methods): + cdef: + WriteBuffer msg + + # use the first supported advertized mechanism + self.scram = SCRAMAuthentication(sasl_auth_methods[0]) + # this involves a call and response with the server + msg = WriteBuffer.new_message(b'p') + msg.write_bytes(self.scram.create_client_first_message(self.user or '')) + msg.end_message() + + return msg + + cdef _auth_password_message_sasl_continue(self, bytes server_response): + cdef: + WriteBuffer msg + + # determine if there is a valid server response + self.scram.parse_server_first_message(server_response) + # this involves a call and response with the server + msg = WriteBuffer.new_message(b'p') + client_final_message = self.scram.create_client_final_message( + self.password or '') + msg.write_bytes(client_final_message) + msg.end_message() + + return msg + + cdef _parse_msg_ready_for_query(self): + cdef char status = self.buffer.read_byte() + + if status == b'I': + self.xact_status = PQTRANS_IDLE + elif status == b'T': + self.xact_status = PQTRANS_INTRANS + elif status == b'E': + self.xact_status = PQTRANS_INERROR + else: + self.xact_status = PQTRANS_UNKNOWN + + cdef _parse_msg_error_response(self, is_error): + cdef: + char code + bytes message + dict parsed = {} + + while True: + code = self.buffer.read_byte() + if code == 0: + break + + message = self.buffer.read_null_str() + + parsed[chr(code)] = message.decode() + + if is_error: + self.result_type = RESULT_FAILED + self.result = parsed + else: + return parsed + + cdef _push_result(self): + try: + self._on_result() + finally: + self._set_state(PROTOCOL_IDLE) + self._reset_result() + + cdef _reset_result(self): + self.result_type = RESULT_OK + self.result = None + self.result_param_desc = None + self.result_row_desc = None + self.result_status_msg = None + self.result_execute_completed = False + self._discard_data = False + + # executemany support data + self._execute_iter = None + self._execute_portal_name = None + self._execute_stmt_name = None + + cdef _set_state(self, ProtocolState new_state): + if new_state == PROTOCOL_IDLE: + if self.state == PROTOCOL_FAILED: + raise apg_exc.InternalClientError( + 'cannot switch to "idle" state; ' + 'protocol is in the "failed" state') + elif self.state == PROTOCOL_IDLE: + pass + else: + self.state = new_state + + elif new_state == PROTOCOL_FAILED: + self.state = PROTOCOL_FAILED + + elif new_state == PROTOCOL_CANCELLED: + self.state = PROTOCOL_CANCELLED + + elif new_state == PROTOCOL_TERMINATING: + self.state = PROTOCOL_TERMINATING + + else: + if self.state == PROTOCOL_IDLE: + self.state = new_state + + elif (self.state == PROTOCOL_COPY_OUT and + new_state == PROTOCOL_COPY_OUT_DATA): + self.state = new_state + + elif (self.state == PROTOCOL_COPY_OUT_DATA and + new_state == PROTOCOL_COPY_OUT_DONE): + self.state = new_state + + elif (self.state == PROTOCOL_COPY_IN and + new_state == PROTOCOL_COPY_IN_DATA): + self.state = new_state + + elif self.state == PROTOCOL_FAILED: + raise apg_exc.InternalClientError( + 'cannot switch to state {}; ' + 'protocol is in the "failed" state'.format(new_state)) + else: + raise apg_exc.InternalClientError( + 'cannot switch to state {}; ' + 'another operation ({}) is in progress'.format( + new_state, self.state)) + + cdef _ensure_connected(self): + if self.con_status != CONNECTION_OK: + raise apg_exc.InternalClientError('not connected') + + cdef WriteBuffer _build_parse_message(self, str stmt_name, str query): + cdef WriteBuffer buf + + buf = WriteBuffer.new_message(b'P') + buf.write_str(stmt_name, self.encoding) + buf.write_str(query, self.encoding) + buf.write_int16(0) + + buf.end_message() + return buf + + cdef WriteBuffer _build_bind_message(self, str portal_name, + str stmt_name, + WriteBuffer bind_data): + cdef WriteBuffer buf + + buf = WriteBuffer.new_message(b'B') + buf.write_str(portal_name, self.encoding) + buf.write_str(stmt_name, self.encoding) + + # Arguments + buf.write_buffer(bind_data) + + buf.end_message() + return buf + + cdef WriteBuffer _build_empty_bind_data(self): + cdef WriteBuffer buf + buf = WriteBuffer.new() + buf.write_int16(0) # The number of parameter format codes + buf.write_int16(0) # The number of parameter values + buf.write_int16(0) # The number of result-column format codes + return buf + + cdef WriteBuffer _build_execute_message(self, str portal_name, + int32_t limit): + cdef WriteBuffer buf + + buf = WriteBuffer.new_message(b'E') + buf.write_str(portal_name, self.encoding) # name of the portal + buf.write_int32(limit) # number of rows to return; 0 - all + + buf.end_message() + return buf + + # API for subclasses + + cdef _connect(self): + cdef: + WriteBuffer buf + WriteBuffer outbuf + + if self.con_status != CONNECTION_BAD: + raise apg_exc.InternalClientError('already connected') + + self._set_state(PROTOCOL_AUTH) + self.con_status = CONNECTION_STARTED + + # Assemble a startup message + buf = WriteBuffer() + + # protocol version + buf.write_int16(3) + buf.write_int16(0) + + buf.write_bytestring(b'client_encoding') + buf.write_bytestring("'{}'".format(self.encoding).encode('ascii')) + + buf.write_str('user', self.encoding) + buf.write_str(self.con_params.user, self.encoding) + + buf.write_str('database', self.encoding) + buf.write_str(self.con_params.database, self.encoding) + + if self.con_params.server_settings is not None: + for k, v in self.con_params.server_settings.items(): + buf.write_str(k, self.encoding) + buf.write_str(v, self.encoding) + + buf.write_bytestring(b'') + + # Send the buffer + outbuf = WriteBuffer() + outbuf.write_int32(buf.len() + 4) + outbuf.write_buffer(buf) + self._write(outbuf) + + cdef _send_parse_message(self, str stmt_name, str query): + cdef: + WriteBuffer msg + + self._ensure_connected() + msg = self._build_parse_message(stmt_name, query) + self._write(msg) + + cdef _prepare_and_describe(self, str stmt_name, str query): + cdef: + WriteBuffer packet + WriteBuffer buf + + self._ensure_connected() + self._set_state(PROTOCOL_PREPARE) + + packet = self._build_parse_message(stmt_name, query) + + buf = WriteBuffer.new_message(b'D') + buf.write_byte(b'S') + buf.write_str(stmt_name, self.encoding) + buf.end_message() + packet.write_buffer(buf) + + packet.write_bytes(FLUSH_MESSAGE) + + self._write(packet) + + cdef _send_bind_message(self, str portal_name, str stmt_name, + WriteBuffer bind_data, int32_t limit): + + cdef: + WriteBuffer packet + WriteBuffer buf + + buf = self._build_bind_message(portal_name, stmt_name, bind_data) + packet = buf + + buf = self._build_execute_message(portal_name, limit) + packet.write_buffer(buf) + + packet.write_bytes(SYNC_MESSAGE) + + self._write(packet) + + cdef _bind_execute(self, str portal_name, str stmt_name, + WriteBuffer bind_data, int32_t limit): + + cdef WriteBuffer buf + + self._ensure_connected() + self._set_state(PROTOCOL_BIND_EXECUTE) + + self.result = [] + + self._send_bind_message(portal_name, stmt_name, bind_data, limit) + + cdef bint _bind_execute_many(self, str portal_name, str stmt_name, + object bind_data): + self._ensure_connected() + self._set_state(PROTOCOL_BIND_EXECUTE_MANY) + + self.result = None + self._discard_data = True + self._execute_iter = bind_data + self._execute_portal_name = portal_name + self._execute_stmt_name = stmt_name + return self._bind_execute_many_more(True) + + cdef bint _bind_execute_many_more(self, bint first=False): + cdef: + WriteBuffer packet + WriteBuffer buf + list buffers = [] + + # as we keep sending, the server may return an error early + if self.result_type == RESULT_FAILED: + self._write(SYNC_MESSAGE) + return False + + # collect up to four 32KB buffers to send + # https://github.com/MagicStack/asyncpg/pull/289#issuecomment-391215051 + while len(buffers) < _EXECUTE_MANY_BUF_NUM: + packet = WriteBuffer.new() + + # fill one 32KB buffer + while packet.len() < _EXECUTE_MANY_BUF_SIZE: + try: + # grab one item from the input + buf = next(self._execute_iter) + + # reached the end of the input + except StopIteration: + if first: + # if we never send anything, simply set the result + self._push_result() + else: + # otherwise, append SYNC and send the buffers + packet.write_bytes(SYNC_MESSAGE) + buffers.append(memoryview(packet)) + self._writelines(buffers) + return False + + # error in input, give up the buffers and cleanup + except Exception as ex: + self._bind_execute_many_fail(ex, first) + return False + + # all good, write to the buffer + first = False + packet.write_buffer( + self._build_bind_message( + self._execute_portal_name, + self._execute_stmt_name, + buf, + ) + ) + packet.write_buffer( + self._build_execute_message(self._execute_portal_name, 0, + ) + ) + + # collected one buffer + buffers.append(memoryview(packet)) + + # write to the wire, and signal the caller for more to send + self._writelines(buffers) + return True + + cdef _bind_execute_many_fail(self, object error, bint first=False): + cdef WriteBuffer buf + + self.result_type = RESULT_FAILED + self.result = error + if first: + self._push_result() + elif self.is_in_transaction(): + # we're in an explicit transaction, just SYNC + self._write(SYNC_MESSAGE) + else: + # In an implicit transaction, if `ignore_till_sync` is set, + # `ROLLBACK` will be ignored and `Sync` will restore the state; + # or the transaction will be rolled back with a warning saying + # that there was no transaction, but rollback is done anyway, + # so we could safely ignore this warning. + # GOTCHA: cannot use simple query message here, because it is + # ignored if `ignore_till_sync` is set. + buf = self._build_parse_message('', 'ROLLBACK') + buf.write_buffer(self._build_bind_message( + '', '', self._build_empty_bind_data())) + buf.write_buffer(self._build_execute_message('', 0)) + buf.write_bytes(SYNC_MESSAGE) + self._write(buf) + + cdef _execute(self, str portal_name, int32_t limit): + cdef WriteBuffer buf + + self._ensure_connected() + self._set_state(PROTOCOL_EXECUTE) + + self.result = [] + + buf = self._build_execute_message(portal_name, limit) + + buf.write_bytes(SYNC_MESSAGE) + + self._write(buf) + + cdef _bind(self, str portal_name, str stmt_name, + WriteBuffer bind_data): + + cdef WriteBuffer buf + + self._ensure_connected() + self._set_state(PROTOCOL_BIND) + + buf = self._build_bind_message(portal_name, stmt_name, bind_data) + + buf.write_bytes(SYNC_MESSAGE) + + self._write(buf) + + cdef _close(self, str name, bint is_portal): + cdef WriteBuffer buf + + self._ensure_connected() + self._set_state(PROTOCOL_CLOSE_STMT_PORTAL) + + buf = WriteBuffer.new_message(b'C') + + if is_portal: + buf.write_byte(b'P') + else: + buf.write_byte(b'S') + + buf.write_str(name, self.encoding) + buf.end_message() + + buf.write_bytes(SYNC_MESSAGE) + + self._write(buf) + + cdef _simple_query(self, str query): + cdef WriteBuffer buf + self._ensure_connected() + self._set_state(PROTOCOL_SIMPLE_QUERY) + buf = WriteBuffer.new_message(b'Q') + buf.write_str(query, self.encoding) + buf.end_message() + self._write(buf) + + cdef _copy_out(self, str copy_stmt): + cdef WriteBuffer buf + + self._ensure_connected() + self._set_state(PROTOCOL_COPY_OUT) + + # Send the COPY .. TO STDOUT using the SimpleQuery protocol. + buf = WriteBuffer.new_message(b'Q') + buf.write_str(copy_stmt, self.encoding) + buf.end_message() + self._write(buf) + + cdef _copy_in(self, str copy_stmt): + cdef WriteBuffer buf + + self._ensure_connected() + self._set_state(PROTOCOL_COPY_IN) + + buf = WriteBuffer.new_message(b'Q') + buf.write_str(copy_stmt, self.encoding) + buf.end_message() + self._write(buf) + + cdef _terminate(self): + cdef WriteBuffer buf + self._ensure_connected() + self._set_state(PROTOCOL_TERMINATING) + buf = WriteBuffer.new_message(b'X') + buf.end_message() + self._write(buf) + + cdef _write(self, buf): + raise NotImplementedError + + cdef _writelines(self, list buffers): + raise NotImplementedError + + cdef _decode_row(self, const char* buf, ssize_t buf_len): + pass + + cdef _set_server_parameter(self, name, val): + pass + + cdef _on_result(self): + pass + + cdef _on_notice(self, parsed): + pass + + cdef _on_notification(self, pid, channel, payload): + pass + + cdef _on_connection_lost(self, exc): + pass + + +cdef bytes SYNC_MESSAGE = bytes(WriteBuffer.new_message(b'S').end_message()) +cdef bytes FLUSH_MESSAGE = bytes(WriteBuffer.new_message(b'H').end_message()) diff --git a/env/Lib/site-packages/asyncpg/protocol/cpythonx.pxd b/env/Lib/site-packages/asyncpg/protocol/cpythonx.pxd new file mode 100644 index 0000000..1c72988 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/cpythonx.pxd @@ -0,0 +1,19 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef extern from "Python.h": + int PyByteArray_Check(object) + + int PyMemoryView_Check(object) + Py_buffer *PyMemoryView_GET_BUFFER(object) + object PyMemoryView_GetContiguous(object, int buffertype, char order) + + Py_UCS4* PyUnicode_AsUCS4Copy(object) except NULL + object PyUnicode_FromKindAndData( + int kind, const void *buffer, Py_ssize_t size) + + int PyUnicode_4BYTE_KIND diff --git a/env/Lib/site-packages/asyncpg/protocol/encodings.pyx b/env/Lib/site-packages/asyncpg/protocol/encodings.pyx new file mode 100644 index 0000000..dcd692b --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/encodings.pyx @@ -0,0 +1,63 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +'''Map PostgreSQL encoding names to Python encoding names + +https://www.postgresql.org/docs/current/static/multibyte.html#CHARSET-TABLE +''' + +cdef dict ENCODINGS_MAP = { + 'abc': 'cp1258', + 'alt': 'cp866', + 'euc_cn': 'euccn', + 'euc_jp': 'eucjp', + 'euc_kr': 'euckr', + 'koi8r': 'koi8_r', + 'koi8u': 'koi8_u', + 'shift_jis_2004': 'euc_jis_2004', + 'sjis': 'shift_jis', + 'sql_ascii': 'ascii', + 'vscii': 'cp1258', + 'tcvn': 'cp1258', + 'tcvn5712': 'cp1258', + 'unicode': 'utf_8', + 'win': 'cp1521', + 'win1250': 'cp1250', + 'win1251': 'cp1251', + 'win1252': 'cp1252', + 'win1253': 'cp1253', + 'win1254': 'cp1254', + 'win1255': 'cp1255', + 'win1256': 'cp1256', + 'win1257': 'cp1257', + 'win1258': 'cp1258', + 'win866': 'cp866', + 'win874': 'cp874', + 'win932': 'cp932', + 'win936': 'cp936', + 'win949': 'cp949', + 'win950': 'cp950', + 'windows1250': 'cp1250', + 'windows1251': 'cp1251', + 'windows1252': 'cp1252', + 'windows1253': 'cp1253', + 'windows1254': 'cp1254', + 'windows1255': 'cp1255', + 'windows1256': 'cp1256', + 'windows1257': 'cp1257', + 'windows1258': 'cp1258', + 'windows866': 'cp866', + 'windows874': 'cp874', + 'windows932': 'cp932', + 'windows936': 'cp936', + 'windows949': 'cp949', + 'windows950': 'cp950', +} + + +cdef get_python_encoding(pg_encoding): + return ENCODINGS_MAP.get(pg_encoding.lower(), pg_encoding.lower()) diff --git a/env/Lib/site-packages/asyncpg/protocol/pgtypes.pxi b/env/Lib/site-packages/asyncpg/protocol/pgtypes.pxi new file mode 100644 index 0000000..e9bb782 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/pgtypes.pxi @@ -0,0 +1,266 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +# GENERATED FROM pg_catalog.pg_type +# DO NOT MODIFY, use tools/generate_type_map.py to update + +DEF INVALIDOID = 0 +DEF MAXBUILTINOID = 9999 +DEF MAXSUPPORTEDOID = 5080 + +DEF BOOLOID = 16 +DEF BYTEAOID = 17 +DEF CHAROID = 18 +DEF NAMEOID = 19 +DEF INT8OID = 20 +DEF INT2OID = 21 +DEF INT4OID = 23 +DEF REGPROCOID = 24 +DEF TEXTOID = 25 +DEF OIDOID = 26 +DEF TIDOID = 27 +DEF XIDOID = 28 +DEF CIDOID = 29 +DEF PG_DDL_COMMANDOID = 32 +DEF JSONOID = 114 +DEF XMLOID = 142 +DEF PG_NODE_TREEOID = 194 +DEF SMGROID = 210 +DEF TABLE_AM_HANDLEROID = 269 +DEF INDEX_AM_HANDLEROID = 325 +DEF POINTOID = 600 +DEF LSEGOID = 601 +DEF PATHOID = 602 +DEF BOXOID = 603 +DEF POLYGONOID = 604 +DEF LINEOID = 628 +DEF CIDROID = 650 +DEF FLOAT4OID = 700 +DEF FLOAT8OID = 701 +DEF ABSTIMEOID = 702 +DEF RELTIMEOID = 703 +DEF TINTERVALOID = 704 +DEF UNKNOWNOID = 705 +DEF CIRCLEOID = 718 +DEF MACADDR8OID = 774 +DEF MONEYOID = 790 +DEF MACADDROID = 829 +DEF INETOID = 869 +DEF _TEXTOID = 1009 +DEF _OIDOID = 1028 +DEF ACLITEMOID = 1033 +DEF BPCHAROID = 1042 +DEF VARCHAROID = 1043 +DEF DATEOID = 1082 +DEF TIMEOID = 1083 +DEF TIMESTAMPOID = 1114 +DEF TIMESTAMPTZOID = 1184 +DEF INTERVALOID = 1186 +DEF TIMETZOID = 1266 +DEF BITOID = 1560 +DEF VARBITOID = 1562 +DEF NUMERICOID = 1700 +DEF REFCURSOROID = 1790 +DEF REGPROCEDUREOID = 2202 +DEF REGOPEROID = 2203 +DEF REGOPERATOROID = 2204 +DEF REGCLASSOID = 2205 +DEF REGTYPEOID = 2206 +DEF RECORDOID = 2249 +DEF CSTRINGOID = 2275 +DEF ANYOID = 2276 +DEF ANYARRAYOID = 2277 +DEF VOIDOID = 2278 +DEF TRIGGEROID = 2279 +DEF LANGUAGE_HANDLEROID = 2280 +DEF INTERNALOID = 2281 +DEF OPAQUEOID = 2282 +DEF ANYELEMENTOID = 2283 +DEF ANYNONARRAYOID = 2776 +DEF UUIDOID = 2950 +DEF TXID_SNAPSHOTOID = 2970 +DEF FDW_HANDLEROID = 3115 +DEF PG_LSNOID = 3220 +DEF TSM_HANDLEROID = 3310 +DEF PG_NDISTINCTOID = 3361 +DEF PG_DEPENDENCIESOID = 3402 +DEF ANYENUMOID = 3500 +DEF TSVECTOROID = 3614 +DEF TSQUERYOID = 3615 +DEF GTSVECTOROID = 3642 +DEF REGCONFIGOID = 3734 +DEF REGDICTIONARYOID = 3769 +DEF JSONBOID = 3802 +DEF ANYRANGEOID = 3831 +DEF EVENT_TRIGGEROID = 3838 +DEF JSONPATHOID = 4072 +DEF REGNAMESPACEOID = 4089 +DEF REGROLEOID = 4096 +DEF REGCOLLATIONOID = 4191 +DEF ANYMULTIRANGEOID = 4537 +DEF ANYCOMPATIBLEMULTIRANGEOID = 4538 +DEF PG_BRIN_BLOOM_SUMMARYOID = 4600 +DEF PG_BRIN_MINMAX_MULTI_SUMMARYOID = 4601 +DEF PG_MCV_LISTOID = 5017 +DEF PG_SNAPSHOTOID = 5038 +DEF XID8OID = 5069 +DEF ANYCOMPATIBLEOID = 5077 +DEF ANYCOMPATIBLEARRAYOID = 5078 +DEF ANYCOMPATIBLENONARRAYOID = 5079 +DEF ANYCOMPATIBLERANGEOID = 5080 + +cdef ARRAY_TYPES = (_TEXTOID, _OIDOID,) + +BUILTIN_TYPE_OID_MAP = { + ABSTIMEOID: 'abstime', + ACLITEMOID: 'aclitem', + ANYARRAYOID: 'anyarray', + ANYCOMPATIBLEARRAYOID: 'anycompatiblearray', + ANYCOMPATIBLEMULTIRANGEOID: 'anycompatiblemultirange', + ANYCOMPATIBLENONARRAYOID: 'anycompatiblenonarray', + ANYCOMPATIBLEOID: 'anycompatible', + ANYCOMPATIBLERANGEOID: 'anycompatiblerange', + ANYELEMENTOID: 'anyelement', + ANYENUMOID: 'anyenum', + ANYMULTIRANGEOID: 'anymultirange', + ANYNONARRAYOID: 'anynonarray', + ANYOID: 'any', + ANYRANGEOID: 'anyrange', + BITOID: 'bit', + BOOLOID: 'bool', + BOXOID: 'box', + BPCHAROID: 'bpchar', + BYTEAOID: 'bytea', + CHAROID: 'char', + CIDOID: 'cid', + CIDROID: 'cidr', + CIRCLEOID: 'circle', + CSTRINGOID: 'cstring', + DATEOID: 'date', + EVENT_TRIGGEROID: 'event_trigger', + FDW_HANDLEROID: 'fdw_handler', + FLOAT4OID: 'float4', + FLOAT8OID: 'float8', + GTSVECTOROID: 'gtsvector', + INDEX_AM_HANDLEROID: 'index_am_handler', + INETOID: 'inet', + INT2OID: 'int2', + INT4OID: 'int4', + INT8OID: 'int8', + INTERNALOID: 'internal', + INTERVALOID: 'interval', + JSONBOID: 'jsonb', + JSONOID: 'json', + JSONPATHOID: 'jsonpath', + LANGUAGE_HANDLEROID: 'language_handler', + LINEOID: 'line', + LSEGOID: 'lseg', + MACADDR8OID: 'macaddr8', + MACADDROID: 'macaddr', + MONEYOID: 'money', + NAMEOID: 'name', + NUMERICOID: 'numeric', + OIDOID: 'oid', + OPAQUEOID: 'opaque', + PATHOID: 'path', + PG_BRIN_BLOOM_SUMMARYOID: 'pg_brin_bloom_summary', + PG_BRIN_MINMAX_MULTI_SUMMARYOID: 'pg_brin_minmax_multi_summary', + PG_DDL_COMMANDOID: 'pg_ddl_command', + PG_DEPENDENCIESOID: 'pg_dependencies', + PG_LSNOID: 'pg_lsn', + PG_MCV_LISTOID: 'pg_mcv_list', + PG_NDISTINCTOID: 'pg_ndistinct', + PG_NODE_TREEOID: 'pg_node_tree', + PG_SNAPSHOTOID: 'pg_snapshot', + POINTOID: 'point', + POLYGONOID: 'polygon', + RECORDOID: 'record', + REFCURSOROID: 'refcursor', + REGCLASSOID: 'regclass', + REGCOLLATIONOID: 'regcollation', + REGCONFIGOID: 'regconfig', + REGDICTIONARYOID: 'regdictionary', + REGNAMESPACEOID: 'regnamespace', + REGOPERATOROID: 'regoperator', + REGOPEROID: 'regoper', + REGPROCEDUREOID: 'regprocedure', + REGPROCOID: 'regproc', + REGROLEOID: 'regrole', + REGTYPEOID: 'regtype', + RELTIMEOID: 'reltime', + SMGROID: 'smgr', + TABLE_AM_HANDLEROID: 'table_am_handler', + TEXTOID: 'text', + TIDOID: 'tid', + TIMEOID: 'time', + TIMESTAMPOID: 'timestamp', + TIMESTAMPTZOID: 'timestamptz', + TIMETZOID: 'timetz', + TINTERVALOID: 'tinterval', + TRIGGEROID: 'trigger', + TSM_HANDLEROID: 'tsm_handler', + TSQUERYOID: 'tsquery', + TSVECTOROID: 'tsvector', + TXID_SNAPSHOTOID: 'txid_snapshot', + UNKNOWNOID: 'unknown', + UUIDOID: 'uuid', + VARBITOID: 'varbit', + VARCHAROID: 'varchar', + VOIDOID: 'void', + XID8OID: 'xid8', + XIDOID: 'xid', + XMLOID: 'xml', + _OIDOID: 'oid[]', + _TEXTOID: 'text[]' +} + +BUILTIN_TYPE_NAME_MAP = {v: k for k, v in BUILTIN_TYPE_OID_MAP.items()} + +BUILTIN_TYPE_NAME_MAP['smallint'] = \ + BUILTIN_TYPE_NAME_MAP['int2'] + +BUILTIN_TYPE_NAME_MAP['int'] = \ + BUILTIN_TYPE_NAME_MAP['int4'] + +BUILTIN_TYPE_NAME_MAP['integer'] = \ + BUILTIN_TYPE_NAME_MAP['int4'] + +BUILTIN_TYPE_NAME_MAP['bigint'] = \ + BUILTIN_TYPE_NAME_MAP['int8'] + +BUILTIN_TYPE_NAME_MAP['decimal'] = \ + BUILTIN_TYPE_NAME_MAP['numeric'] + +BUILTIN_TYPE_NAME_MAP['real'] = \ + BUILTIN_TYPE_NAME_MAP['float4'] + +BUILTIN_TYPE_NAME_MAP['double precision'] = \ + BUILTIN_TYPE_NAME_MAP['float8'] + +BUILTIN_TYPE_NAME_MAP['timestamp with timezone'] = \ + BUILTIN_TYPE_NAME_MAP['timestamptz'] + +BUILTIN_TYPE_NAME_MAP['timestamp without timezone'] = \ + BUILTIN_TYPE_NAME_MAP['timestamp'] + +BUILTIN_TYPE_NAME_MAP['time with timezone'] = \ + BUILTIN_TYPE_NAME_MAP['timetz'] + +BUILTIN_TYPE_NAME_MAP['time without timezone'] = \ + BUILTIN_TYPE_NAME_MAP['time'] + +BUILTIN_TYPE_NAME_MAP['char'] = \ + BUILTIN_TYPE_NAME_MAP['bpchar'] + +BUILTIN_TYPE_NAME_MAP['character'] = \ + BUILTIN_TYPE_NAME_MAP['bpchar'] + +BUILTIN_TYPE_NAME_MAP['character varying'] = \ + BUILTIN_TYPE_NAME_MAP['varchar'] + +BUILTIN_TYPE_NAME_MAP['bit varying'] = \ + BUILTIN_TYPE_NAME_MAP['varbit'] diff --git a/env/Lib/site-packages/asyncpg/protocol/prepared_stmt.pxd b/env/Lib/site-packages/asyncpg/protocol/prepared_stmt.pxd new file mode 100644 index 0000000..369db73 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/prepared_stmt.pxd @@ -0,0 +1,39 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef class PreparedStatementState: + cdef: + readonly str name + readonly str query + readonly bint closed + readonly bint prepared + readonly int refs + readonly type record_class + readonly bint ignore_custom_codec + + + list row_desc + list parameters_desc + + ConnectionSettings settings + + int16_t args_num + bint have_text_args + tuple args_codecs + + int16_t cols_num + object cols_desc + bint have_text_cols + tuple rows_codecs + + cdef _encode_bind_msg(self, args, int seqno = ?) + cpdef _init_codecs(self) + cdef _ensure_rows_decoder(self) + cdef _ensure_args_encoder(self) + cdef _set_row_desc(self, object desc) + cdef _set_args_desc(self, object desc) + cdef _decode_row(self, const char* cbuf, ssize_t buf_len) diff --git a/env/Lib/site-packages/asyncpg/protocol/prepared_stmt.pyx b/env/Lib/site-packages/asyncpg/protocol/prepared_stmt.pyx new file mode 100644 index 0000000..7335825 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/prepared_stmt.pyx @@ -0,0 +1,395 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from asyncpg import exceptions + + +@cython.final +cdef class PreparedStatementState: + + def __cinit__( + self, + str name, + str query, + BaseProtocol protocol, + type record_class, + bint ignore_custom_codec + ): + self.name = name + self.query = query + self.settings = protocol.settings + self.row_desc = self.parameters_desc = None + self.args_codecs = self.rows_codecs = None + self.args_num = self.cols_num = 0 + self.cols_desc = None + self.closed = False + self.prepared = True + self.refs = 0 + self.record_class = record_class + self.ignore_custom_codec = ignore_custom_codec + + def _get_parameters(self): + cdef Codec codec + + result = [] + for oid in self.parameters_desc: + codec = self.settings.get_data_codec(oid) + if codec is None: + raise exceptions.InternalClientError( + 'missing codec information for OID {}'.format(oid)) + result.append(apg_types.Type( + oid, codec.name, codec.kind, codec.schema)) + + return tuple(result) + + def _get_attributes(self): + cdef Codec codec + + if not self.row_desc: + return () + + result = [] + for d in self.row_desc: + name = d[0] + oid = d[3] + + codec = self.settings.get_data_codec(oid) + if codec is None: + raise exceptions.InternalClientError( + 'missing codec information for OID {}'.format(oid)) + + name = name.decode(self.settings._encoding) + + result.append( + apg_types.Attribute(name, + apg_types.Type(oid, codec.name, codec.kind, codec.schema))) + + return tuple(result) + + def _init_types(self): + cdef: + Codec codec + set missing = set() + + if self.parameters_desc: + for p_oid in self.parameters_desc: + codec = self.settings.get_data_codec(p_oid) + if codec is None or not codec.has_encoder(): + missing.add(p_oid) + + if self.row_desc: + for rdesc in self.row_desc: + codec = self.settings.get_data_codec((rdesc[3])) + if codec is None or not codec.has_decoder(): + missing.add(rdesc[3]) + + return missing + + cpdef _init_codecs(self): + self._ensure_args_encoder() + self._ensure_rows_decoder() + + def attach(self): + self.refs += 1 + + def detach(self): + self.refs -= 1 + + def mark_closed(self): + self.closed = True + + def mark_unprepared(self): + if self.name: + raise exceptions.InternalClientError( + "named prepared statements cannot be marked unprepared") + self.prepared = False + + cdef _encode_bind_msg(self, args, int seqno = -1): + cdef: + int idx + WriteBuffer writer + Codec codec + + if not cpython.PySequence_Check(args): + if seqno >= 0: + raise exceptions.DataError( + f'invalid input in executemany() argument sequence ' + f'element #{seqno}: expected a sequence, got ' + f'{type(args).__name__}' + ) + else: + # Non executemany() callers do not pass user input directly, + # so bad input is a bug. + raise exceptions.InternalClientError( + f'Bind: expected a sequence, got {type(args).__name__}') + + if len(args) > 32767: + raise exceptions.InterfaceError( + 'the number of query arguments cannot exceed 32767') + + writer = WriteBuffer.new() + + num_args_passed = len(args) + if self.args_num != num_args_passed: + hint = 'Check the query against the passed list of arguments.' + + if self.args_num == 0: + # If the server was expecting zero arguments, it is likely + # that the user tried to parametrize a statement that does + # not support parameters. + hint += (r' Note that parameters are supported only in' + r' SELECT, INSERT, UPDATE, DELETE, and VALUES' + r' statements, and will *not* work in statements ' + r' like CREATE VIEW or DECLARE CURSOR.') + + raise exceptions.InterfaceError( + 'the server expects {x} argument{s} for this query, ' + '{y} {w} passed'.format( + x=self.args_num, s='s' if self.args_num != 1 else '', + y=num_args_passed, + w='was' if num_args_passed == 1 else 'were'), + hint=hint) + + if self.have_text_args: + writer.write_int16(self.args_num) + for idx in range(self.args_num): + codec = (self.args_codecs[idx]) + writer.write_int16(codec.format) + else: + # All arguments are in binary format + writer.write_int32(0x00010001) + + writer.write_int16(self.args_num) + + for idx in range(self.args_num): + arg = args[idx] + if arg is None: + writer.write_int32(-1) + else: + codec = (self.args_codecs[idx]) + try: + codec.encode(self.settings, writer, arg) + except (AssertionError, exceptions.InternalClientError): + # These are internal errors and should raise as-is. + raise + except exceptions.InterfaceError as e: + # This is already a descriptive error, but annotate + # with argument name for clarity. + pos = f'${idx + 1}' + if seqno >= 0: + pos = ( + f'{pos} in element #{seqno} of' + f' executemany() sequence' + ) + raise e.with_msg( + f'query argument {pos}: {e.args[0]}' + ) from None + except Exception as e: + # Everything else is assumed to be an encoding error + # due to invalid input. + pos = f'${idx + 1}' + if seqno >= 0: + pos = ( + f'{pos} in element #{seqno} of' + f' executemany() sequence' + ) + value_repr = repr(arg) + if len(value_repr) > 40: + value_repr = value_repr[:40] + '...' + + raise exceptions.DataError( + f'invalid input for query argument' + f' {pos}: {value_repr} ({e})' + ) from e + + if self.have_text_cols: + writer.write_int16(self.cols_num) + for idx in range(self.cols_num): + codec = (self.rows_codecs[idx]) + writer.write_int16(codec.format) + else: + # All columns are in binary format + writer.write_int32(0x00010001) + + return writer + + cdef _ensure_rows_decoder(self): + cdef: + list cols_names + object cols_mapping + tuple row + uint32_t oid + Codec codec + list codecs + + if self.cols_desc is not None: + return + + if self.cols_num == 0: + self.cols_desc = record.ApgRecordDesc_New({}, ()) + return + + cols_mapping = collections.OrderedDict() + cols_names = [] + codecs = [] + for i from 0 <= i < self.cols_num: + row = self.row_desc[i] + col_name = row[0].decode(self.settings._encoding) + cols_mapping[col_name] = i + cols_names.append(col_name) + oid = row[3] + codec = self.settings.get_data_codec( + oid, ignore_custom_codec=self.ignore_custom_codec) + if codec is None or not codec.has_decoder(): + raise exceptions.InternalClientError( + 'no decoder for OID {}'.format(oid)) + if not codec.is_binary(): + self.have_text_cols = True + + codecs.append(codec) + + self.cols_desc = record.ApgRecordDesc_New( + cols_mapping, tuple(cols_names)) + + self.rows_codecs = tuple(codecs) + + cdef _ensure_args_encoder(self): + cdef: + uint32_t p_oid + Codec codec + list codecs = [] + + if self.args_num == 0 or self.args_codecs is not None: + return + + for i from 0 <= i < self.args_num: + p_oid = self.parameters_desc[i] + codec = self.settings.get_data_codec( + p_oid, ignore_custom_codec=self.ignore_custom_codec) + if codec is None or not codec.has_encoder(): + raise exceptions.InternalClientError( + 'no encoder for OID {}'.format(p_oid)) + if codec.type not in {}: + self.have_text_args = True + + codecs.append(codec) + + self.args_codecs = tuple(codecs) + + cdef _set_row_desc(self, object desc): + self.row_desc = _decode_row_desc(desc) + self.cols_num = (len(self.row_desc)) + + cdef _set_args_desc(self, object desc): + self.parameters_desc = _decode_parameters_desc(desc) + self.args_num = (len(self.parameters_desc)) + + cdef _decode_row(self, const char* cbuf, ssize_t buf_len): + cdef: + Codec codec + int16_t fnum + int32_t flen + object dec_row + tuple rows_codecs = self.rows_codecs + ConnectionSettings settings = self.settings + int32_t i + FRBuffer rbuf + ssize_t bl + + frb_init(&rbuf, cbuf, buf_len) + + fnum = hton.unpack_int16(frb_read(&rbuf, 2)) + + if fnum != self.cols_num: + raise exceptions.ProtocolError( + 'the number of columns in the result row ({}) is ' + 'different from what was described ({})'.format( + fnum, self.cols_num)) + + dec_row = record.ApgRecord_New(self.record_class, self.cols_desc, fnum) + for i in range(fnum): + flen = hton.unpack_int32(frb_read(&rbuf, 4)) + + if flen == -1: + val = None + else: + # Clamp buffer size to that of the reported field length + # to make sure that codecs can rely on read_all() working + # properly. + bl = frb_get_len(&rbuf) + if flen > bl: + frb_check(&rbuf, flen) + frb_set_len(&rbuf, flen) + codec = cpython.PyTuple_GET_ITEM(rows_codecs, i) + val = codec.decode(settings, &rbuf) + if frb_get_len(&rbuf) != 0: + raise BufferError( + 'unexpected trailing {} bytes in buffer'.format( + frb_get_len(&rbuf))) + frb_set_len(&rbuf, bl - flen) + + cpython.Py_INCREF(val) + record.ApgRecord_SET_ITEM(dec_row, i, val) + + if frb_get_len(&rbuf) != 0: + raise BufferError('unexpected trailing {} bytes in buffer'.format( + frb_get_len(&rbuf))) + + return dec_row + + +cdef _decode_parameters_desc(object desc): + cdef: + ReadBuffer reader + int16_t nparams + uint32_t p_oid + list result = [] + + reader = ReadBuffer.new_message_parser(desc) + nparams = reader.read_int16() + + for i from 0 <= i < nparams: + p_oid = reader.read_int32() + result.append(p_oid) + + return result + + +cdef _decode_row_desc(object desc): + cdef: + ReadBuffer reader + + int16_t nfields + + bytes f_name + uint32_t f_table_oid + int16_t f_column_num + uint32_t f_dt_oid + int16_t f_dt_size + int32_t f_dt_mod + int16_t f_format + + list result + + reader = ReadBuffer.new_message_parser(desc) + nfields = reader.read_int16() + result = [] + + for i from 0 <= i < nfields: + f_name = reader.read_null_str() + f_table_oid = reader.read_int32() + f_column_num = reader.read_int16() + f_dt_oid = reader.read_int32() + f_dt_size = reader.read_int16() + f_dt_mod = reader.read_int32() + f_format = reader.read_int16() + + result.append( + (f_name, f_table_oid, f_column_num, f_dt_oid, + f_dt_size, f_dt_mod, f_format)) + + return result diff --git a/env/Lib/site-packages/asyncpg/protocol/protocol.cp311-win_amd64.pyd b/env/Lib/site-packages/asyncpg/protocol/protocol.cp311-win_amd64.pyd new file mode 100644 index 0000000..49393c4 Binary files /dev/null and b/env/Lib/site-packages/asyncpg/protocol/protocol.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/asyncpg/protocol/protocol.pxd b/env/Lib/site-packages/asyncpg/protocol/protocol.pxd new file mode 100644 index 0000000..a9ac8d5 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/protocol.pxd @@ -0,0 +1,78 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from libc.stdint cimport int16_t, int32_t, uint16_t, \ + uint32_t, int64_t, uint64_t + +from asyncpg.pgproto.debug cimport PG_DEBUG + +from asyncpg.pgproto.pgproto cimport ( + WriteBuffer, + ReadBuffer, + FRBuffer, +) + +from asyncpg.pgproto cimport pgproto + +include "consts.pxi" +include "pgtypes.pxi" + +include "codecs/base.pxd" +include "settings.pxd" +include "coreproto.pxd" +include "prepared_stmt.pxd" + + +cdef class BaseProtocol(CoreProtocol): + + cdef: + object loop + object address + ConnectionSettings settings + object cancel_sent_waiter + object cancel_waiter + object waiter + bint return_extra + object create_future + object timeout_handle + object conref + type record_class + bint is_reading + + str last_query + + bint writing_paused + bint closing + + readonly uint64_t queries_count + + bint _is_ssl + + PreparedStatementState statement + + cdef get_connection(self) + + cdef _get_timeout_impl(self, timeout) + cdef _check_state(self) + cdef _new_waiter(self, timeout) + cdef _coreproto_error(self) + + cdef _on_result__connect(self, object waiter) + cdef _on_result__prepare(self, object waiter) + cdef _on_result__bind_and_exec(self, object waiter) + cdef _on_result__close_stmt_or_portal(self, object waiter) + cdef _on_result__simple_query(self, object waiter) + cdef _on_result__bind(self, object waiter) + cdef _on_result__copy_out(self, object waiter) + cdef _on_result__copy_in(self, object waiter) + + cdef _handle_waiter_on_connection_lost(self, cause) + + cdef _dispatch_result(self) + + cdef inline resume_reading(self) + cdef inline pause_reading(self) diff --git a/env/Lib/site-packages/asyncpg/protocol/protocol.pyx b/env/Lib/site-packages/asyncpg/protocol/protocol.pyx new file mode 100644 index 0000000..b43b0e9 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/protocol.pyx @@ -0,0 +1,1064 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +# cython: language_level=3 + +cimport cython +cimport cpython + +import asyncio +import builtins +import codecs +import collections.abc +import socket +import time +import weakref + +from asyncpg.pgproto.pgproto cimport ( + WriteBuffer, + ReadBuffer, + + FRBuffer, + frb_init, + frb_read, + frb_read_all, + frb_slice_from, + frb_check, + frb_set_len, + frb_get_len, +) + +from asyncpg.pgproto cimport pgproto +from asyncpg.protocol cimport cpythonx +from asyncpg.protocol cimport record + +from libc.stdint cimport int8_t, uint8_t, int16_t, uint16_t, \ + int32_t, uint32_t, int64_t, uint64_t, \ + INT32_MAX, UINT32_MAX + +from asyncpg.exceptions import _base as apg_exc_base +from asyncpg import compat +from asyncpg import types as apg_types +from asyncpg import exceptions as apg_exc + +from asyncpg.pgproto cimport hton + + +include "consts.pxi" +include "pgtypes.pxi" + +include "encodings.pyx" +include "settings.pyx" + +include "codecs/base.pyx" +include "codecs/textutils.pyx" + +# register codecs provided by pgproto +include "codecs/pgproto.pyx" + +# nonscalar +include "codecs/array.pyx" +include "codecs/range.pyx" +include "codecs/record.pyx" + +include "coreproto.pyx" +include "prepared_stmt.pyx" + + +NO_TIMEOUT = object() + + +cdef class BaseProtocol(CoreProtocol): + def __init__(self, addr, connected_fut, con_params, record_class: type, loop): + # type of `con_params` is `_ConnectionParameters` + CoreProtocol.__init__(self, con_params) + + self.loop = loop + self.transport = None + self.waiter = connected_fut + self.cancel_waiter = None + self.cancel_sent_waiter = None + + self.address = addr + self.settings = ConnectionSettings((self.address, con_params.database)) + self.record_class = record_class + + self.statement = None + self.return_extra = False + + self.last_query = None + + self.closing = False + self.is_reading = True + self.writing_allowed = asyncio.Event() + self.writing_allowed.set() + + self.timeout_handle = None + + self.queries_count = 0 + + self._is_ssl = False + + try: + self.create_future = loop.create_future + except AttributeError: + self.create_future = self._create_future_fallback + + def set_connection(self, connection): + self.conref = weakref.ref(connection) + + cdef get_connection(self): + if self.conref is not None: + return self.conref() + else: + return None + + def get_server_pid(self): + return self.backend_pid + + def get_settings(self): + return self.settings + + def get_record_class(self): + return self.record_class + + cdef inline resume_reading(self): + if not self.is_reading: + self.is_reading = True + self.transport.resume_reading() + + cdef inline pause_reading(self): + if self.is_reading: + self.is_reading = False + self.transport.pause_reading() + + @cython.iterable_coroutine + async def prepare(self, stmt_name, query, timeout, + *, + PreparedStatementState state=None, + ignore_custom_codec=False, + record_class): + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + timeout = self._get_timeout_impl(timeout) + + waiter = self._new_waiter(timeout) + try: + self._prepare_and_describe(stmt_name, query) # network op + self.last_query = query + if state is None: + state = PreparedStatementState( + stmt_name, query, self, record_class, ignore_custom_codec) + self.statement = state + except Exception as ex: + waiter.set_exception(ex) + self._coreproto_error() + finally: + return await waiter + + @cython.iterable_coroutine + async def bind_execute( + self, + state: PreparedStatementState, + args, + portal_name: str, + limit: int, + return_extra: bool, + timeout, + ): + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + timeout = self._get_timeout_impl(timeout) + args_buf = state._encode_bind_msg(args) + + waiter = self._new_waiter(timeout) + try: + if not state.prepared: + self._send_parse_message(state.name, state.query) + + self._bind_execute( + portal_name, + state.name, + args_buf, + limit) # network op + + self.last_query = state.query + self.statement = state + self.return_extra = return_extra + self.queries_count += 1 + except Exception as ex: + waiter.set_exception(ex) + self._coreproto_error() + finally: + return await waiter + + @cython.iterable_coroutine + async def bind_execute_many( + self, + state: PreparedStatementState, + args, + portal_name: str, + timeout, + ): + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + timeout = self._get_timeout_impl(timeout) + timer = Timer(timeout) + + # Make sure the argument sequence is encoded lazily with + # this generator expression to keep the memory pressure under + # control. + data_gen = (state._encode_bind_msg(b, i) for i, b in enumerate(args)) + arg_bufs = iter(data_gen) + + waiter = self._new_waiter(timeout) + try: + if not state.prepared: + self._send_parse_message(state.name, state.query) + + more = self._bind_execute_many( + portal_name, + state.name, + arg_bufs) # network op + + self.last_query = state.query + self.statement = state + self.return_extra = False + self.queries_count += 1 + + while more: + with timer: + await compat.wait_for( + self.writing_allowed.wait(), + timeout=timer.get_remaining_budget()) + # On Windows the above event somehow won't allow context + # switch, so forcing one with sleep(0) here + await asyncio.sleep(0) + if not timer.has_budget_greater_than(0): + raise asyncio.TimeoutError + more = self._bind_execute_many_more() # network op + + except asyncio.TimeoutError as e: + self._bind_execute_many_fail(e) # network op + + except Exception as ex: + waiter.set_exception(ex) + self._coreproto_error() + finally: + return await waiter + + @cython.iterable_coroutine + async def bind(self, PreparedStatementState state, args, + str portal_name, timeout): + + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + timeout = self._get_timeout_impl(timeout) + args_buf = state._encode_bind_msg(args) + + waiter = self._new_waiter(timeout) + try: + self._bind( + portal_name, + state.name, + args_buf) # network op + + self.last_query = state.query + self.statement = state + except Exception as ex: + waiter.set_exception(ex) + self._coreproto_error() + finally: + return await waiter + + @cython.iterable_coroutine + async def execute(self, PreparedStatementState state, + str portal_name, int limit, return_extra, + timeout): + + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + timeout = self._get_timeout_impl(timeout) + + waiter = self._new_waiter(timeout) + try: + self._execute( + portal_name, + limit) # network op + + self.last_query = state.query + self.statement = state + self.return_extra = return_extra + self.queries_count += 1 + except Exception as ex: + waiter.set_exception(ex) + self._coreproto_error() + finally: + return await waiter + + @cython.iterable_coroutine + async def close_portal(self, str portal_name, timeout): + + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + timeout = self._get_timeout_impl(timeout) + + waiter = self._new_waiter(timeout) + try: + self._close( + portal_name, + True) # network op + except Exception as ex: + waiter.set_exception(ex) + self._coreproto_error() + finally: + return await waiter + + @cython.iterable_coroutine + async def query(self, query, timeout): + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + # query() needs to call _get_timeout instead of _get_timeout_impl + # for consistent validation, as it is called differently from + # prepare/bind/execute methods. + timeout = self._get_timeout(timeout) + + waiter = self._new_waiter(timeout) + try: + self._simple_query(query) # network op + self.last_query = query + self.queries_count += 1 + except Exception as ex: + waiter.set_exception(ex) + self._coreproto_error() + finally: + return await waiter + + @cython.iterable_coroutine + async def copy_out(self, copy_stmt, sink, timeout): + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + + timeout = self._get_timeout_impl(timeout) + timer = Timer(timeout) + + # The copy operation is guarded by a single timeout + # on the top level. + waiter = self._new_waiter(timer.get_remaining_budget()) + + self._copy_out(copy_stmt) + + try: + while True: + self.resume_reading() + + with timer: + buffer, done, status_msg = await waiter + + # buffer will be empty if CopyDone was received apart from + # the last CopyData message. + if buffer: + try: + with timer: + await compat.wait_for( + sink(buffer), + timeout=timer.get_remaining_budget()) + except (Exception, asyncio.CancelledError) as ex: + # Abort the COPY operation on any error in + # output sink. + self._request_cancel() + # Make asyncio shut up about unretrieved + # QueryCanceledError + waiter.add_done_callback(lambda f: f.exception()) + raise + + # done will be True upon receipt of CopyDone. + if done: + break + + waiter = self._new_waiter(timer.get_remaining_budget()) + + finally: + self.resume_reading() + + return status_msg + + @cython.iterable_coroutine + async def copy_in(self, copy_stmt, reader, data, + records, PreparedStatementState record_stmt, timeout): + cdef: + WriteBuffer wbuf + ssize_t num_cols + Codec codec + + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + + timeout = self._get_timeout_impl(timeout) + timer = Timer(timeout) + + waiter = self._new_waiter(timer.get_remaining_budget()) + + # Initiate COPY IN. + self._copy_in(copy_stmt) + + try: + if record_stmt is not None: + # copy_in_records in binary mode + wbuf = WriteBuffer.new() + # Signature + wbuf.write_bytes(_COPY_SIGNATURE) + # Flags field + wbuf.write_int32(0) + # No header extension + wbuf.write_int32(0) + + record_stmt._ensure_rows_decoder() + codecs = record_stmt.rows_codecs + num_cols = len(codecs) + settings = self.settings + + for codec in codecs: + if (not codec.has_encoder() or + codec.format != PG_FORMAT_BINARY): + raise apg_exc.InternalClientError( + 'no binary format encoder for ' + 'type {} (OID {})'.format(codec.name, codec.oid)) + + if isinstance(records, collections.abc.AsyncIterable): + async for row in records: + # Tuple header + wbuf.write_int16(num_cols) + # Tuple data + for i in range(num_cols): + item = row[i] + if item is None: + wbuf.write_int32(-1) + else: + codec = cpython.PyTuple_GET_ITEM( + codecs, i) + codec.encode(settings, wbuf, item) + + if wbuf.len() >= _COPY_BUFFER_SIZE: + with timer: + await self.writing_allowed.wait() + self._write_copy_data_msg(wbuf) + wbuf = WriteBuffer.new() + else: + for row in records: + # Tuple header + wbuf.write_int16(num_cols) + # Tuple data + for i in range(num_cols): + item = row[i] + if item is None: + wbuf.write_int32(-1) + else: + codec = cpython.PyTuple_GET_ITEM( + codecs, i) + codec.encode(settings, wbuf, item) + + if wbuf.len() >= _COPY_BUFFER_SIZE: + with timer: + await self.writing_allowed.wait() + self._write_copy_data_msg(wbuf) + wbuf = WriteBuffer.new() + + # End of binary copy. + wbuf.write_int16(-1) + self._write_copy_data_msg(wbuf) + + elif reader is not None: + try: + aiter = reader.__aiter__ + except AttributeError: + raise TypeError('reader is not an asynchronous iterable') + else: + iterator = aiter() + + try: + while True: + # We rely on protocol flow control to moderate the + # rate of data messages. + with timer: + await self.writing_allowed.wait() + with timer: + chunk = await compat.wait_for( + iterator.__anext__(), + timeout=timer.get_remaining_budget()) + self._write_copy_data_msg(chunk) + except builtins.StopAsyncIteration: + pass + else: + # Buffer passed in directly. + await self.writing_allowed.wait() + self._write_copy_data_msg(data) + + except asyncio.TimeoutError: + self._write_copy_fail_msg('TimeoutError') + self._on_timeout(self.waiter) + try: + await waiter + except TimeoutError: + raise + else: + raise apg_exc.InternalClientError('TimoutError was not raised') + + except (Exception, asyncio.CancelledError) as e: + self._write_copy_fail_msg(str(e)) + self._request_cancel() + # Make asyncio shut up about unretrieved QueryCanceledError + waiter.add_done_callback(lambda f: f.exception()) + raise + + self._write_copy_done_msg() + + status_msg = await waiter + + return status_msg + + @cython.iterable_coroutine + async def close_statement(self, PreparedStatementState state, timeout): + if self.cancel_waiter is not None: + await self.cancel_waiter + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + self._check_state() + + if state.refs != 0: + raise apg_exc.InternalClientError( + 'cannot close prepared statement; refs == {} != 0'.format( + state.refs)) + + timeout = self._get_timeout_impl(timeout) + waiter = self._new_waiter(timeout) + try: + self._close(state.name, False) # network op + state.closed = True + except Exception as ex: + waiter.set_exception(ex) + self._coreproto_error() + finally: + return await waiter + + def is_closed(self): + return self.closing + + def is_connected(self): + return not self.closing and self.con_status == CONNECTION_OK + + def abort(self): + if self.closing: + return + self.closing = True + self._handle_waiter_on_connection_lost(None) + self._terminate() + self.transport.abort() + self.transport = None + + @cython.iterable_coroutine + async def close(self, timeout): + if self.closing: + return + + self.closing = True + + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + + if self.cancel_waiter is not None: + await self.cancel_waiter + + if self.waiter is not None: + # If there is a query running, cancel it + self._request_cancel() + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + if self.cancel_waiter is not None: + await self.cancel_waiter + + assert self.waiter is None + + timeout = self._get_timeout_impl(timeout) + + # Ask the server to terminate the connection and wait for it + # to drop. + self.waiter = self._new_waiter(timeout) + self._terminate() + try: + await self.waiter + except ConnectionResetError: + # There appears to be a difference in behaviour of asyncio + # in Windows, where, instead of calling protocol.connection_lost() + # a ConnectionResetError will be thrown into the task. + pass + finally: + self.waiter = None + self.transport.abort() + + def _request_cancel(self): + self.cancel_waiter = self.create_future() + self.cancel_sent_waiter = self.create_future() + + con = self.get_connection() + if con is not None: + # if 'con' is None it means that the connection object has been + # garbage collected and that the transport will soon be aborted. + con._cancel_current_command(self.cancel_sent_waiter) + else: + self.loop.call_exception_handler({ + 'message': 'asyncpg.Protocol has no reference to its ' + 'Connection object and yet a cancellation ' + 'was requested. Please report this at ' + 'github.com/magicstack/asyncpg.' + }) + self.abort() + + if self.state == PROTOCOL_PREPARE: + # we need to send a SYNC to server if we cancel during the PREPARE phase + # because the PREPARE sequence does not send a SYNC itself. + # we cannot send this extra SYNC if we are not in PREPARE phase, + # because then we would issue two SYNCs and we would get two ReadyForQuery + # replies, which our current state machine implementation cannot handle + self._write(SYNC_MESSAGE) + self._set_state(PROTOCOL_CANCELLED) + + def _on_timeout(self, fut): + if self.waiter is not fut or fut.done() or \ + self.cancel_waiter is not None or \ + self.timeout_handle is None: + return + self._request_cancel() + self.waiter.set_exception(asyncio.TimeoutError()) + + def _on_waiter_completed(self, fut): + if self.timeout_handle: + self.timeout_handle.cancel() + self.timeout_handle = None + if fut is not self.waiter or self.cancel_waiter is not None: + return + if fut.cancelled(): + self._request_cancel() + + def _create_future_fallback(self): + return asyncio.Future(loop=self.loop) + + cdef _handle_waiter_on_connection_lost(self, cause): + if self.waiter is not None and not self.waiter.done(): + exc = apg_exc.ConnectionDoesNotExistError( + 'connection was closed in the middle of ' + 'operation') + if cause is not None: + exc.__cause__ = cause + self.waiter.set_exception(exc) + self.waiter = None + + cdef _set_server_parameter(self, name, val): + self.settings.add_setting(name, val) + + def _get_timeout(self, timeout): + if timeout is not None: + try: + if type(timeout) is bool: + raise ValueError + timeout = float(timeout) + except ValueError: + raise ValueError( + 'invalid timeout value: expected non-negative float ' + '(got {!r})'.format(timeout)) from None + + return self._get_timeout_impl(timeout) + + cdef inline _get_timeout_impl(self, timeout): + if timeout is None: + timeout = self.get_connection()._config.command_timeout + elif timeout is NO_TIMEOUT: + timeout = None + else: + timeout = float(timeout) + + if timeout is not None and timeout <= 0: + raise asyncio.TimeoutError() + return timeout + + cdef _check_state(self): + if self.cancel_waiter is not None: + raise apg_exc.InterfaceError( + 'cannot perform operation: another operation is cancelling') + if self.closing: + raise apg_exc.InterfaceError( + 'cannot perform operation: connection is closed') + if self.waiter is not None or self.timeout_handle is not None: + raise apg_exc.InterfaceError( + 'cannot perform operation: another operation is in progress') + + def _is_cancelling(self): + return ( + self.cancel_waiter is not None or + self.cancel_sent_waiter is not None + ) + + @cython.iterable_coroutine + async def _wait_for_cancellation(self): + if self.cancel_sent_waiter is not None: + await self.cancel_sent_waiter + self.cancel_sent_waiter = None + if self.cancel_waiter is not None: + await self.cancel_waiter + + cdef _coreproto_error(self): + try: + if self.waiter is not None: + if not self.waiter.done(): + raise apg_exc.InternalClientError( + 'waiter is not done while handling critical ' + 'protocol error') + self.waiter = None + finally: + self.abort() + + cdef _new_waiter(self, timeout): + if self.waiter is not None: + raise apg_exc.InterfaceError( + 'cannot perform operation: another operation is in progress') + self.waiter = self.create_future() + if timeout is not None: + self.timeout_handle = self.loop.call_later( + timeout, self._on_timeout, self.waiter) + self.waiter.add_done_callback(self._on_waiter_completed) + return self.waiter + + cdef _on_result__connect(self, object waiter): + waiter.set_result(True) + + cdef _on_result__prepare(self, object waiter): + if PG_DEBUG: + if self.statement is None: + raise apg_exc.InternalClientError( + '_on_result__prepare: statement is None') + + if self.result_param_desc is not None: + self.statement._set_args_desc(self.result_param_desc) + if self.result_row_desc is not None: + self.statement._set_row_desc(self.result_row_desc) + waiter.set_result(self.statement) + + cdef _on_result__bind_and_exec(self, object waiter): + if self.return_extra: + waiter.set_result(( + self.result, + self.result_status_msg, + self.result_execute_completed)) + else: + waiter.set_result(self.result) + + cdef _on_result__bind(self, object waiter): + waiter.set_result(self.result) + + cdef _on_result__close_stmt_or_portal(self, object waiter): + waiter.set_result(self.result) + + cdef _on_result__simple_query(self, object waiter): + waiter.set_result(self.result_status_msg.decode(self.encoding)) + + cdef _on_result__copy_out(self, object waiter): + cdef bint copy_done = self.state == PROTOCOL_COPY_OUT_DONE + if copy_done: + status_msg = self.result_status_msg.decode(self.encoding) + else: + status_msg = None + + # We need to put some backpressure on Postgres + # here in case the sink is slow to process the output. + self.pause_reading() + + waiter.set_result((self.result, copy_done, status_msg)) + + cdef _on_result__copy_in(self, object waiter): + status_msg = self.result_status_msg.decode(self.encoding) + waiter.set_result(status_msg) + + cdef _decode_row(self, const char* buf, ssize_t buf_len): + if PG_DEBUG: + if self.statement is None: + raise apg_exc.InternalClientError( + '_decode_row: statement is None') + + return self.statement._decode_row(buf, buf_len) + + cdef _dispatch_result(self): + waiter = self.waiter + self.waiter = None + + if PG_DEBUG: + if waiter is None: + raise apg_exc.InternalClientError('_on_result: waiter is None') + + if waiter.cancelled(): + return + + if waiter.done(): + raise apg_exc.InternalClientError('_on_result: waiter is done') + + if self.result_type == RESULT_FAILED: + if isinstance(self.result, dict): + exc = apg_exc_base.PostgresError.new( + self.result, query=self.last_query) + else: + exc = self.result + waiter.set_exception(exc) + return + + try: + if self.state == PROTOCOL_AUTH: + self._on_result__connect(waiter) + + elif self.state == PROTOCOL_PREPARE: + self._on_result__prepare(waiter) + + elif self.state == PROTOCOL_BIND_EXECUTE: + self._on_result__bind_and_exec(waiter) + + elif self.state == PROTOCOL_BIND_EXECUTE_MANY: + self._on_result__bind_and_exec(waiter) + + elif self.state == PROTOCOL_EXECUTE: + self._on_result__bind_and_exec(waiter) + + elif self.state == PROTOCOL_BIND: + self._on_result__bind(waiter) + + elif self.state == PROTOCOL_CLOSE_STMT_PORTAL: + self._on_result__close_stmt_or_portal(waiter) + + elif self.state == PROTOCOL_SIMPLE_QUERY: + self._on_result__simple_query(waiter) + + elif (self.state == PROTOCOL_COPY_OUT_DATA or + self.state == PROTOCOL_COPY_OUT_DONE): + self._on_result__copy_out(waiter) + + elif self.state == PROTOCOL_COPY_IN_DATA: + self._on_result__copy_in(waiter) + + elif self.state == PROTOCOL_TERMINATING: + # We are waiting for the connection to drop, so + # ignore any stray results at this point. + pass + + else: + raise apg_exc.InternalClientError( + 'got result for unknown protocol state {}'. + format(self.state)) + + except Exception as exc: + waiter.set_exception(exc) + + cdef _on_result(self): + if self.timeout_handle is not None: + self.timeout_handle.cancel() + self.timeout_handle = None + + if self.cancel_waiter is not None: + # We have received the result of a cancelled command. + if not self.cancel_waiter.done(): + # The cancellation future might have been cancelled + # by the cancellation of the entire task running the query. + self.cancel_waiter.set_result(None) + self.cancel_waiter = None + if self.waiter is not None and self.waiter.done(): + self.waiter = None + if self.waiter is None: + return + + try: + self._dispatch_result() + finally: + self.statement = None + self.last_query = None + self.return_extra = False + + cdef _on_notice(self, parsed): + con = self.get_connection() + if con is not None: + con._process_log_message(parsed, self.last_query) + + cdef _on_notification(self, pid, channel, payload): + con = self.get_connection() + if con is not None: + con._process_notification(pid, channel, payload) + + cdef _on_connection_lost(self, exc): + if self.closing: + # The connection was lost because + # Protocol.close() was called + if self.waiter is not None and not self.waiter.done(): + if exc is None: + self.waiter.set_result(None) + else: + self.waiter.set_exception(exc) + self.waiter = None + else: + # The connection was lost because it was + # terminated or due to another error; + # Throw an error in any awaiting waiter. + self.closing = True + # Cleanup the connection resources, including, possibly, + # releasing the pool holder. + con = self.get_connection() + if con is not None: + con._cleanup() + self._handle_waiter_on_connection_lost(exc) + + cdef _write(self, buf): + self.transport.write(memoryview(buf)) + + cdef _writelines(self, list buffers): + self.transport.writelines(buffers) + + # asyncio callbacks: + + def data_received(self, data): + self.buffer.feed_data(data) + self._read_server_messages() + + def connection_made(self, transport): + self.transport = transport + + sock = transport.get_extra_info('socket') + if (sock is not None and + (not hasattr(socket, 'AF_UNIX') + or sock.family != socket.AF_UNIX)): + sock.setsockopt(socket.IPPROTO_TCP, + socket.TCP_NODELAY, 1) + + try: + self._connect() + except Exception as ex: + transport.abort() + self.con_status = CONNECTION_BAD + self._set_state(PROTOCOL_FAILED) + self._on_error(ex) + + def connection_lost(self, exc): + self.con_status = CONNECTION_BAD + self._set_state(PROTOCOL_FAILED) + self._on_connection_lost(exc) + + def pause_writing(self): + self.writing_allowed.clear() + + def resume_writing(self): + self.writing_allowed.set() + + @property + def is_ssl(self): + return self._is_ssl + + @is_ssl.setter + def is_ssl(self, value): + self._is_ssl = value + + +class Timer: + def __init__(self, budget): + self._budget = budget + self._started = 0 + + def __enter__(self): + if self._budget is not None: + self._started = time.monotonic() + + def __exit__(self, et, e, tb): + if self._budget is not None: + self._budget -= time.monotonic() - self._started + + def get_remaining_budget(self): + return self._budget + + def has_budget_greater_than(self, amount): + if self._budget is None: + # Unlimited budget. + return True + else: + return self._budget > amount + + +class Protocol(BaseProtocol, asyncio.Protocol): + pass + + +def _create_record(object mapping, tuple elems): + # Exposed only for testing purposes. + + cdef: + object rec + int32_t i + + if mapping is None: + desc = record.ApgRecordDesc_New({}, ()) + else: + desc = record.ApgRecordDesc_New( + mapping, tuple(mapping) if mapping else ()) + + rec = record.ApgRecord_New(Record, desc, len(elems)) + for i in range(len(elems)): + elem = elems[i] + cpython.Py_INCREF(elem) + record.ApgRecord_SET_ITEM(rec, i, elem) + return rec + + +Record = record.ApgRecord_InitTypes() diff --git a/env/Lib/site-packages/asyncpg/protocol/record/__init__.pxd b/env/Lib/site-packages/asyncpg/protocol/record/__init__.pxd new file mode 100644 index 0000000..43ac5e3 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/record/__init__.pxd @@ -0,0 +1,19 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cimport cpython + + +cdef extern from "record/recordobj.h": + + cpython.PyTypeObject *ApgRecord_InitTypes() except NULL + + int ApgRecord_CheckExact(object) + object ApgRecord_New(type, object, int) + void ApgRecord_SET_ITEM(object, int, object) + + object ApgRecordDesc_New(object, object) diff --git a/env/Lib/site-packages/asyncpg/protocol/scram.pxd b/env/Lib/site-packages/asyncpg/protocol/scram.pxd new file mode 100644 index 0000000..5421429 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/scram.pxd @@ -0,0 +1,31 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef class SCRAMAuthentication: + cdef: + readonly bytes authentication_method + readonly bytes authorization_message + readonly bytes client_channel_binding + readonly bytes client_first_message_bare + readonly bytes client_nonce + readonly bytes client_proof + readonly bytes password_salt + readonly int password_iterations + readonly bytes server_first_message + # server_key is an instance of hmac.HAMC + readonly object server_key + readonly bytes server_nonce + + cdef create_client_first_message(self, str username) + cdef create_client_final_message(self, str password) + cdef parse_server_first_message(self, bytes server_response) + cdef verify_server_final_message(self, bytes server_final_message) + cdef _bytes_xor(self, bytes a, bytes b) + cdef _generate_client_nonce(self, int num_bytes) + cdef _generate_client_proof(self, str password) + cdef _generate_salted_password(self, str password, bytes salt, int iterations) + cdef _normalize_password(self, str original_password) diff --git a/env/Lib/site-packages/asyncpg/protocol/scram.pyx b/env/Lib/site-packages/asyncpg/protocol/scram.pyx new file mode 100644 index 0000000..9b485ae --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/scram.pyx @@ -0,0 +1,341 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import base64 +import hashlib +import hmac +import re +import secrets +import stringprep +import unicodedata + + +@cython.final +cdef class SCRAMAuthentication: + """Contains the protocol for generating and a SCRAM hashed password. + + Since PostgreSQL 10, the option to hash passwords using the SCRAM-SHA-256 + method was added. This module follows the defined protocol, which can be + referenced from here: + + https://www.postgresql.org/docs/current/sasl-authentication.html#SASL-SCRAM-SHA-256 + + libpq references the following RFCs that it uses for implementation: + + * RFC 5802 + * RFC 5803 + * RFC 7677 + + The protocol works as such: + + - A client connets to the server. The server requests the client to begin + SASL authentication using SCRAM and presents a client with the methods it + supports. At present, those are SCRAM-SHA-256, and, on servers that are + built with OpenSSL and + are PG11+, SCRAM-SHA-256-PLUS (which supports channel binding, more on that + below) + + - The client sends a "first message" to the server, where it chooses which + method to authenticate with, and sends, along with the method, an indication + of channel binding (we disable for now), a nonce, and the username. + (Technically, PostgreSQL ignores the username as it already has it from the + initical connection, but we add it for completeness) + + - The server responds with a "first message" in which it extends the nonce, + as well as a password salt and the number of iterations to hash the password + with. The client validates that the new nonce contains the first part of the + client's original nonce + + - The client generates a salted password, but does not sent this up to the + server. Instead, the client follows the SCRAM algorithm (RFC5802) to + generate a proof. This proof is sent aspart of a client "final message" to + the server for it to validate. + + - The server validates the proof. If it is valid, the server sends a + verification code for the client to verify that the server came to the same + proof the client did. PostgreSQL immediately sends an AuthenticationOK + response right after a valid negotiation. If the password the client + provided was invalid, then authentication fails. + + (The beauty of this is that the salted password is never transmitted over + the wire!) + + PostgreSQL 11 added support for the channel binding (i.e. + SCRAM-SHA-256-PLUS) but to do some ongoing discussion, there is a conscious + decision by several driver authors to not support it as of yet. As such, the + channel binding parameter is hard-coded to "n" for now, but can be updated + to support other channel binding methos in the future + """ + AUTHENTICATION_METHODS = [b"SCRAM-SHA-256"] + DEFAULT_CLIENT_NONCE_BYTES = 24 + DIGEST = hashlib.sha256 + REQUIREMENTS_CLIENT_FINAL_MESSAGE = ['client_channel_binding', + 'server_nonce'] + REQUIREMENTS_CLIENT_PROOF = ['password_iterations', 'password_salt', + 'server_first_message', 'server_nonce'] + SASLPREP_PROHIBITED = ( + stringprep.in_table_a1, # PostgreSQL treats this as prohibited + stringprep.in_table_c12, + stringprep.in_table_c21_c22, + stringprep.in_table_c3, + stringprep.in_table_c4, + stringprep.in_table_c5, + stringprep.in_table_c6, + stringprep.in_table_c7, + stringprep.in_table_c8, + stringprep.in_table_c9, + ) + + def __cinit__(self, bytes authentication_method): + self.authentication_method = authentication_method + self.authorization_message = None + # channel binding is turned off for the time being + self.client_channel_binding = b"n,," + self.client_first_message_bare = None + self.client_nonce = None + self.client_proof = None + self.password_salt = None + # self.password_iterations = None + self.server_first_message = None + self.server_key = None + self.server_nonce = None + + cdef create_client_first_message(self, str username): + """Create the initial client message for SCRAM authentication""" + cdef: + bytes msg + bytes client_first_message + + self.client_nonce = \ + self._generate_client_nonce(self.DEFAULT_CLIENT_NONCE_BYTES) + # set the client first message bare here, as it's used in a later step + self.client_first_message_bare = b"n=" + username.encode("utf-8") + \ + b",r=" + self.client_nonce + # put together the full message here + msg = bytes() + msg += self.authentication_method + b"\0" + client_first_message = self.client_channel_binding + \ + self.client_first_message_bare + msg += (len(client_first_message)).to_bytes(4, byteorder='big') + \ + client_first_message + return msg + + cdef create_client_final_message(self, str password): + """Create the final client message as part of SCRAM authentication""" + cdef: + bytes msg + + if any([getattr(self, val) is None for val in + self.REQUIREMENTS_CLIENT_FINAL_MESSAGE]): + raise Exception( + "you need values from server to generate a client proof") + + # normalize the password using the SASLprep algorithm in RFC 4013 + password = self._normalize_password(password) + + # generate the client proof + self.client_proof = self._generate_client_proof(password=password) + msg = bytes() + msg += b"c=" + base64.b64encode(self.client_channel_binding) + \ + b",r=" + self.server_nonce + \ + b",p=" + base64.b64encode(self.client_proof) + return msg + + cdef parse_server_first_message(self, bytes server_response): + """Parse the response from the first message from the server""" + self.server_first_message = server_response + try: + self.server_nonce = re.search(b'r=([^,]+),', + self.server_first_message).group(1) + except IndexError: + raise Exception("could not get nonce") + if not self.server_nonce.startswith(self.client_nonce): + raise Exception("invalid nonce") + try: + self.password_salt = re.search(b',s=([^,]+),', + self.server_first_message).group(1) + except IndexError: + raise Exception("could not get salt") + try: + self.password_iterations = int(re.search(b',i=(\d+),?', + self.server_first_message).group(1)) + except (IndexError, TypeError, ValueError): + raise Exception("could not get iterations") + + cdef verify_server_final_message(self, bytes server_final_message): + """Verify the final message from the server""" + cdef: + bytes server_signature + + try: + server_signature = re.search(b'v=([^,]+)', + server_final_message).group(1) + except IndexError: + raise Exception("could not get server signature") + + verify_server_signature = hmac.new(self.server_key.digest(), + self.authorization_message, self.DIGEST) + # validate the server signature against the verifier + return server_signature == base64.b64encode( + verify_server_signature.digest()) + + cdef _bytes_xor(self, bytes a, bytes b): + """XOR two bytestrings together""" + return bytes(a_i ^ b_i for a_i, b_i in zip(a, b)) + + cdef _generate_client_nonce(self, int num_bytes): + cdef: + bytes token + + token = secrets.token_bytes(num_bytes) + + return base64.b64encode(token) + + cdef _generate_client_proof(self, str password): + """need to ensure a server response exists, i.e. """ + cdef: + bytes salted_password + + if any([getattr(self, val) is None for val in + self.REQUIREMENTS_CLIENT_PROOF]): + raise Exception( + "you need values from server to generate a client proof") + # generate a salt password + salted_password = self._generate_salted_password(password, + self.password_salt, self.password_iterations) + # client key is derived from the salted password + client_key = hmac.new(salted_password, b"Client Key", self.DIGEST) + # this allows us to compute the stored key that is residing on the server + stored_key = self.DIGEST(client_key.digest()) + # as well as compute the server key + self.server_key = hmac.new(salted_password, b"Server Key", self.DIGEST) + # build the authorization message that will be used in the + # client signature + # the "c=" portion is for the channel binding, but this is not + # presently implemented + self.authorization_message = self.client_first_message_bare + b"," + \ + self.server_first_message + b",c=" + \ + base64.b64encode(self.client_channel_binding) + \ + b",r=" + self.server_nonce + # sign! + client_signature = hmac.new(stored_key.digest(), + self.authorization_message, self.DIGEST) + # and the proof + return self._bytes_xor(client_key.digest(), client_signature.digest()) + + cdef _generate_salted_password(self, str password, bytes salt, int iterations): + """This follows the "Hi" algorithm specified in RFC5802""" + cdef: + bytes p + bytes s + bytes u + + # convert the password to a binary string - UTF8 is safe for SASL + # (though there are SASLPrep rules) + p = password.encode("utf8") + # the salt needs to be base64 decoded -- full binary must be used + s = base64.b64decode(salt) + # the initial signature is the salt with a terminator of a 32-bit string + # ending in 1 + ui = hmac.new(p, s + b'\x00\x00\x00\x01', self.DIGEST) + # grab the initial digest + u = ui.digest() + # for X number of iterations, recompute the HMAC signature against the + # password and the latest iteration of the hash, and XOR it with the + # previous version + for x in range(iterations - 1): + ui = hmac.new(p, ui.digest(), hashlib.sha256) + # this is a fancy way of XORing two byte strings together + u = self._bytes_xor(u, ui.digest()) + return u + + cdef _normalize_password(self, str original_password): + """Normalize the password using the SASLprep from RFC4013""" + cdef: + str normalized_password + + # Note: Per the PostgreSQL documentation, PostgreSWL does not require + # UTF-8 to be used for the password, but will perform SASLprep on the + # password regardless. + # If the password is not valid UTF-8, PostgreSQL will then **not** use + # SASLprep processing. + # If the password fails SASLprep, the password should still be sent + # See: https://www.postgresql.org/docs/current/sasl-authentication.html + # and + # https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/common/saslprep.c + # using the `pg_saslprep` function + normalized_password = original_password + # if the original password is an ASCII string or fails to encode as a + # UTF-8 string, then no further action is needed + try: + original_password.encode("ascii") + except UnicodeEncodeError: + pass + else: + return original_password + + # Step 1 of SASLPrep: Map. Per the algorithm, we map non-ascii space + # characters to ASCII spaces (\x20 or \u0020, but we will use ' ') and + # commonly mapped to nothing characters are removed + # Table C.1.2 -- non-ASCII spaces + # Table B.1 -- "Commonly mapped to nothing" + normalized_password = u"".join( + ' ' if stringprep.in_table_c12(c) else c + for c in tuple(normalized_password) if not stringprep.in_table_b1(c) + ) + + # If at this point the password is empty, PostgreSQL uses the original + # password + if not normalized_password: + return original_password + + # Step 2 of SASLPrep: Normalize. Normalize the password using the + # Unicode normalization algorithm to NFKC form + normalized_password = unicodedata.normalize('NFKC', normalized_password) + + # If the password is not empty, PostgreSQL uses the original password + if not normalized_password: + return original_password + + normalized_password_tuple = tuple(normalized_password) + + # Step 3 of SASLPrep: Prohobited characters. If PostgreSQL detects any + # of the prohibited characters in SASLPrep, it will use the original + # password + # We also include "unassigned code points" in the prohibited character + # category as PostgreSQL does the same + for c in normalized_password_tuple: + if any( + in_prohibited_table(c) + for in_prohibited_table in self.SASLPREP_PROHIBITED + ): + return original_password + + # Step 4 of SASLPrep: Bi-directional characters. PostgreSQL follows the + # rules for bi-directional characters laid on in RFC3454 Sec. 6 which + # are: + # 1. Characters in RFC 3454 Sec 5.8 are prohibited (C.8) + # 2. If a string contains a RandALCat character, it cannot containy any + # LCat character + # 3. If the string contains any RandALCat character, an RandALCat + # character must be the first and last character of the string + # RandALCat characters are found in table D.1, whereas LCat are in D.2 + if any(stringprep.in_table_d1(c) for c in normalized_password_tuple): + # if the first character or the last character are not in D.1, + # return the original password + if not (stringprep.in_table_d1(normalized_password_tuple[0]) and + stringprep.in_table_d1(normalized_password_tuple[-1])): + return original_password + + # if any characters are in D.2, use the original password + if any( + stringprep.in_table_d2(c) for c in normalized_password_tuple + ): + return original_password + + # return the normalized password + return normalized_password diff --git a/env/Lib/site-packages/asyncpg/protocol/settings.pxd b/env/Lib/site-packages/asyncpg/protocol/settings.pxd new file mode 100644 index 0000000..0a1a5f6 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/settings.pxd @@ -0,0 +1,30 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +cdef class ConnectionSettings(pgproto.CodecContext): + cdef: + str _encoding + object _codec + dict _settings + bint _is_utf8 + DataCodecConfig _data_codecs + + cdef add_setting(self, str name, str val) + cdef is_encoding_utf8(self) + cpdef get_text_codec(self) + cpdef inline register_data_types(self, types) + cpdef inline add_python_codec( + self, typeoid, typename, typeschema, typeinfos, typekind, encoder, + decoder, format) + cpdef inline remove_python_codec( + self, typeoid, typename, typeschema) + cpdef inline clear_type_cache(self) + cpdef inline set_builtin_type_codec( + self, typeoid, typename, typeschema, typekind, alias_to, format) + cpdef inline Codec get_data_codec( + self, uint32_t oid, ServerDataFormat format=*, + bint ignore_custom_codec=*) diff --git a/env/Lib/site-packages/asyncpg/protocol/settings.pyx b/env/Lib/site-packages/asyncpg/protocol/settings.pyx new file mode 100644 index 0000000..8e6591b --- /dev/null +++ b/env/Lib/site-packages/asyncpg/protocol/settings.pyx @@ -0,0 +1,106 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +from asyncpg import exceptions + + +@cython.final +cdef class ConnectionSettings(pgproto.CodecContext): + + def __cinit__(self, conn_key): + self._encoding = 'utf-8' + self._is_utf8 = True + self._settings = {} + self._codec = codecs.lookup('utf-8') + self._data_codecs = DataCodecConfig(conn_key) + + cdef add_setting(self, str name, str val): + self._settings[name] = val + if name == 'client_encoding': + py_enc = get_python_encoding(val) + self._codec = codecs.lookup(py_enc) + self._encoding = self._codec.name + self._is_utf8 = self._encoding == 'utf-8' + + cdef is_encoding_utf8(self): + return self._is_utf8 + + cpdef get_text_codec(self): + return self._codec + + cpdef inline register_data_types(self, types): + self._data_codecs.add_types(types) + + cpdef inline add_python_codec(self, typeoid, typename, typeschema, + typeinfos, typekind, encoder, decoder, + format): + cdef: + ServerDataFormat _format + ClientExchangeFormat xformat + + if format == 'binary': + _format = PG_FORMAT_BINARY + xformat = PG_XFORMAT_OBJECT + elif format == 'text': + _format = PG_FORMAT_TEXT + xformat = PG_XFORMAT_OBJECT + elif format == 'tuple': + _format = PG_FORMAT_ANY + xformat = PG_XFORMAT_TUPLE + else: + raise exceptions.InterfaceError( + 'invalid `format` argument, expected {}, got {!r}'.format( + "'text', 'binary' or 'tuple'", format + )) + + self._data_codecs.add_python_codec(typeoid, typename, typeschema, + typekind, typeinfos, + encoder, decoder, + _format, xformat) + + cpdef inline remove_python_codec(self, typeoid, typename, typeschema): + self._data_codecs.remove_python_codec(typeoid, typename, typeschema) + + cpdef inline clear_type_cache(self): + self._data_codecs.clear_type_cache() + + cpdef inline set_builtin_type_codec(self, typeoid, typename, typeschema, + typekind, alias_to, format): + cdef: + ServerDataFormat _format + + if format is None: + _format = PG_FORMAT_ANY + elif format == 'binary': + _format = PG_FORMAT_BINARY + elif format == 'text': + _format = PG_FORMAT_TEXT + else: + raise exceptions.InterfaceError( + 'invalid `format` argument, expected {}, got {!r}'.format( + "'text' or 'binary'", format + )) + + self._data_codecs.set_builtin_type_codec(typeoid, typename, typeschema, + typekind, alias_to, _format) + + cpdef inline Codec get_data_codec(self, uint32_t oid, + ServerDataFormat format=PG_FORMAT_ANY, + bint ignore_custom_codec=False): + return self._data_codecs.get_codec(oid, format, ignore_custom_codec) + + def __getattr__(self, name): + if not name.startswith('_'): + try: + return self._settings[name] + except KeyError: + raise AttributeError(name) from None + + return object.__getattribute__(self, name) + + def __repr__(self): + return ''.format(self._settings) diff --git a/env/Lib/site-packages/asyncpg/serverversion.py b/env/Lib/site-packages/asyncpg/serverversion.py new file mode 100644 index 0000000..31568a2 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/serverversion.py @@ -0,0 +1,60 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import re + +from .types import ServerVersion + +version_regex = re.compile( + r"(Postgre[^\s]*)?\s*" + r"(?P[0-9]+)\.?" + r"((?P[0-9]+)\.?)?" + r"(?P[0-9]+)?" + r"(?P[a-z]+)?" + r"(?P[0-9]+)?" +) + + +def split_server_version_string(version_string): + version_match = version_regex.search(version_string) + + if version_match is None: + raise ValueError( + "Unable to parse Postgres " + f'version from "{version_string}"' + ) + + version = version_match.groupdict() + for ver_key, ver_value in version.items(): + # Cast all possible versions parts to int + try: + version[ver_key] = int(ver_value) + except (TypeError, ValueError): + pass + + if version.get("major") < 10: + return ServerVersion( + version.get("major"), + version.get("minor") or 0, + version.get("micro") or 0, + version.get("releaselevel") or "final", + version.get("serial") or 0, + ) + + # Since PostgreSQL 10 the versioning scheme has changed. + # 10.x really means 10.0.x. While parsing 10.1 + # as (10, 1) may seem less confusing, in practice most + # version checks are written as version[:2], and we + # want to keep that behaviour consistent, i.e not fail + # a major version check due to a bugfix release. + return ServerVersion( + version.get("major"), + 0, + version.get("minor") or 0, + version.get("releaselevel") or "final", + version.get("serial") or 0, + ) diff --git a/env/Lib/site-packages/asyncpg/transaction.py b/env/Lib/site-packages/asyncpg/transaction.py new file mode 100644 index 0000000..562811e --- /dev/null +++ b/env/Lib/site-packages/asyncpg/transaction.py @@ -0,0 +1,246 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import enum + +from . import connresource +from . import exceptions as apg_errors + + +class TransactionState(enum.Enum): + NEW = 0 + STARTED = 1 + COMMITTED = 2 + ROLLEDBACK = 3 + FAILED = 4 + + +ISOLATION_LEVELS = { + 'read_committed', + 'read_uncommitted', + 'serializable', + 'repeatable_read', +} +ISOLATION_LEVELS_BY_VALUE = { + 'read committed': 'read_committed', + 'read uncommitted': 'read_uncommitted', + 'serializable': 'serializable', + 'repeatable read': 'repeatable_read', +} + + +class Transaction(connresource.ConnectionResource): + """Represents a transaction or savepoint block. + + Transactions are created by calling the + :meth:`Connection.transaction() ` + function. + """ + + __slots__ = ('_connection', '_isolation', '_readonly', '_deferrable', + '_state', '_nested', '_id', '_managed') + + def __init__(self, connection, isolation, readonly, deferrable): + super().__init__(connection) + + if isolation and isolation not in ISOLATION_LEVELS: + raise ValueError( + 'isolation is expected to be either of {}, ' + 'got {!r}'.format(ISOLATION_LEVELS, isolation)) + + self._isolation = isolation + self._readonly = readonly + self._deferrable = deferrable + self._state = TransactionState.NEW + self._nested = False + self._id = None + self._managed = False + + async def __aenter__(self): + if self._managed: + raise apg_errors.InterfaceError( + 'cannot enter context: already in an `async with` block') + self._managed = True + await self.start() + + async def __aexit__(self, extype, ex, tb): + try: + self._check_conn_validity('__aexit__') + except apg_errors.InterfaceError: + if extype is GeneratorExit: + # When a PoolAcquireContext is being exited, and there + # is an open transaction in an async generator that has + # not been iterated fully, there is a possibility that + # Pool.release() would race with this __aexit__(), since + # both would be in concurrent tasks. In such case we + # yield to Pool.release() to do the ROLLBACK for us. + # See https://github.com/MagicStack/asyncpg/issues/232 + # for an example. + return + else: + raise + + try: + if extype is not None: + await self.__rollback() + else: + await self.__commit() + finally: + self._managed = False + + @connresource.guarded + async def start(self): + """Enter the transaction or savepoint block.""" + self.__check_state_base('start') + if self._state is TransactionState.STARTED: + raise apg_errors.InterfaceError( + 'cannot start; the transaction is already started') + + con = self._connection + + if con._top_xact is None: + if con._protocol.is_in_transaction(): + raise apg_errors.InterfaceError( + 'cannot use Connection.transaction() in ' + 'a manually started transaction') + con._top_xact = self + else: + # Nested transaction block + if self._isolation: + top_xact_isolation = con._top_xact._isolation + if top_xact_isolation is None: + top_xact_isolation = ISOLATION_LEVELS_BY_VALUE[ + await self._connection.fetchval( + 'SHOW transaction_isolation;')] + if self._isolation != top_xact_isolation: + raise apg_errors.InterfaceError( + 'nested transaction has a different isolation level: ' + 'current {!r} != outer {!r}'.format( + self._isolation, top_xact_isolation)) + self._nested = True + + if self._nested: + self._id = con._get_unique_id('savepoint') + query = 'SAVEPOINT {};'.format(self._id) + else: + query = 'BEGIN' + if self._isolation == 'read_committed': + query += ' ISOLATION LEVEL READ COMMITTED' + elif self._isolation == 'read_uncommitted': + query += ' ISOLATION LEVEL READ UNCOMMITTED' + elif self._isolation == 'repeatable_read': + query += ' ISOLATION LEVEL REPEATABLE READ' + elif self._isolation == 'serializable': + query += ' ISOLATION LEVEL SERIALIZABLE' + if self._readonly: + query += ' READ ONLY' + if self._deferrable: + query += ' DEFERRABLE' + query += ';' + + try: + await self._connection.execute(query) + except BaseException: + self._state = TransactionState.FAILED + raise + else: + self._state = TransactionState.STARTED + + def __check_state_base(self, opname): + if self._state is TransactionState.COMMITTED: + raise apg_errors.InterfaceError( + 'cannot {}; the transaction is already committed'.format( + opname)) + if self._state is TransactionState.ROLLEDBACK: + raise apg_errors.InterfaceError( + 'cannot {}; the transaction is already rolled back'.format( + opname)) + if self._state is TransactionState.FAILED: + raise apg_errors.InterfaceError( + 'cannot {}; the transaction is in error state'.format( + opname)) + + def __check_state(self, opname): + if self._state is not TransactionState.STARTED: + if self._state is TransactionState.NEW: + raise apg_errors.InterfaceError( + 'cannot {}; the transaction is not yet started'.format( + opname)) + self.__check_state_base(opname) + + async def __commit(self): + self.__check_state('commit') + + if self._connection._top_xact is self: + self._connection._top_xact = None + + if self._nested: + query = 'RELEASE SAVEPOINT {};'.format(self._id) + else: + query = 'COMMIT;' + + try: + await self._connection.execute(query) + except BaseException: + self._state = TransactionState.FAILED + raise + else: + self._state = TransactionState.COMMITTED + + async def __rollback(self): + self.__check_state('rollback') + + if self._connection._top_xact is self: + self._connection._top_xact = None + + if self._nested: + query = 'ROLLBACK TO {};'.format(self._id) + else: + query = 'ROLLBACK;' + + try: + await self._connection.execute(query) + except BaseException: + self._state = TransactionState.FAILED + raise + else: + self._state = TransactionState.ROLLEDBACK + + @connresource.guarded + async def commit(self): + """Exit the transaction or savepoint block and commit changes.""" + if self._managed: + raise apg_errors.InterfaceError( + 'cannot manually commit from within an `async with` block') + await self.__commit() + + @connresource.guarded + async def rollback(self): + """Exit the transaction or savepoint block and rollback changes.""" + if self._managed: + raise apg_errors.InterfaceError( + 'cannot manually rollback from within an `async with` block') + await self.__rollback() + + def __repr__(self): + attrs = [] + attrs.append('state:{}'.format(self._state.name.lower())) + + if self._isolation is not None: + attrs.append(self._isolation) + if self._readonly: + attrs.append('readonly') + if self._deferrable: + attrs.append('deferrable') + + if self.__class__.__module__.startswith('asyncpg.'): + mod = 'asyncpg' + else: + mod = self.__class__.__module__ + + return '<{}.{} {} {:#x}>'.format( + mod, self.__class__.__name__, ' '.join(attrs), id(self)) diff --git a/env/Lib/site-packages/asyncpg/types.py b/env/Lib/site-packages/asyncpg/types.py new file mode 100644 index 0000000..bd5813f --- /dev/null +++ b/env/Lib/site-packages/asyncpg/types.py @@ -0,0 +1,177 @@ +# Copyright (C) 2016-present the asyncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import collections + +from asyncpg.pgproto.types import ( + BitString, Point, Path, Polygon, + Box, Line, LineSegment, Circle, +) + + +__all__ = ( + 'Type', 'Attribute', 'Range', 'BitString', 'Point', 'Path', 'Polygon', + 'Box', 'Line', 'LineSegment', 'Circle', 'ServerVersion', +) + + +Type = collections.namedtuple('Type', ['oid', 'name', 'kind', 'schema']) +Type.__doc__ = 'Database data type.' +Type.oid.__doc__ = 'OID of the type.' +Type.name.__doc__ = 'Type name. For example "int2".' +Type.kind.__doc__ = \ + 'Type kind. Can be "scalar", "array", "composite" or "range".' +Type.schema.__doc__ = 'Name of the database schema that defines the type.' + + +Attribute = collections.namedtuple('Attribute', ['name', 'type']) +Attribute.__doc__ = 'Database relation attribute.' +Attribute.name.__doc__ = 'Attribute name.' +Attribute.type.__doc__ = 'Attribute data type :class:`asyncpg.types.Type`.' + + +ServerVersion = collections.namedtuple( + 'ServerVersion', ['major', 'minor', 'micro', 'releaselevel', 'serial']) +ServerVersion.__doc__ = 'PostgreSQL server version tuple.' + + +class Range: + """Immutable representation of PostgreSQL `range` type.""" + + __slots__ = '_lower', '_upper', '_lower_inc', '_upper_inc', '_empty' + + def __init__(self, lower=None, upper=None, *, + lower_inc=True, upper_inc=False, + empty=False): + self._empty = empty + if empty: + self._lower = self._upper = None + self._lower_inc = self._upper_inc = False + else: + self._lower = lower + self._upper = upper + self._lower_inc = lower is not None and lower_inc + self._upper_inc = upper is not None and upper_inc + + @property + def lower(self): + return self._lower + + @property + def lower_inc(self): + return self._lower_inc + + @property + def lower_inf(self): + return self._lower is None and not self._empty + + @property + def upper(self): + return self._upper + + @property + def upper_inc(self): + return self._upper_inc + + @property + def upper_inf(self): + return self._upper is None and not self._empty + + @property + def isempty(self): + return self._empty + + def _issubset_lower(self, other): + if other._lower is None: + return True + if self._lower is None: + return False + + return self._lower > other._lower or ( + self._lower == other._lower + and (other._lower_inc or not self._lower_inc) + ) + + def _issubset_upper(self, other): + if other._upper is None: + return True + if self._upper is None: + return False + + return self._upper < other._upper or ( + self._upper == other._upper + and (other._upper_inc or not self._upper_inc) + ) + + def issubset(self, other): + if self._empty: + return True + if other._empty: + return False + + return self._issubset_lower(other) and self._issubset_upper(other) + + def issuperset(self, other): + return other.issubset(self) + + def __bool__(self): + return not self._empty + + def __eq__(self, other): + if not isinstance(other, Range): + return NotImplemented + + return ( + self._lower, + self._upper, + self._lower_inc, + self._upper_inc, + self._empty + ) == ( + other._lower, + other._upper, + other._lower_inc, + other._upper_inc, + other._empty + ) + + def __hash__(self): + return hash(( + self._lower, + self._upper, + self._lower_inc, + self._upper_inc, + self._empty + )) + + def __repr__(self): + if self._empty: + desc = 'empty' + else: + if self._lower is None or not self._lower_inc: + lb = '(' + else: + lb = '[' + + if self._lower is not None: + lb += repr(self._lower) + + if self._upper is not None: + ub = repr(self._upper) + else: + ub = '' + + if self._upper is None or not self._upper_inc: + ub += ')' + else: + ub += ']' + + desc = '{}, {}'.format(lb, ub) + + return ''.format(desc) + + __str__ = __repr__ diff --git a/env/Lib/site-packages/asyncpg/utils.py b/env/Lib/site-packages/asyncpg/utils.py new file mode 100644 index 0000000..3940e04 --- /dev/null +++ b/env/Lib/site-packages/asyncpg/utils.py @@ -0,0 +1,45 @@ +# Copyright (C) 2016-present the ayncpg authors and contributors +# +# +# This module is part of asyncpg and is released under +# the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 + + +import re + + +def _quote_ident(ident): + return '"{}"'.format(ident.replace('"', '""')) + + +def _quote_literal(string): + return "'{}'".format(string.replace("'", "''")) + + +async def _mogrify(conn, query, args): + """Safely inline arguments to query text.""" + # Introspect the target query for argument types and + # build a list of safely-quoted fully-qualified type names. + ps = await conn.prepare(query) + paramtypes = [] + for t in ps.get_parameters(): + if t.name.endswith('[]'): + pname = '_' + t.name[:-2] + else: + pname = t.name + + paramtypes.append('{}.{}'.format( + _quote_ident(t.schema), _quote_ident(pname))) + del ps + + # Use Postgres to convert arguments to text representation + # by casting each value to text. + cols = ['quote_literal(${}::{}::text)'.format(i, t) + for i, t in enumerate(paramtypes, start=1)] + + textified = await conn.fetchrow( + 'SELECT {cols}'.format(cols=', '.join(cols)), *args) + + # Finally, replace $n references with text values. + return re.sub( + r'\$(\d+)\b', lambda m: textified[int(m.group(1)) - 1], query) diff --git a/env/Lib/site-packages/attr/__init__.py b/env/Lib/site-packages/attr/__init__.py new file mode 100644 index 0000000..51b1c25 --- /dev/null +++ b/env/Lib/site-packages/attr/__init__.py @@ -0,0 +1,103 @@ +# SPDX-License-Identifier: MIT + +""" +Classes Without Boilerplate +""" + +from functools import partial +from typing import Callable + +from . import converters, exceptions, filters, setters, validators +from ._cmp import cmp_using +from ._compat import Protocol +from ._config import get_run_validators, set_run_validators +from ._funcs import asdict, assoc, astuple, evolve, has, resolve_types +from ._make import ( + NOTHING, + Attribute, + Converter, + Factory, + attrib, + attrs, + fields, + fields_dict, + make_class, + validate, +) +from ._next_gen import define, field, frozen, mutable +from ._version_info import VersionInfo + + +s = attributes = attrs +ib = attr = attrib +dataclass = partial(attrs, auto_attribs=True) # happy Easter ;) + + +class AttrsInstance(Protocol): + pass + + +__all__ = [ + "Attribute", + "AttrsInstance", + "Converter", + "Factory", + "NOTHING", + "asdict", + "assoc", + "astuple", + "attr", + "attrib", + "attributes", + "attrs", + "cmp_using", + "converters", + "define", + "evolve", + "exceptions", + "field", + "fields", + "fields_dict", + "filters", + "frozen", + "get_run_validators", + "has", + "ib", + "make_class", + "mutable", + "resolve_types", + "s", + "set_run_validators", + "setters", + "validate", + "validators", +] + + +def _make_getattr(mod_name: str) -> Callable: + """ + Create a metadata proxy for packaging information that uses *mod_name* in + its warnings and errors. + """ + + def __getattr__(name: str) -> str: + if name not in ("__version__", "__version_info__"): + msg = f"module {mod_name} has no attribute {name}" + raise AttributeError(msg) + + try: + from importlib.metadata import metadata + except ImportError: + from importlib_metadata import metadata + + meta = metadata("attrs") + + if name == "__version_info__": + return VersionInfo._from_version_string(meta["version"]) + + return meta["version"] + + return __getattr__ + + +__getattr__ = _make_getattr(__name__) diff --git a/env/Lib/site-packages/attr/__init__.pyi b/env/Lib/site-packages/attr/__init__.pyi new file mode 100644 index 0000000..6ae0a83 --- /dev/null +++ b/env/Lib/site-packages/attr/__init__.pyi @@ -0,0 +1,388 @@ +import enum +import sys + +from typing import ( + Any, + Callable, + Generic, + Mapping, + Protocol, + Sequence, + TypeVar, + overload, +) + +# `import X as X` is required to make these public +from . import converters as converters +from . import exceptions as exceptions +from . import filters as filters +from . import setters as setters +from . import validators as validators +from ._cmp import cmp_using as cmp_using +from ._typing_compat import AttrsInstance_ +from ._version_info import VersionInfo +from attrs import ( + define as define, + field as field, + mutable as mutable, + frozen as frozen, + _EqOrderType, + _ValidatorType, + _ConverterType, + _ReprArgType, + _OnSetAttrType, + _OnSetAttrArgType, + _FieldTransformer, + _ValidatorArgType, +) + +if sys.version_info >= (3, 10): + from typing import TypeGuard +else: + from typing_extensions import TypeGuard + +if sys.version_info >= (3, 11): + from typing import dataclass_transform +else: + from typing_extensions import dataclass_transform + +__version__: str +__version_info__: VersionInfo +__title__: str +__description__: str +__url__: str +__uri__: str +__author__: str +__email__: str +__license__: str +__copyright__: str + +_T = TypeVar("_T") +_C = TypeVar("_C", bound=type) + +_FilterType = Callable[["Attribute[_T]", _T], bool] + +# We subclass this here to keep the protocol's qualified name clean. +class AttrsInstance(AttrsInstance_, Protocol): + pass + +_A = TypeVar("_A", bound=type[AttrsInstance]) + +class _Nothing(enum.Enum): + NOTHING = enum.auto() + +NOTHING = _Nothing.NOTHING + +# NOTE: Factory lies about its return type to make this possible: +# `x: List[int] # = Factory(list)` +# Work around mypy issue #4554 in the common case by using an overload. +if sys.version_info >= (3, 8): + from typing import Literal + @overload + def Factory(factory: Callable[[], _T]) -> _T: ... + @overload + def Factory( + factory: Callable[[Any], _T], + takes_self: Literal[True], + ) -> _T: ... + @overload + def Factory( + factory: Callable[[], _T], + takes_self: Literal[False], + ) -> _T: ... + +else: + @overload + def Factory(factory: Callable[[], _T]) -> _T: ... + @overload + def Factory( + factory: Union[Callable[[Any], _T], Callable[[], _T]], + takes_self: bool = ..., + ) -> _T: ... + +In = TypeVar("In") +Out = TypeVar("Out") + +class Converter(Generic[In, Out]): + @overload + def __init__(self, converter: Callable[[In], Out]) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, AttrsInstance, Attribute], Out], + *, + takes_self: Literal[True], + takes_field: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, Attribute], Out], + *, + takes_field: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, AttrsInstance], Out], + *, + takes_self: Literal[True], + ) -> None: ... + +class Attribute(Generic[_T]): + name: str + default: _T | None + validator: _ValidatorType[_T] | None + repr: _ReprArgType + cmp: _EqOrderType + eq: _EqOrderType + order: _EqOrderType + hash: bool | None + init: bool + converter: _ConverterType | Converter[Any, _T] | None + metadata: dict[Any, Any] + type: type[_T] | None + kw_only: bool + on_setattr: _OnSetAttrType + alias: str | None + + def evolve(self, **changes: Any) -> "Attribute[Any]": ... + +# NOTE: We had several choices for the annotation to use for type arg: +# 1) Type[_T] +# - Pros: Handles simple cases correctly +# - Cons: Might produce less informative errors in the case of conflicting +# TypeVars e.g. `attr.ib(default='bad', type=int)` +# 2) Callable[..., _T] +# - Pros: Better error messages than #1 for conflicting TypeVars +# - Cons: Terrible error messages for validator checks. +# e.g. attr.ib(type=int, validator=validate_str) +# -> error: Cannot infer function type argument +# 3) type (and do all of the work in the mypy plugin) +# - Pros: Simple here, and we could customize the plugin with our own errors. +# - Cons: Would need to write mypy plugin code to handle all the cases. +# We chose option #1. + +# `attr` lies about its return type to make the following possible: +# attr() -> Any +# attr(8) -> int +# attr(validator=) -> Whatever the callable expects. +# This makes this type of assignments possible: +# x: int = attr(8) +# +# This form catches explicit None or no default but with no other arguments +# returns Any. +@overload +def attrib( + default: None = ..., + validator: None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: None = ..., + converter: None = ..., + factory: None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> Any: ... + +# This form catches an explicit None or no default and infers the type from the +# other arguments. +@overload +def attrib( + default: None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: type[_T] | None = ..., + converter: _ConverterType | Converter[Any, _T] | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> _T: ... + +# This form catches an explicit default argument. +@overload +def attrib( + default: _T, + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: type[_T] | None = ..., + converter: _ConverterType | Converter[Any, _T] | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> _T: ... + +# This form covers type=non-Type: e.g. forward references (str), Any +@overload +def attrib( + default: _T | None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: object = ..., + converter: _ConverterType | Converter[Any, _T] | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> Any: ... +@overload +@dataclass_transform(order_default=True, field_specifiers=(attrib, field)) +def attrs( + maybe_cls: _C, + these: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + auto_detect: bool = ..., + collect_by_mro: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., + unsafe_hash: bool | None = ..., +) -> _C: ... +@overload +@dataclass_transform(order_default=True, field_specifiers=(attrib, field)) +def attrs( + maybe_cls: None = ..., + these: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + auto_detect: bool = ..., + collect_by_mro: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., + unsafe_hash: bool | None = ..., +) -> Callable[[_C], _C]: ... +def fields(cls: type[AttrsInstance]) -> Any: ... +def fields_dict(cls: type[AttrsInstance]) -> dict[str, Attribute[Any]]: ... +def validate(inst: AttrsInstance) -> None: ... +def resolve_types( + cls: _A, + globalns: dict[str, Any] | None = ..., + localns: dict[str, Any] | None = ..., + attribs: list[Attribute[Any]] | None = ..., + include_extras: bool = ..., +) -> _A: ... + +# TODO: add support for returning a proper attrs class from the mypy plugin +# we use Any instead of _CountingAttr so that e.g. `make_class('Foo', +# [attr.ib()])` is valid +def make_class( + name: str, + attrs: list[str] | tuple[str, ...] | dict[str, Any], + bases: tuple[type, ...] = ..., + class_body: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + collect_by_mro: bool = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., +) -> type: ... + +# _funcs -- + +# TODO: add support for returning TypedDict from the mypy plugin +# FIXME: asdict/astuple do not honor their factory args. Waiting on one of +# these: +# https://github.com/python/mypy/issues/4236 +# https://github.com/python/typing/issues/253 +# XXX: remember to fix attrs.asdict/astuple too! +def asdict( + inst: AttrsInstance, + recurse: bool = ..., + filter: _FilterType[Any] | None = ..., + dict_factory: type[Mapping[Any, Any]] = ..., + retain_collection_types: bool = ..., + value_serializer: Callable[[type, Attribute[Any], Any], Any] | None = ..., + tuple_keys: bool | None = ..., +) -> dict[str, Any]: ... + +# TODO: add support for returning NamedTuple from the mypy plugin +def astuple( + inst: AttrsInstance, + recurse: bool = ..., + filter: _FilterType[Any] | None = ..., + tuple_factory: type[Sequence[Any]] = ..., + retain_collection_types: bool = ..., +) -> tuple[Any, ...]: ... +def has(cls: type) -> TypeGuard[type[AttrsInstance]]: ... +def assoc(inst: _T, **changes: Any) -> _T: ... +def evolve(inst: _T, **changes: Any) -> _T: ... + +# _config -- + +def set_run_validators(run: bool) -> None: ... +def get_run_validators() -> bool: ... + +# aliases -- + +s = attributes = attrs +ib = attr = attrib +dataclass = attrs # Technically, partial(attrs, auto_attribs=True) ;) diff --git a/env/Lib/site-packages/attr/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..c5344a1 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/_cmp.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/_cmp.cpython-311.pyc new file mode 100644 index 0000000..ce3b8a1 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/_cmp.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/_compat.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/_compat.cpython-311.pyc new file mode 100644 index 0000000..419943e Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/_compat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/_config.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/_config.cpython-311.pyc new file mode 100644 index 0000000..f996182 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/_config.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/_funcs.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/_funcs.cpython-311.pyc new file mode 100644 index 0000000..57205c4 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/_funcs.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/_make.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/_make.cpython-311.pyc new file mode 100644 index 0000000..c183507 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/_make.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/_next_gen.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/_next_gen.cpython-311.pyc new file mode 100644 index 0000000..46af57f Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/_next_gen.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/_version_info.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/_version_info.cpython-311.pyc new file mode 100644 index 0000000..a31cf90 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/_version_info.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/converters.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/converters.cpython-311.pyc new file mode 100644 index 0000000..74f4196 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/converters.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/exceptions.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000..af4812e Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/exceptions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/filters.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000..e26682d Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/filters.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/setters.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/setters.cpython-311.pyc new file mode 100644 index 0000000..38e1613 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/setters.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/__pycache__/validators.cpython-311.pyc b/env/Lib/site-packages/attr/__pycache__/validators.cpython-311.pyc new file mode 100644 index 0000000..3107035 Binary files /dev/null and b/env/Lib/site-packages/attr/__pycache__/validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attr/_cmp.py b/env/Lib/site-packages/attr/_cmp.py new file mode 100644 index 0000000..f367bb3 --- /dev/null +++ b/env/Lib/site-packages/attr/_cmp.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: MIT + + +import functools +import types + +from ._make import _make_ne + + +_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="} + + +def cmp_using( + eq=None, + lt=None, + le=None, + gt=None, + ge=None, + require_same_type=True, + class_name="Comparable", +): + """ + Create a class that can be passed into `attrs.field`'s ``eq``, ``order``, + and ``cmp`` arguments to customize field comparison. + + The resulting class will have a full set of ordering methods if at least + one of ``{lt, le, gt, ge}`` and ``eq`` are provided. + + Args: + eq (typing.Callable | None): + Callable used to evaluate equality of two objects. + + lt (typing.Callable | None): + Callable used to evaluate whether one object is less than another + object. + + le (typing.Callable | None): + Callable used to evaluate whether one object is less than or equal + to another object. + + gt (typing.Callable | None): + Callable used to evaluate whether one object is greater than + another object. + + ge (typing.Callable | None): + Callable used to evaluate whether one object is greater than or + equal to another object. + + require_same_type (bool): + When `True`, equality and ordering methods will return + `NotImplemented` if objects are not of the same type. + + class_name (str | None): Name of class. Defaults to "Comparable". + + See `comparison` for more details. + + .. versionadded:: 21.1.0 + """ + + body = { + "__slots__": ["value"], + "__init__": _make_init(), + "_requirements": [], + "_is_comparable_to": _is_comparable_to, + } + + # Add operations. + num_order_functions = 0 + has_eq_function = False + + if eq is not None: + has_eq_function = True + body["__eq__"] = _make_operator("eq", eq) + body["__ne__"] = _make_ne() + + if lt is not None: + num_order_functions += 1 + body["__lt__"] = _make_operator("lt", lt) + + if le is not None: + num_order_functions += 1 + body["__le__"] = _make_operator("le", le) + + if gt is not None: + num_order_functions += 1 + body["__gt__"] = _make_operator("gt", gt) + + if ge is not None: + num_order_functions += 1 + body["__ge__"] = _make_operator("ge", ge) + + type_ = types.new_class( + class_name, (object,), {}, lambda ns: ns.update(body) + ) + + # Add same type requirement. + if require_same_type: + type_._requirements.append(_check_same_type) + + # Add total ordering if at least one operation was defined. + if 0 < num_order_functions < 4: + if not has_eq_function: + # functools.total_ordering requires __eq__ to be defined, + # so raise early error here to keep a nice stack. + msg = "eq must be define is order to complete ordering from lt, le, gt, ge." + raise ValueError(msg) + type_ = functools.total_ordering(type_) + + return type_ + + +def _make_init(): + """ + Create __init__ method. + """ + + def __init__(self, value): + """ + Initialize object with *value*. + """ + self.value = value + + return __init__ + + +def _make_operator(name, func): + """ + Create operator method. + """ + + def method(self, other): + if not self._is_comparable_to(other): + return NotImplemented + + result = func(self.value, other.value) + if result is NotImplemented: + return NotImplemented + + return result + + method.__name__ = f"__{name}__" + method.__doc__ = ( + f"Return a {_operation_names[name]} b. Computed by attrs." + ) + + return method + + +def _is_comparable_to(self, other): + """ + Check whether `other` is comparable to `self`. + """ + return all(func(self, other) for func in self._requirements) + + +def _check_same_type(self, other): + """ + Return True if *self* and *other* are of the same type, False otherwise. + """ + return other.value.__class__ is self.value.__class__ diff --git a/env/Lib/site-packages/attr/_cmp.pyi b/env/Lib/site-packages/attr/_cmp.pyi new file mode 100644 index 0000000..cc7893b --- /dev/null +++ b/env/Lib/site-packages/attr/_cmp.pyi @@ -0,0 +1,13 @@ +from typing import Any, Callable + +_CompareWithType = Callable[[Any, Any], bool] + +def cmp_using( + eq: _CompareWithType | None = ..., + lt: _CompareWithType | None = ..., + le: _CompareWithType | None = ..., + gt: _CompareWithType | None = ..., + ge: _CompareWithType | None = ..., + require_same_type: bool = ..., + class_name: str = ..., +) -> type: ... diff --git a/env/Lib/site-packages/attr/_compat.py b/env/Lib/site-packages/attr/_compat.py new file mode 100644 index 0000000..104eeb0 --- /dev/null +++ b/env/Lib/site-packages/attr/_compat.py @@ -0,0 +1,103 @@ +# SPDX-License-Identifier: MIT + +import inspect +import platform +import sys +import threading + +from collections.abc import Mapping, Sequence # noqa: F401 +from typing import _GenericAlias + + +PYPY = platform.python_implementation() == "PyPy" +PY_3_8_PLUS = sys.version_info[:2] >= (3, 8) +PY_3_9_PLUS = sys.version_info[:2] >= (3, 9) +PY_3_10_PLUS = sys.version_info[:2] >= (3, 10) +PY_3_11_PLUS = sys.version_info[:2] >= (3, 11) +PY_3_12_PLUS = sys.version_info[:2] >= (3, 12) +PY_3_13_PLUS = sys.version_info[:2] >= (3, 13) +PY_3_14_PLUS = sys.version_info[:2] >= (3, 14) + + +if sys.version_info < (3, 8): + try: + from typing_extensions import Protocol + except ImportError: # pragma: no cover + Protocol = object +else: + from typing import Protocol # noqa: F401 + +if PY_3_14_PLUS: # pragma: no cover + import annotationlib + + _get_annotations = annotationlib.get_annotations + +else: + + def _get_annotations(cls): + """ + Get annotations for *cls*. + """ + return cls.__dict__.get("__annotations__", {}) + + +class _AnnotationExtractor: + """ + Extract type annotations from a callable, returning None whenever there + is none. + """ + + __slots__ = ["sig"] + + def __init__(self, callable): + try: + self.sig = inspect.signature(callable) + except (ValueError, TypeError): # inspect failed + self.sig = None + + def get_first_param_type(self): + """ + Return the type annotation of the first argument if it's not empty. + """ + if not self.sig: + return None + + params = list(self.sig.parameters.values()) + if params and params[0].annotation is not inspect.Parameter.empty: + return params[0].annotation + + return None + + def get_return_type(self): + """ + Return the return type if it's not empty. + """ + if ( + self.sig + and self.sig.return_annotation is not inspect.Signature.empty + ): + return self.sig.return_annotation + + return None + + +# Thread-local global to track attrs instances which are already being repr'd. +# This is needed because there is no other (thread-safe) way to pass info +# about the instances that are already being repr'd through the call stack +# in order to ensure we don't perform infinite recursion. +# +# For instance, if an instance contains a dict which contains that instance, +# we need to know that we're already repr'ing the outside instance from within +# the dict's repr() call. +# +# This lives here rather than in _make.py so that the functions in _make.py +# don't have a direct reference to the thread-local in their globals dict. +# If they have such a reference, it breaks cloudpickle. +repr_context = threading.local() + + +def get_generic_base(cl): + """If this is a generic class (A[str]), return the generic base for it.""" + if cl.__class__ is _GenericAlias: + return cl.__origin__ + return None diff --git a/env/Lib/site-packages/attr/_config.py b/env/Lib/site-packages/attr/_config.py new file mode 100644 index 0000000..9c245b1 --- /dev/null +++ b/env/Lib/site-packages/attr/_config.py @@ -0,0 +1,31 @@ +# SPDX-License-Identifier: MIT + +__all__ = ["set_run_validators", "get_run_validators"] + +_run_validators = True + + +def set_run_validators(run): + """ + Set whether or not validators are run. By default, they are run. + + .. deprecated:: 21.3.0 It will not be removed, but it also will not be + moved to new ``attrs`` namespace. Use `attrs.validators.set_disabled()` + instead. + """ + if not isinstance(run, bool): + msg = "'run' must be bool." + raise TypeError(msg) + global _run_validators + _run_validators = run + + +def get_run_validators(): + """ + Return whether or not validators are run. + + .. deprecated:: 21.3.0 It will not be removed, but it also will not be + moved to new ``attrs`` namespace. Use `attrs.validators.get_disabled()` + instead. + """ + return _run_validators diff --git a/env/Lib/site-packages/attr/_funcs.py b/env/Lib/site-packages/attr/_funcs.py new file mode 100644 index 0000000..355cef4 --- /dev/null +++ b/env/Lib/site-packages/attr/_funcs.py @@ -0,0 +1,522 @@ +# SPDX-License-Identifier: MIT + + +import copy + +from ._compat import PY_3_9_PLUS, get_generic_base +from ._make import _OBJ_SETATTR, NOTHING, fields +from .exceptions import AttrsAttributeNotFoundError + + +def asdict( + inst, + recurse=True, + filter=None, + dict_factory=dict, + retain_collection_types=False, + value_serializer=None, +): + """ + Return the *attrs* attribute values of *inst* as a dict. + + Optionally recurse into other *attrs*-decorated classes. + + Args: + inst: Instance of an *attrs*-decorated class. + + recurse (bool): Recurse into classes that are also *attrs*-decorated. + + filter (~typing.Callable): + A callable whose return code determines whether an attribute or + element is included (`True`) or dropped (`False`). Is called with + the `attrs.Attribute` as the first argument and the value as the + second argument. + + dict_factory (~typing.Callable): + A callable to produce dictionaries from. For example, to produce + ordered dictionaries instead of normal Python dictionaries, pass in + ``collections.OrderedDict``. + + retain_collection_types (bool): + Do not convert to `list` when encountering an attribute whose type + is `tuple` or `set`. Only meaningful if *recurse* is `True`. + + value_serializer (typing.Callable | None): + A hook that is called for every attribute or dict key/value. It + receives the current instance, field and value and must return the + (updated) value. The hook is run *after* the optional *filter* has + been applied. + + Returns: + Return type of *dict_factory*. + + Raises: + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 16.0.0 *dict_factory* + .. versionadded:: 16.1.0 *retain_collection_types* + .. versionadded:: 20.3.0 *value_serializer* + .. versionadded:: 21.3.0 + If a dict has a collection for a key, it is serialized as a tuple. + """ + attrs = fields(inst.__class__) + rv = dict_factory() + for a in attrs: + v = getattr(inst, a.name) + if filter is not None and not filter(a, v): + continue + + if value_serializer is not None: + v = value_serializer(inst, a, v) + + if recurse is True: + if has(v.__class__): + rv[a.name] = asdict( + v, + recurse=True, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + elif isinstance(v, (tuple, list, set, frozenset)): + cf = v.__class__ if retain_collection_types is True else list + items = [ + _asdict_anything( + i, + is_key=False, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + for i in v + ] + try: + rv[a.name] = cf(items) + except TypeError: + if not issubclass(cf, tuple): + raise + # Workaround for TypeError: cf.__new__() missing 1 required + # positional argument (which appears, for a namedturle) + rv[a.name] = cf(*items) + elif isinstance(v, dict): + df = dict_factory + rv[a.name] = df( + ( + _asdict_anything( + kk, + is_key=True, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + _asdict_anything( + vv, + is_key=False, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + ) + for kk, vv in v.items() + ) + else: + rv[a.name] = v + else: + rv[a.name] = v + return rv + + +def _asdict_anything( + val, + is_key, + filter, + dict_factory, + retain_collection_types, + value_serializer, +): + """ + ``asdict`` only works on attrs instances, this works on anything. + """ + if getattr(val.__class__, "__attrs_attrs__", None) is not None: + # Attrs class. + rv = asdict( + val, + recurse=True, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + elif isinstance(val, (tuple, list, set, frozenset)): + if retain_collection_types is True: + cf = val.__class__ + elif is_key: + cf = tuple + else: + cf = list + + rv = cf( + [ + _asdict_anything( + i, + is_key=False, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + for i in val + ] + ) + elif isinstance(val, dict): + df = dict_factory + rv = df( + ( + _asdict_anything( + kk, + is_key=True, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + _asdict_anything( + vv, + is_key=False, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + ) + for kk, vv in val.items() + ) + else: + rv = val + if value_serializer is not None: + rv = value_serializer(None, None, rv) + + return rv + + +def astuple( + inst, + recurse=True, + filter=None, + tuple_factory=tuple, + retain_collection_types=False, +): + """ + Return the *attrs* attribute values of *inst* as a tuple. + + Optionally recurse into other *attrs*-decorated classes. + + Args: + inst: Instance of an *attrs*-decorated class. + + recurse (bool): + Recurse into classes that are also *attrs*-decorated. + + filter (~typing.Callable): + A callable whose return code determines whether an attribute or + element is included (`True`) or dropped (`False`). Is called with + the `attrs.Attribute` as the first argument and the value as the + second argument. + + tuple_factory (~typing.Callable): + A callable to produce tuples from. For example, to produce lists + instead of tuples. + + retain_collection_types (bool): + Do not convert to `list` or `dict` when encountering an attribute + which type is `tuple`, `dict` or `set`. Only meaningful if + *recurse* is `True`. + + Returns: + Return type of *tuple_factory* + + Raises: + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 16.2.0 + """ + attrs = fields(inst.__class__) + rv = [] + retain = retain_collection_types # Very long. :/ + for a in attrs: + v = getattr(inst, a.name) + if filter is not None and not filter(a, v): + continue + if recurse is True: + if has(v.__class__): + rv.append( + astuple( + v, + recurse=True, + filter=filter, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + ) + elif isinstance(v, (tuple, list, set, frozenset)): + cf = v.__class__ if retain is True else list + items = [ + ( + astuple( + j, + recurse=True, + filter=filter, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(j.__class__) + else j + ) + for j in v + ] + try: + rv.append(cf(items)) + except TypeError: + if not issubclass(cf, tuple): + raise + # Workaround for TypeError: cf.__new__() missing 1 required + # positional argument (which appears, for a namedturle) + rv.append(cf(*items)) + elif isinstance(v, dict): + df = v.__class__ if retain is True else dict + rv.append( + df( + ( + ( + astuple( + kk, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(kk.__class__) + else kk + ), + ( + astuple( + vv, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(vv.__class__) + else vv + ), + ) + for kk, vv in v.items() + ) + ) + else: + rv.append(v) + else: + rv.append(v) + + return rv if tuple_factory is list else tuple_factory(rv) + + +def has(cls): + """ + Check whether *cls* is a class with *attrs* attributes. + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + Returns: + bool: + """ + attrs = getattr(cls, "__attrs_attrs__", None) + if attrs is not None: + return True + + # No attrs, maybe it's a specialized generic (A[str])? + generic_base = get_generic_base(cls) + if generic_base is not None: + generic_attrs = getattr(generic_base, "__attrs_attrs__", None) + if generic_attrs is not None: + # Stick it on here for speed next time. + cls.__attrs_attrs__ = generic_attrs + return generic_attrs is not None + return False + + +def assoc(inst, **changes): + """ + Copy *inst* and apply *changes*. + + This is different from `evolve` that applies the changes to the arguments + that create the new instance. + + `evolve`'s behavior is preferable, but there are `edge cases`_ where it + doesn't work. Therefore `assoc` is deprecated, but will not be removed. + + .. _`edge cases`: https://github.com/python-attrs/attrs/issues/251 + + Args: + inst: Instance of a class with *attrs* attributes. + + changes: Keyword changes in the new copy. + + Returns: + A copy of inst with *changes* incorporated. + + Raises: + attrs.exceptions.AttrsAttributeNotFoundError: + If *attr_name* couldn't be found on *cls*. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. deprecated:: 17.1.0 + Use `attrs.evolve` instead if you can. This function will not be + removed du to the slightly different approach compared to + `attrs.evolve`, though. + """ + new = copy.copy(inst) + attrs = fields(inst.__class__) + for k, v in changes.items(): + a = getattr(attrs, k, NOTHING) + if a is NOTHING: + msg = f"{k} is not an attrs attribute on {new.__class__}." + raise AttrsAttributeNotFoundError(msg) + _OBJ_SETATTR(new, k, v) + return new + + +def evolve(*args, **changes): + """ + Create a new instance, based on the first positional argument with + *changes* applied. + + Args: + + inst: + Instance of a class with *attrs* attributes. *inst* must be passed + as a positional argument. + + changes: + Keyword changes in the new copy. + + Returns: + A copy of inst with *changes* incorporated. + + Raises: + TypeError: + If *attr_name* couldn't be found in the class ``__init__``. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 17.1.0 + .. deprecated:: 23.1.0 + It is now deprecated to pass the instance using the keyword argument + *inst*. It will raise a warning until at least April 2024, after which + it will become an error. Always pass the instance as a positional + argument. + .. versionchanged:: 24.1.0 + *inst* can't be passed as a keyword argument anymore. + """ + try: + (inst,) = args + except ValueError: + msg = ( + f"evolve() takes 1 positional argument, but {len(args)} were given" + ) + raise TypeError(msg) from None + + cls = inst.__class__ + attrs = fields(cls) + for a in attrs: + if not a.init: + continue + attr_name = a.name # To deal with private attributes. + init_name = a.alias + if init_name not in changes: + changes[init_name] = getattr(inst, attr_name) + + return cls(**changes) + + +def resolve_types( + cls, globalns=None, localns=None, attribs=None, include_extras=True +): + """ + Resolve any strings and forward annotations in type annotations. + + This is only required if you need concrete types in :class:`Attribute`'s + *type* field. In other words, you don't need to resolve your types if you + only use them for static type checking. + + With no arguments, names will be looked up in the module in which the class + was created. If this is not what you want, for example, if the name only + exists inside a method, you may pass *globalns* or *localns* to specify + other dictionaries in which to look up these names. See the docs of + `typing.get_type_hints` for more details. + + Args: + cls (type): Class to resolve. + + globalns (dict | None): Dictionary containing global variables. + + localns (dict | None): Dictionary containing local variables. + + attribs (list | None): + List of attribs for the given class. This is necessary when calling + from inside a ``field_transformer`` since *cls* is not an *attrs* + class yet. + + include_extras (bool): + Resolve more accurately, if possible. Pass ``include_extras`` to + ``typing.get_hints``, if supported by the typing module. On + supported Python versions (3.9+), this resolves the types more + accurately. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class and you didn't pass any attribs. + + NameError: If types cannot be resolved because of missing variables. + + Returns: + *cls* so you can use this function also as a class decorator. Please + note that you have to apply it **after** `attrs.define`. That means the + decorator has to come in the line **before** `attrs.define`. + + .. versionadded:: 20.1.0 + .. versionadded:: 21.1.0 *attribs* + .. versionadded:: 23.1.0 *include_extras* + """ + # Since calling get_type_hints is expensive we cache whether we've + # done it already. + if getattr(cls, "__attrs_types_resolved__", None) != cls: + import typing + + kwargs = {"globalns": globalns, "localns": localns} + + if PY_3_9_PLUS: + kwargs["include_extras"] = include_extras + + hints = typing.get_type_hints(cls, **kwargs) + for field in fields(cls) if attribs is None else attribs: + if field.name in hints: + # Since fields have been frozen we must work around it. + _OBJ_SETATTR(field, "type", hints[field.name]) + # We store the class we resolved so that subclasses know they haven't + # been resolved. + cls.__attrs_types_resolved__ = cls + + # Return the class so you can use it as a decorator too. + return cls diff --git a/env/Lib/site-packages/attr/_make.py b/env/Lib/site-packages/attr/_make.py new file mode 100644 index 0000000..bf00c5f --- /dev/null +++ b/env/Lib/site-packages/attr/_make.py @@ -0,0 +1,2960 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + +import abc +import contextlib +import copy +import enum +import functools +import inspect +import itertools +import linecache +import sys +import types +import typing + +from operator import itemgetter + +# We need to import _compat itself in addition to the _compat members to avoid +# having the thread-local in the globals here. +from . import _compat, _config, setters +from ._compat import ( + PY_3_8_PLUS, + PY_3_10_PLUS, + PY_3_11_PLUS, + _AnnotationExtractor, + _get_annotations, + get_generic_base, +) +from .exceptions import ( + DefaultAlreadySetError, + FrozenInstanceError, + NotAnAttrsClassError, + UnannotatedAttributeError, +) + + +# This is used at least twice, so cache it here. +_OBJ_SETATTR = object.__setattr__ +_INIT_FACTORY_PAT = "__attr_factory_%s" +_CLASSVAR_PREFIXES = ( + "typing.ClassVar", + "t.ClassVar", + "ClassVar", + "typing_extensions.ClassVar", +) +# we don't use a double-underscore prefix because that triggers +# name mangling when trying to create a slot for the field +# (when slots=True) +_HASH_CACHE_FIELD = "_attrs_cached_hash" + +_EMPTY_METADATA_SINGLETON = types.MappingProxyType({}) + +# Unique object for unequivocal getattr() defaults. +_SENTINEL = object() + +_DEFAULT_ON_SETATTR = setters.pipe(setters.convert, setters.validate) + + +class _Nothing(enum.Enum): + """ + Sentinel to indicate the lack of a value when `None` is ambiguous. + + If extending attrs, you can use ``typing.Literal[NOTHING]`` to show + that a value may be ``NOTHING``. + + .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False. + .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant. + """ + + NOTHING = enum.auto() + + def __repr__(self): + return "NOTHING" + + def __bool__(self): + return False + + +NOTHING = _Nothing.NOTHING +""" +Sentinel to indicate the lack of a value when `None` is ambiguous. +""" + + +class _CacheHashWrapper(int): + """ + An integer subclass that pickles / copies as None + + This is used for non-slots classes with ``cache_hash=True``, to avoid + serializing a potentially (even likely) invalid hash value. Since `None` + is the default value for uncalculated hashes, whenever this is copied, + the copy's value for the hash should automatically reset. + + See GH #613 for more details. + """ + + def __reduce__(self, _none_constructor=type(None), _args=()): # noqa: B008 + return _none_constructor, _args + + +def attrib( + default=NOTHING, + validator=None, + repr=True, + cmp=None, + hash=None, + init=True, + metadata=None, + type=None, + converter=None, + factory=None, + kw_only=False, + eq=None, + order=None, + on_setattr=None, + alias=None, +): + """ + Create a new field / attribute on a class. + + Identical to `attrs.field`, except it's not keyword-only. + + Consider using `attrs.field` in new code (``attr.ib`` will *never* go away, + though). + + .. warning:: + + Does **nothing** unless the class is also decorated with + `attr.s` (or similar)! + + + .. versionadded:: 15.2.0 *convert* + .. versionadded:: 16.3.0 *metadata* + .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. + .. versionchanged:: 17.1.0 + *hash* is `None` and therefore mirrors *eq* by default. + .. versionadded:: 17.3.0 *type* + .. deprecated:: 17.4.0 *convert* + .. versionadded:: 17.4.0 + *converter* as a replacement for the deprecated *convert* to achieve + consistency with other noun-based arguments. + .. versionadded:: 18.1.0 + ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``. + .. versionadded:: 18.2.0 *kw_only* + .. versionchanged:: 19.2.0 *convert* keyword argument removed. + .. versionchanged:: 19.2.0 *repr* also accepts a custom callable. + .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. + .. versionadded:: 19.2.0 *eq* and *order* + .. versionadded:: 20.1.0 *on_setattr* + .. versionchanged:: 20.3.0 *kw_only* backported to Python 2 + .. versionchanged:: 21.1.0 + *eq*, *order*, and *cmp* also accept a custom callable + .. versionchanged:: 21.1.0 *cmp* undeprecated + .. versionadded:: 22.2.0 *alias* + """ + eq, eq_key, order, order_key = _determine_attrib_eq_order( + cmp, eq, order, True + ) + + if hash is not None and hash is not True and hash is not False: + msg = "Invalid value for hash. Must be True, False, or None." + raise TypeError(msg) + + if factory is not None: + if default is not NOTHING: + msg = ( + "The `default` and `factory` arguments are mutually exclusive." + ) + raise ValueError(msg) + if not callable(factory): + msg = "The `factory` argument must be a callable." + raise ValueError(msg) + default = Factory(factory) + + if metadata is None: + metadata = {} + + # Apply syntactic sugar by auto-wrapping. + if isinstance(on_setattr, (list, tuple)): + on_setattr = setters.pipe(*on_setattr) + + if validator and isinstance(validator, (list, tuple)): + validator = and_(*validator) + + if converter and isinstance(converter, (list, tuple)): + converter = pipe(*converter) + + return _CountingAttr( + default=default, + validator=validator, + repr=repr, + cmp=None, + hash=hash, + init=init, + converter=converter, + metadata=metadata, + type=type, + kw_only=kw_only, + eq=eq, + eq_key=eq_key, + order=order, + order_key=order_key, + on_setattr=on_setattr, + alias=alias, + ) + + +def _compile_and_eval(script, globs, locs=None, filename=""): + """ + Evaluate the script with the given global (globs) and local (locs) + variables. + """ + bytecode = compile(script, filename, "exec") + eval(bytecode, globs, locs) + + +def _make_method(name, script, filename, globs, locals=None): + """ + Create the method with the script given and return the method object. + """ + locs = {} if locals is None else locals + + # In order of debuggers like PDB being able to step through the code, + # we add a fake linecache entry. + count = 1 + base_filename = filename + while True: + linecache_tuple = ( + len(script), + None, + script.splitlines(True), + filename, + ) + old_val = linecache.cache.setdefault(filename, linecache_tuple) + if old_val == linecache_tuple: + break + + filename = f"{base_filename[:-1]}-{count}>" + count += 1 + + _compile_and_eval(script, globs, locs, filename) + + return locs[name] + + +def _make_attr_tuple_class(cls_name, attr_names): + """ + Create a tuple subclass to hold `Attribute`s for an `attrs` class. + + The subclass is a bare tuple with properties for names. + + class MyClassAttributes(tuple): + __slots__ = () + x = property(itemgetter(0)) + """ + attr_class_name = f"{cls_name}Attributes" + attr_class_template = [ + f"class {attr_class_name}(tuple):", + " __slots__ = ()", + ] + if attr_names: + for i, attr_name in enumerate(attr_names): + attr_class_template.append( + f" {attr_name} = _attrs_property(_attrs_itemgetter({i}))" + ) + else: + attr_class_template.append(" pass") + globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property} + _compile_and_eval("\n".join(attr_class_template), globs) + return globs[attr_class_name] + + +# Tuple class for extracted attributes from a class definition. +# `base_attrs` is a subset of `attrs`. +_Attributes = _make_attr_tuple_class( + "_Attributes", + [ + # all attributes to build dunder methods for + "attrs", + # attributes that have been inherited + "base_attrs", + # map inherited attributes to their originating classes + "base_attrs_map", + ], +) + + +def _is_class_var(annot): + """ + Check whether *annot* is a typing.ClassVar. + + The string comparison hack is used to avoid evaluating all string + annotations which would put attrs-based classes at a performance + disadvantage compared to plain old classes. + """ + annot = str(annot) + + # Annotation can be quoted. + if annot.startswith(("'", '"')) and annot.endswith(("'", '"')): + annot = annot[1:-1] + + return annot.startswith(_CLASSVAR_PREFIXES) + + +def _has_own_attribute(cls, attrib_name): + """ + Check whether *cls* defines *attrib_name* (and doesn't just inherit it). + """ + return attrib_name in cls.__dict__ + + +def _collect_base_attrs(cls, taken_attr_names): + """ + Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. + """ + base_attrs = [] + base_attr_map = {} # A dictionary of base attrs to their classes. + + # Traverse the MRO and collect attributes. + for base_cls in reversed(cls.__mro__[1:-1]): + for a in getattr(base_cls, "__attrs_attrs__", []): + if a.inherited or a.name in taken_attr_names: + continue + + a = a.evolve(inherited=True) # noqa: PLW2901 + base_attrs.append(a) + base_attr_map[a.name] = base_cls + + # For each name, only keep the freshest definition i.e. the furthest at the + # back. base_attr_map is fine because it gets overwritten with every new + # instance. + filtered = [] + seen = set() + for a in reversed(base_attrs): + if a.name in seen: + continue + filtered.insert(0, a) + seen.add(a.name) + + return filtered, base_attr_map + + +def _collect_base_attrs_broken(cls, taken_attr_names): + """ + Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. + + N.B. *taken_attr_names* will be mutated. + + Adhere to the old incorrect behavior. + + Notably it collects from the front and considers inherited attributes which + leads to the buggy behavior reported in #428. + """ + base_attrs = [] + base_attr_map = {} # A dictionary of base attrs to their classes. + + # Traverse the MRO and collect attributes. + for base_cls in cls.__mro__[1:-1]: + for a in getattr(base_cls, "__attrs_attrs__", []): + if a.name in taken_attr_names: + continue + + a = a.evolve(inherited=True) # noqa: PLW2901 + taken_attr_names.add(a.name) + base_attrs.append(a) + base_attr_map[a.name] = base_cls + + return base_attrs, base_attr_map + + +def _transform_attrs( + cls, these, auto_attribs, kw_only, collect_by_mro, field_transformer +): + """ + Transform all `_CountingAttr`s on a class into `Attribute`s. + + If *these* is passed, use that and don't look for them on the class. + + If *collect_by_mro* is True, collect them in the correct MRO order, + otherwise use the old -- incorrect -- order. See #428. + + Return an `_Attributes`. + """ + cd = cls.__dict__ + anns = _get_annotations(cls) + + if these is not None: + ca_list = list(these.items()) + elif auto_attribs is True: + ca_names = { + name + for name, attr in cd.items() + if isinstance(attr, _CountingAttr) + } + ca_list = [] + annot_names = set() + for attr_name, type in anns.items(): + if _is_class_var(type): + continue + annot_names.add(attr_name) + a = cd.get(attr_name, NOTHING) + + if not isinstance(a, _CountingAttr): + a = attrib() if a is NOTHING else attrib(default=a) + ca_list.append((attr_name, a)) + + unannotated = ca_names - annot_names + if len(unannotated) > 0: + raise UnannotatedAttributeError( + "The following `attr.ib`s lack a type annotation: " + + ", ".join( + sorted(unannotated, key=lambda n: cd.get(n).counter) + ) + + "." + ) + else: + ca_list = sorted( + ( + (name, attr) + for name, attr in cd.items() + if isinstance(attr, _CountingAttr) + ), + key=lambda e: e[1].counter, + ) + + own_attrs = [ + Attribute.from_counting_attr( + name=attr_name, ca=ca, type=anns.get(attr_name) + ) + for attr_name, ca in ca_list + ] + + if collect_by_mro: + base_attrs, base_attr_map = _collect_base_attrs( + cls, {a.name for a in own_attrs} + ) + else: + base_attrs, base_attr_map = _collect_base_attrs_broken( + cls, {a.name for a in own_attrs} + ) + + if kw_only: + own_attrs = [a.evolve(kw_only=True) for a in own_attrs] + base_attrs = [a.evolve(kw_only=True) for a in base_attrs] + + attrs = base_attrs + own_attrs + + # Mandatory vs non-mandatory attr order only matters when they are part of + # the __init__ signature and when they aren't kw_only (which are moved to + # the end and can be mandatory or non-mandatory in any order, as they will + # be specified as keyword args anyway). Check the order of those attrs: + had_default = False + for a in (a for a in attrs if a.init is not False and a.kw_only is False): + if had_default is True and a.default is NOTHING: + msg = f"No mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: {a!r}" + raise ValueError(msg) + + if had_default is False and a.default is not NOTHING: + had_default = True + + if field_transformer is not None: + attrs = field_transformer(cls, attrs) + + # Resolve default field alias after executing field_transformer. + # This allows field_transformer to differentiate between explicit vs + # default aliases and supply their own defaults. + attrs = [ + a.evolve(alias=_default_init_alias_for(a.name)) if not a.alias else a + for a in attrs + ] + + # Create AttrsClass *after* applying the field_transformer since it may + # add or remove attributes! + attr_names = [a.name for a in attrs] + AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names) + + return _Attributes((AttrsClass(attrs), base_attrs, base_attr_map)) + + +def _make_cached_property_getattr(cached_properties, original_getattr, cls): + lines = [ + # Wrapped to get `__class__` into closure cell for super() + # (It will be replaced with the newly constructed class after construction). + "def wrapper(_cls):", + " __class__ = _cls", + " def __getattr__(self, item, cached_properties=cached_properties, original_getattr=original_getattr, _cached_setattr_get=_cached_setattr_get):", + " func = cached_properties.get(item)", + " if func is not None:", + " result = func(self)", + " _setter = _cached_setattr_get(self)", + " _setter(item, result)", + " return result", + ] + if original_getattr is not None: + lines.append( + " return original_getattr(self, item)", + ) + else: + lines.extend( + [ + " try:", + " return super().__getattribute__(item)", + " except AttributeError:", + " if not hasattr(super(), '__getattr__'):", + " raise", + " return super().__getattr__(item)", + " original_error = f\"'{self.__class__.__name__}' object has no attribute '{item}'\"", + " raise AttributeError(original_error)", + ] + ) + + lines.extend( + [ + " return __getattr__", + "__getattr__ = wrapper(_cls)", + ] + ) + + unique_filename = _generate_unique_filename(cls, "getattr") + + glob = { + "cached_properties": cached_properties, + "_cached_setattr_get": _OBJ_SETATTR.__get__, + "original_getattr": original_getattr, + } + + return _make_method( + "__getattr__", + "\n".join(lines), + unique_filename, + glob, + locals={ + "_cls": cls, + }, + ) + + +def _frozen_setattrs(self, name, value): + """ + Attached to frozen classes as __setattr__. + """ + if isinstance(self, BaseException) and name in ( + "__cause__", + "__context__", + "__traceback__", + ): + BaseException.__setattr__(self, name, value) + return + + raise FrozenInstanceError() + + +def _frozen_delattrs(self, name): + """ + Attached to frozen classes as __delattr__. + """ + raise FrozenInstanceError() + + +class _ClassBuilder: + """ + Iteratively build *one* class. + """ + + __slots__ = ( + "_attr_names", + "_attrs", + "_base_attr_map", + "_base_names", + "_cache_hash", + "_cls", + "_cls_dict", + "_delete_attribs", + "_frozen", + "_has_pre_init", + "_pre_init_has_args", + "_has_post_init", + "_is_exc", + "_on_setattr", + "_slots", + "_weakref_slot", + "_wrote_own_setattr", + "_has_custom_setattr", + ) + + def __init__( + self, + cls, + these, + slots, + frozen, + weakref_slot, + getstate_setstate, + auto_attribs, + kw_only, + cache_hash, + is_exc, + collect_by_mro, + on_setattr, + has_custom_setattr, + field_transformer, + ): + attrs, base_attrs, base_map = _transform_attrs( + cls, + these, + auto_attribs, + kw_only, + collect_by_mro, + field_transformer, + ) + + self._cls = cls + self._cls_dict = dict(cls.__dict__) if slots else {} + self._attrs = attrs + self._base_names = {a.name for a in base_attrs} + self._base_attr_map = base_map + self._attr_names = tuple(a.name for a in attrs) + self._slots = slots + self._frozen = frozen + self._weakref_slot = weakref_slot + self._cache_hash = cache_hash + self._has_pre_init = bool(getattr(cls, "__attrs_pre_init__", False)) + self._pre_init_has_args = False + if self._has_pre_init: + # Check if the pre init method has more arguments than just `self` + # We want to pass arguments if pre init expects arguments + pre_init_func = cls.__attrs_pre_init__ + pre_init_signature = inspect.signature(pre_init_func) + self._pre_init_has_args = len(pre_init_signature.parameters) > 1 + self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False)) + self._delete_attribs = not bool(these) + self._is_exc = is_exc + self._on_setattr = on_setattr + + self._has_custom_setattr = has_custom_setattr + self._wrote_own_setattr = False + + self._cls_dict["__attrs_attrs__"] = self._attrs + + if frozen: + self._cls_dict["__setattr__"] = _frozen_setattrs + self._cls_dict["__delattr__"] = _frozen_delattrs + + self._wrote_own_setattr = True + elif on_setattr in ( + _DEFAULT_ON_SETATTR, + setters.validate, + setters.convert, + ): + has_validator = has_converter = False + for a in attrs: + if a.validator is not None: + has_validator = True + if a.converter is not None: + has_converter = True + + if has_validator and has_converter: + break + if ( + ( + on_setattr == _DEFAULT_ON_SETATTR + and not (has_validator or has_converter) + ) + or (on_setattr == setters.validate and not has_validator) + or (on_setattr == setters.convert and not has_converter) + ): + # If class-level on_setattr is set to convert + validate, but + # there's no field to convert or validate, pretend like there's + # no on_setattr. + self._on_setattr = None + + if getstate_setstate: + ( + self._cls_dict["__getstate__"], + self._cls_dict["__setstate__"], + ) = self._make_getstate_setstate() + + def __repr__(self): + return f"<_ClassBuilder(cls={self._cls.__name__})>" + + def build_class(self): + """ + Finalize class based on the accumulated configuration. + + Builder cannot be used after calling this method. + """ + if self._slots is True: + cls = self._create_slots_class() + else: + cls = self._patch_original_class() + if PY_3_10_PLUS: + cls = abc.update_abstractmethods(cls) + + # The method gets only called if it's not inherited from a base class. + # _has_own_attribute does NOT work properly for classmethods. + if ( + getattr(cls, "__attrs_init_subclass__", None) + and "__attrs_init_subclass__" not in cls.__dict__ + ): + cls.__attrs_init_subclass__() + + return cls + + def _patch_original_class(self): + """ + Apply accumulated methods and return the class. + """ + cls = self._cls + base_names = self._base_names + + # Clean class of attribute definitions (`attr.ib()`s). + if self._delete_attribs: + for name in self._attr_names: + if ( + name not in base_names + and getattr(cls, name, _SENTINEL) is not _SENTINEL + ): + # An AttributeError can happen if a base class defines a + # class variable and we want to set an attribute with the + # same name by using only a type annotation. + with contextlib.suppress(AttributeError): + delattr(cls, name) + + # Attach our dunder methods. + for name, value in self._cls_dict.items(): + setattr(cls, name, value) + + # If we've inherited an attrs __setattr__ and don't write our own, + # reset it to object's. + if not self._wrote_own_setattr and getattr( + cls, "__attrs_own_setattr__", False + ): + cls.__attrs_own_setattr__ = False + + if not self._has_custom_setattr: + cls.__setattr__ = _OBJ_SETATTR + + return cls + + def _create_slots_class(self): + """ + Build and return a new class with a `__slots__` attribute. + """ + cd = { + k: v + for k, v in self._cls_dict.items() + if k not in (*tuple(self._attr_names), "__dict__", "__weakref__") + } + + # If our class doesn't have its own implementation of __setattr__ + # (either from the user or by us), check the bases, if one of them has + # an attrs-made __setattr__, that needs to be reset. We don't walk the + # MRO because we only care about our immediate base classes. + # XXX: This can be confused by subclassing a slotted attrs class with + # XXX: a non-attrs class and subclass the resulting class with an attrs + # XXX: class. See `test_slotted_confused` for details. For now that's + # XXX: OK with us. + if not self._wrote_own_setattr: + cd["__attrs_own_setattr__"] = False + + if not self._has_custom_setattr: + for base_cls in self._cls.__bases__: + if base_cls.__dict__.get("__attrs_own_setattr__", False): + cd["__setattr__"] = _OBJ_SETATTR + break + + # Traverse the MRO to collect existing slots + # and check for an existing __weakref__. + existing_slots = {} + weakref_inherited = False + for base_cls in self._cls.__mro__[1:-1]: + if base_cls.__dict__.get("__weakref__", None) is not None: + weakref_inherited = True + existing_slots.update( + { + name: getattr(base_cls, name) + for name in getattr(base_cls, "__slots__", []) + } + ) + + base_names = set(self._base_names) + + names = self._attr_names + if ( + self._weakref_slot + and "__weakref__" not in getattr(self._cls, "__slots__", ()) + and "__weakref__" not in names + and not weakref_inherited + ): + names += ("__weakref__",) + + if PY_3_8_PLUS: + cached_properties = { + name: cached_property.func + for name, cached_property in cd.items() + if isinstance(cached_property, functools.cached_property) + } + else: + # `functools.cached_property` was introduced in 3.8. + # So can't be used before this. + cached_properties = {} + + # Collect methods with a `__class__` reference that are shadowed in the new class. + # To know to update them. + additional_closure_functions_to_update = [] + if cached_properties: + class_annotations = _get_annotations(self._cls) + for name, func in cached_properties.items(): + # Add cached properties to names for slotting. + names += (name,) + # Clear out function from class to avoid clashing. + del cd[name] + additional_closure_functions_to_update.append(func) + annotation = inspect.signature(func).return_annotation + if annotation is not inspect.Parameter.empty: + class_annotations[name] = annotation + + original_getattr = cd.get("__getattr__") + if original_getattr is not None: + additional_closure_functions_to_update.append(original_getattr) + + cd["__getattr__"] = _make_cached_property_getattr( + cached_properties, original_getattr, self._cls + ) + + # We only add the names of attributes that aren't inherited. + # Setting __slots__ to inherited attributes wastes memory. + slot_names = [name for name in names if name not in base_names] + + # There are slots for attributes from current class + # that are defined in parent classes. + # As their descriptors may be overridden by a child class, + # we collect them here and update the class dict + reused_slots = { + slot: slot_descriptor + for slot, slot_descriptor in existing_slots.items() + if slot in slot_names + } + slot_names = [name for name in slot_names if name not in reused_slots] + cd.update(reused_slots) + if self._cache_hash: + slot_names.append(_HASH_CACHE_FIELD) + + cd["__slots__"] = tuple(slot_names) + + cd["__qualname__"] = self._cls.__qualname__ + + # Create new class based on old class and our methods. + cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd) + + # The following is a fix for + # . + # If a method mentions `__class__` or uses the no-arg super(), the + # compiler will bake a reference to the class in the method itself + # as `method.__closure__`. Since we replace the class with a + # clone, we rewrite these references so it keeps working. + for item in itertools.chain( + cls.__dict__.values(), additional_closure_functions_to_update + ): + if isinstance(item, (classmethod, staticmethod)): + # Class- and staticmethods hide their functions inside. + # These might need to be rewritten as well. + closure_cells = getattr(item.__func__, "__closure__", None) + elif isinstance(item, property): + # Workaround for property `super()` shortcut (PY3-only). + # There is no universal way for other descriptors. + closure_cells = getattr(item.fget, "__closure__", None) + else: + closure_cells = getattr(item, "__closure__", None) + + if not closure_cells: # Catch None or the empty list. + continue + for cell in closure_cells: + try: + match = cell.cell_contents is self._cls + except ValueError: # noqa: PERF203 + # ValueError: Cell is empty + pass + else: + if match: + cell.cell_contents = cls + return cls + + def add_repr(self, ns): + self._cls_dict["__repr__"] = self._add_method_dunders( + _make_repr(self._attrs, ns, self._cls) + ) + return self + + def add_str(self): + repr = self._cls_dict.get("__repr__") + if repr is None: + msg = "__str__ can only be generated if a __repr__ exists." + raise ValueError(msg) + + def __str__(self): + return self.__repr__() + + self._cls_dict["__str__"] = self._add_method_dunders(__str__) + return self + + def _make_getstate_setstate(self): + """ + Create custom __setstate__ and __getstate__ methods. + """ + # __weakref__ is not writable. + state_attr_names = tuple( + an for an in self._attr_names if an != "__weakref__" + ) + + def slots_getstate(self): + """ + Automatically created by attrs. + """ + return {name: getattr(self, name) for name in state_attr_names} + + hash_caching_enabled = self._cache_hash + + def slots_setstate(self, state): + """ + Automatically created by attrs. + """ + __bound_setattr = _OBJ_SETATTR.__get__(self) + if isinstance(state, tuple): + # Backward compatibility with attrs instances pickled with + # attrs versions before v22.2.0 which stored tuples. + for name, value in zip(state_attr_names, state): + __bound_setattr(name, value) + else: + for name in state_attr_names: + if name in state: + __bound_setattr(name, state[name]) + + # The hash code cache is not included when the object is + # serialized, but it still needs to be initialized to None to + # indicate that the first call to __hash__ should be a cache + # miss. + if hash_caching_enabled: + __bound_setattr(_HASH_CACHE_FIELD, None) + + return slots_getstate, slots_setstate + + def make_unhashable(self): + self._cls_dict["__hash__"] = None + return self + + def add_hash(self): + self._cls_dict["__hash__"] = self._add_method_dunders( + _make_hash( + self._cls, + self._attrs, + frozen=self._frozen, + cache_hash=self._cache_hash, + ) + ) + + return self + + def add_init(self): + self._cls_dict["__init__"] = self._add_method_dunders( + _make_init( + self._cls, + self._attrs, + self._has_pre_init, + self._pre_init_has_args, + self._has_post_init, + self._frozen, + self._slots, + self._cache_hash, + self._base_attr_map, + self._is_exc, + self._on_setattr, + attrs_init=False, + ) + ) + + return self + + def add_match_args(self): + self._cls_dict["__match_args__"] = tuple( + field.name + for field in self._attrs + if field.init and not field.kw_only + ) + + def add_attrs_init(self): + self._cls_dict["__attrs_init__"] = self._add_method_dunders( + _make_init( + self._cls, + self._attrs, + self._has_pre_init, + self._pre_init_has_args, + self._has_post_init, + self._frozen, + self._slots, + self._cache_hash, + self._base_attr_map, + self._is_exc, + self._on_setattr, + attrs_init=True, + ) + ) + + return self + + def add_eq(self): + cd = self._cls_dict + + cd["__eq__"] = self._add_method_dunders( + _make_eq(self._cls, self._attrs) + ) + cd["__ne__"] = self._add_method_dunders(_make_ne()) + + return self + + def add_order(self): + cd = self._cls_dict + + cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = ( + self._add_method_dunders(meth) + for meth in _make_order(self._cls, self._attrs) + ) + + return self + + def add_setattr(self): + if self._frozen: + return self + + sa_attrs = {} + for a in self._attrs: + on_setattr = a.on_setattr or self._on_setattr + if on_setattr and on_setattr is not setters.NO_OP: + sa_attrs[a.name] = a, on_setattr + + if not sa_attrs: + return self + + if self._has_custom_setattr: + # We need to write a __setattr__ but there already is one! + msg = "Can't combine custom __setattr__ with on_setattr hooks." + raise ValueError(msg) + + # docstring comes from _add_method_dunders + def __setattr__(self, name, val): + try: + a, hook = sa_attrs[name] + except KeyError: + nval = val + else: + nval = hook(self, a, val) + + _OBJ_SETATTR(self, name, nval) + + self._cls_dict["__attrs_own_setattr__"] = True + self._cls_dict["__setattr__"] = self._add_method_dunders(__setattr__) + self._wrote_own_setattr = True + + return self + + def _add_method_dunders(self, method): + """ + Add __module__ and __qualname__ to a *method* if possible. + """ + with contextlib.suppress(AttributeError): + method.__module__ = self._cls.__module__ + + with contextlib.suppress(AttributeError): + method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}" + + with contextlib.suppress(AttributeError): + method.__doc__ = ( + "Method generated by attrs for class " + f"{self._cls.__qualname__}." + ) + + return method + + +def _determine_attrs_eq_order(cmp, eq, order, default_eq): + """ + Validate the combination of *cmp*, *eq*, and *order*. Derive the effective + values of eq and order. If *eq* is None, set it to *default_eq*. + """ + if cmp is not None and any((eq is not None, order is not None)): + msg = "Don't mix `cmp` with `eq' and `order`." + raise ValueError(msg) + + # cmp takes precedence due to bw-compatibility. + if cmp is not None: + return cmp, cmp + + # If left None, equality is set to the specified default and ordering + # mirrors equality. + if eq is None: + eq = default_eq + + if order is None: + order = eq + + if eq is False and order is True: + msg = "`order` can only be True if `eq` is True too." + raise ValueError(msg) + + return eq, order + + +def _determine_attrib_eq_order(cmp, eq, order, default_eq): + """ + Validate the combination of *cmp*, *eq*, and *order*. Derive the effective + values of eq and order. If *eq* is None, set it to *default_eq*. + """ + if cmp is not None and any((eq is not None, order is not None)): + msg = "Don't mix `cmp` with `eq' and `order`." + raise ValueError(msg) + + def decide_callable_or_boolean(value): + """ + Decide whether a key function is used. + """ + if callable(value): + value, key = True, value + else: + key = None + return value, key + + # cmp takes precedence due to bw-compatibility. + if cmp is not None: + cmp, cmp_key = decide_callable_or_boolean(cmp) + return cmp, cmp_key, cmp, cmp_key + + # If left None, equality is set to the specified default and ordering + # mirrors equality. + if eq is None: + eq, eq_key = default_eq, None + else: + eq, eq_key = decide_callable_or_boolean(eq) + + if order is None: + order, order_key = eq, eq_key + else: + order, order_key = decide_callable_or_boolean(order) + + if eq is False and order is True: + msg = "`order` can only be True if `eq` is True too." + raise ValueError(msg) + + return eq, eq_key, order, order_key + + +def _determine_whether_to_implement( + cls, flag, auto_detect, dunders, default=True +): + """ + Check whether we should implement a set of methods for *cls*. + + *flag* is the argument passed into @attr.s like 'init', *auto_detect* the + same as passed into @attr.s and *dunders* is a tuple of attribute names + whose presence signal that the user has implemented it themselves. + + Return *default* if no reason for either for or against is found. + """ + if flag is True or flag is False: + return flag + + if flag is None and auto_detect is False: + return default + + # Logically, flag is None and auto_detect is True here. + for dunder in dunders: + if _has_own_attribute(cls, dunder): + return False + + return default + + +def attrs( + maybe_cls=None, + these=None, + repr_ns=None, + repr=None, + cmp=None, + hash=None, + init=None, + slots=False, + frozen=False, + weakref_slot=True, + str=False, + auto_attribs=False, + kw_only=False, + cache_hash=False, + auto_exc=False, + eq=None, + order=None, + auto_detect=False, + collect_by_mro=False, + getstate_setstate=None, + on_setattr=None, + field_transformer=None, + match_args=True, + unsafe_hash=None, +): + r""" + A class decorator that adds :term:`dunder methods` according to the + specified attributes using `attr.ib` or the *these* argument. + + Consider using `attrs.define` / `attrs.frozen` in new code (``attr.s`` will + *never* go away, though). + + Args: + repr_ns (str): + When using nested classes, there was no way in Python 2 to + automatically detect that. This argument allows to set a custom + name for a more meaningful ``repr`` output. This argument is + pointless in Python 3 and is therefore deprecated. + + .. caution:: + Refer to `attrs.define` for the rest of the parameters, but note that they + can have different defaults. + + Notably, leaving *on_setattr* as `None` will **not** add any hooks. + + .. versionadded:: 16.0.0 *slots* + .. versionadded:: 16.1.0 *frozen* + .. versionadded:: 16.3.0 *str* + .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``. + .. versionchanged:: 17.1.0 + *hash* supports `None` as value which is also the default now. + .. versionadded:: 17.3.0 *auto_attribs* + .. versionchanged:: 18.1.0 + If *these* is passed, no attributes are deleted from the class body. + .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained. + .. versionadded:: 18.2.0 *weakref_slot* + .. deprecated:: 18.2.0 + ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a + `DeprecationWarning` if the classes compared are subclasses of + each other. ``__eq`` and ``__ne__`` never tried to compared subclasses + to each other. + .. versionchanged:: 19.2.0 + ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider + subclasses comparable anymore. + .. versionadded:: 18.2.0 *kw_only* + .. versionadded:: 18.2.0 *cache_hash* + .. versionadded:: 19.1.0 *auto_exc* + .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. + .. versionadded:: 19.2.0 *eq* and *order* + .. versionadded:: 20.1.0 *auto_detect* + .. versionadded:: 20.1.0 *collect_by_mro* + .. versionadded:: 20.1.0 *getstate_setstate* + .. versionadded:: 20.1.0 *on_setattr* + .. versionadded:: 20.3.0 *field_transformer* + .. versionchanged:: 21.1.0 + ``init=False`` injects ``__attrs_init__`` + .. versionchanged:: 21.1.0 Support for ``__attrs_pre_init__`` + .. versionchanged:: 21.1.0 *cmp* undeprecated + .. versionadded:: 21.3.0 *match_args* + .. versionadded:: 22.2.0 + *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance). + .. deprecated:: 24.1.0 *repr_ns* + .. versionchanged:: 24.1.0 + Instances are not compared as tuples of attributes anymore, but using a + big ``and`` condition. This is faster and has more correct behavior for + uncomparable values like `math.nan`. + .. versionadded:: 24.1.0 + If a class has an *inherited* classmethod called + ``__attrs_init_subclass__``, it is executed after the class is created. + .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*. + """ + if repr_ns is not None: + import warnings + + warnings.warn( + DeprecationWarning( + "The `repr_ns` argument is deprecated and will be removed in or after August 2025." + ), + stacklevel=2, + ) + + eq_, order_ = _determine_attrs_eq_order(cmp, eq, order, None) + + # unsafe_hash takes precedence due to PEP 681. + if unsafe_hash is not None: + hash = unsafe_hash + + if isinstance(on_setattr, (list, tuple)): + on_setattr = setters.pipe(*on_setattr) + + def wrap(cls): + is_frozen = frozen or _has_frozen_base_class(cls) + is_exc = auto_exc is True and issubclass(cls, BaseException) + has_own_setattr = auto_detect and _has_own_attribute( + cls, "__setattr__" + ) + + if has_own_setattr and is_frozen: + msg = "Can't freeze a class with a custom __setattr__." + raise ValueError(msg) + + builder = _ClassBuilder( + cls, + these, + slots, + is_frozen, + weakref_slot, + _determine_whether_to_implement( + cls, + getstate_setstate, + auto_detect, + ("__getstate__", "__setstate__"), + default=slots, + ), + auto_attribs, + kw_only, + cache_hash, + is_exc, + collect_by_mro, + on_setattr, + has_own_setattr, + field_transformer, + ) + if _determine_whether_to_implement( + cls, repr, auto_detect, ("__repr__",) + ): + builder.add_repr(repr_ns) + if str is True: + builder.add_str() + + eq = _determine_whether_to_implement( + cls, eq_, auto_detect, ("__eq__", "__ne__") + ) + if not is_exc and eq is True: + builder.add_eq() + if not is_exc and _determine_whether_to_implement( + cls, order_, auto_detect, ("__lt__", "__le__", "__gt__", "__ge__") + ): + builder.add_order() + + builder.add_setattr() + + nonlocal hash + if ( + hash is None + and auto_detect is True + and _has_own_attribute(cls, "__hash__") + ): + hash = False + + if hash is not True and hash is not False and hash is not None: + # Can't use `hash in` because 1 == True for example. + msg = "Invalid value for hash. Must be True, False, or None." + raise TypeError(msg) + + if hash is False or (hash is None and eq is False) or is_exc: + # Don't do anything. Should fall back to __object__'s __hash__ + # which is by id. + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled." + raise TypeError(msg) + elif hash is True or ( + hash is None and eq is True and is_frozen is True + ): + # Build a __hash__ if told so, or if it's safe. + builder.add_hash() + else: + # Raise TypeError on attempts to hash. + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled." + raise TypeError(msg) + builder.make_unhashable() + + if _determine_whether_to_implement( + cls, init, auto_detect, ("__init__",) + ): + builder.add_init() + else: + builder.add_attrs_init() + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, init must be True." + raise TypeError(msg) + + if ( + PY_3_10_PLUS + and match_args + and not _has_own_attribute(cls, "__match_args__") + ): + builder.add_match_args() + + return builder.build_class() + + # maybe_cls's type depends on the usage of the decorator. It's a class + # if it's used as `@attrs` but `None` if used as `@attrs()`. + if maybe_cls is None: + return wrap + + return wrap(maybe_cls) + + +_attrs = attrs +""" +Internal alias so we can use it in functions that take an argument called +*attrs*. +""" + + +def _has_frozen_base_class(cls): + """ + Check whether *cls* has a frozen ancestor by looking at its + __setattr__. + """ + return cls.__setattr__ is _frozen_setattrs + + +def _generate_unique_filename(cls, func_name): + """ + Create a "filename" suitable for a function being generated. + """ + return ( + f"" + ) + + +def _make_hash(cls, attrs, frozen, cache_hash): + attrs = tuple( + a for a in attrs if a.hash is True or (a.hash is None and a.eq is True) + ) + + tab = " " + + unique_filename = _generate_unique_filename(cls, "hash") + type_hash = hash(unique_filename) + # If eq is custom generated, we need to include the functions in globs + globs = {} + + hash_def = "def __hash__(self" + hash_func = "hash((" + closing_braces = "))" + if not cache_hash: + hash_def += "):" + else: + hash_def += ", *" + + hash_def += ", _cache_wrapper=__import__('attr._make')._make._CacheHashWrapper):" + hash_func = "_cache_wrapper(" + hash_func + closing_braces += ")" + + method_lines = [hash_def] + + def append_hash_computation_lines(prefix, indent): + """ + Generate the code for actually computing the hash code. + Below this will either be returned directly or used to compute + a value which is then cached, depending on the value of cache_hash + """ + + method_lines.extend( + [ + indent + prefix + hash_func, + indent + f" {type_hash},", + ] + ) + + for a in attrs: + if a.eq_key: + cmp_name = f"_{a.name}_key" + globs[cmp_name] = a.eq_key + method_lines.append( + indent + f" {cmp_name}(self.{a.name})," + ) + else: + method_lines.append(indent + f" self.{a.name},") + + method_lines.append(indent + " " + closing_braces) + + if cache_hash: + method_lines.append(tab + f"if self.{_HASH_CACHE_FIELD} is None:") + if frozen: + append_hash_computation_lines( + f"object.__setattr__(self, '{_HASH_CACHE_FIELD}', ", tab * 2 + ) + method_lines.append(tab * 2 + ")") # close __setattr__ + else: + append_hash_computation_lines( + f"self.{_HASH_CACHE_FIELD} = ", tab * 2 + ) + method_lines.append(tab + f"return self.{_HASH_CACHE_FIELD}") + else: + append_hash_computation_lines("return ", tab) + + script = "\n".join(method_lines) + return _make_method("__hash__", script, unique_filename, globs) + + +def _add_hash(cls, attrs): + """ + Add a hash method to *cls*. + """ + cls.__hash__ = _make_hash(cls, attrs, frozen=False, cache_hash=False) + return cls + + +def _make_ne(): + """ + Create __ne__ method. + """ + + def __ne__(self, other): + """ + Check equality and either forward a NotImplemented or + return the result negated. + """ + result = self.__eq__(other) + if result is NotImplemented: + return NotImplemented + + return not result + + return __ne__ + + +def _make_eq(cls, attrs): + """ + Create __eq__ method for *cls* with *attrs*. + """ + attrs = [a for a in attrs if a.eq] + + unique_filename = _generate_unique_filename(cls, "eq") + lines = [ + "def __eq__(self, other):", + " if other.__class__ is not self.__class__:", + " return NotImplemented", + ] + + # We can't just do a big self.x = other.x and... clause due to + # irregularities like nan == nan is false but (nan,) == (nan,) is true. + globs = {} + if attrs: + lines.append(" return (") + for a in attrs: + if a.eq_key: + cmp_name = f"_{a.name}_key" + # Add the key function to the global namespace + # of the evaluated function. + globs[cmp_name] = a.eq_key + lines.append( + f" {cmp_name}(self.{a.name}) == {cmp_name}(other.{a.name})" + ) + else: + lines.append(f" self.{a.name} == other.{a.name}") + if a is not attrs[-1]: + lines[-1] = f"{lines[-1]} and" + lines.append(" )") + else: + lines.append(" return True") + + script = "\n".join(lines) + + return _make_method("__eq__", script, unique_filename, globs) + + +def _make_order(cls, attrs): + """ + Create ordering methods for *cls* with *attrs*. + """ + attrs = [a for a in attrs if a.order] + + def attrs_to_tuple(obj): + """ + Save us some typing. + """ + return tuple( + key(value) if key else value + for value, key in ( + (getattr(obj, a.name), a.order_key) for a in attrs + ) + ) + + def __lt__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) < attrs_to_tuple(other) + + return NotImplemented + + def __le__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) <= attrs_to_tuple(other) + + return NotImplemented + + def __gt__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) > attrs_to_tuple(other) + + return NotImplemented + + def __ge__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) >= attrs_to_tuple(other) + + return NotImplemented + + return __lt__, __le__, __gt__, __ge__ + + +def _add_eq(cls, attrs=None): + """ + Add equality methods to *cls* with *attrs*. + """ + if attrs is None: + attrs = cls.__attrs_attrs__ + + cls.__eq__ = _make_eq(cls, attrs) + cls.__ne__ = _make_ne() + + return cls + + +def _make_repr(attrs, ns, cls): + unique_filename = _generate_unique_filename(cls, "repr") + # Figure out which attributes to include, and which function to use to + # format them. The a.repr value can be either bool or a custom + # callable. + attr_names_with_reprs = tuple( + (a.name, (repr if a.repr is True else a.repr), a.init) + for a in attrs + if a.repr is not False + ) + globs = { + name + "_repr": r for name, r, _ in attr_names_with_reprs if r != repr + } + globs["_compat"] = _compat + globs["AttributeError"] = AttributeError + globs["NOTHING"] = NOTHING + attribute_fragments = [] + for name, r, i in attr_names_with_reprs: + accessor = ( + "self." + name if i else 'getattr(self, "' + name + '", NOTHING)' + ) + fragment = ( + "%s={%s!r}" % (name, accessor) + if r == repr + else "%s={%s_repr(%s)}" % (name, name, accessor) + ) + attribute_fragments.append(fragment) + repr_fragment = ", ".join(attribute_fragments) + + if ns is None: + cls_name_fragment = '{self.__class__.__qualname__.rsplit(">.", 1)[-1]}' + else: + cls_name_fragment = ns + ".{self.__class__.__name__}" + + lines = [ + "def __repr__(self):", + " try:", + " already_repring = _compat.repr_context.already_repring", + " except AttributeError:", + " already_repring = {id(self),}", + " _compat.repr_context.already_repring = already_repring", + " else:", + " if id(self) in already_repring:", + " return '...'", + " else:", + " already_repring.add(id(self))", + " try:", + f" return f'{cls_name_fragment}({repr_fragment})'", + " finally:", + " already_repring.remove(id(self))", + ] + + return _make_method( + "__repr__", "\n".join(lines), unique_filename, globs=globs + ) + + +def _add_repr(cls, ns=None, attrs=None): + """ + Add a repr method to *cls*. + """ + if attrs is None: + attrs = cls.__attrs_attrs__ + + cls.__repr__ = _make_repr(attrs, ns, cls) + return cls + + +def fields(cls): + """ + Return the tuple of *attrs* attributes for a class. + + The tuple also allows accessing the fields by their names (see below for + examples). + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + Returns: + tuple (with name accessors) of `attrs.Attribute` + + .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields + by name. + .. versionchanged:: 23.1.0 Add support for generic classes. + """ + generic_base = get_generic_base(cls) + + if generic_base is None and not isinstance(cls, type): + msg = "Passed object must be a class." + raise TypeError(msg) + + attrs = getattr(cls, "__attrs_attrs__", None) + + if attrs is None: + if generic_base is not None: + attrs = getattr(generic_base, "__attrs_attrs__", None) + if attrs is not None: + # Even though this is global state, stick it on here to speed + # it up. We rely on `cls` being cached for this to be + # efficient. + cls.__attrs_attrs__ = attrs + return attrs + msg = f"{cls!r} is not an attrs-decorated class." + raise NotAnAttrsClassError(msg) + + return attrs + + +def fields_dict(cls): + """ + Return an ordered dictionary of *attrs* attributes for a class, whose keys + are the attribute names. + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + Returns: + dict[str, attrs.Attribute]: Dict of attribute name to definition + + .. versionadded:: 18.1.0 + """ + if not isinstance(cls, type): + msg = "Passed object must be a class." + raise TypeError(msg) + attrs = getattr(cls, "__attrs_attrs__", None) + if attrs is None: + msg = f"{cls!r} is not an attrs-decorated class." + raise NotAnAttrsClassError(msg) + return {a.name: a for a in attrs} + + +def validate(inst): + """ + Validate all attributes on *inst* that have a validator. + + Leaves all exceptions through. + + Args: + inst: Instance of a class with *attrs* attributes. + """ + if _config._run_validators is False: + return + + for a in fields(inst.__class__): + v = a.validator + if v is not None: + v(inst, a, getattr(inst, a.name)) + + +def _is_slot_attr(a_name, base_attr_map): + """ + Check if the attribute name comes from a slot class. + """ + cls = base_attr_map.get(a_name) + return cls and "__slots__" in cls.__dict__ + + +def _make_init( + cls, + attrs, + pre_init, + pre_init_has_args, + post_init, + frozen, + slots, + cache_hash, + base_attr_map, + is_exc, + cls_on_setattr, + attrs_init, +): + has_cls_on_setattr = ( + cls_on_setattr is not None and cls_on_setattr is not setters.NO_OP + ) + + if frozen and has_cls_on_setattr: + msg = "Frozen classes can't use on_setattr." + raise ValueError(msg) + + needs_cached_setattr = cache_hash or frozen + filtered_attrs = [] + attr_dict = {} + for a in attrs: + if not a.init and a.default is NOTHING: + continue + + filtered_attrs.append(a) + attr_dict[a.name] = a + + if a.on_setattr is not None: + if frozen is True: + msg = "Frozen classes can't use on_setattr." + raise ValueError(msg) + + needs_cached_setattr = True + elif has_cls_on_setattr and a.on_setattr is not setters.NO_OP: + needs_cached_setattr = True + + unique_filename = _generate_unique_filename(cls, "init") + + script, globs, annotations = _attrs_to_init_script( + filtered_attrs, + frozen, + slots, + pre_init, + pre_init_has_args, + post_init, + cache_hash, + base_attr_map, + is_exc, + needs_cached_setattr, + has_cls_on_setattr, + "__attrs_init__" if attrs_init else "__init__", + ) + if cls.__module__ in sys.modules: + # This makes typing.get_type_hints(CLS.__init__) resolve string types. + globs.update(sys.modules[cls.__module__].__dict__) + + globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict}) + + if needs_cached_setattr: + # Save the lookup overhead in __init__ if we need to circumvent + # setattr hooks. + globs["_cached_setattr_get"] = _OBJ_SETATTR.__get__ + + init = _make_method( + "__attrs_init__" if attrs_init else "__init__", + script, + unique_filename, + globs, + ) + init.__annotations__ = annotations + + return init + + +def _setattr(attr_name: str, value_var: str, has_on_setattr: bool) -> str: + """ + Use the cached object.setattr to set *attr_name* to *value_var*. + """ + return f"_setattr('{attr_name}', {value_var})" + + +def _setattr_with_converter( + attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter +) -> str: + """ + Use the cached object.setattr to set *attr_name* to *value_var*, but run + its converter first. + """ + return f"_setattr('{attr_name}', {converter._fmt_converter_call(attr_name, value_var)})" + + +def _assign(attr_name: str, value: str, has_on_setattr: bool) -> str: + """ + Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise + relegate to _setattr. + """ + if has_on_setattr: + return _setattr(attr_name, value, True) + + return f"self.{attr_name} = {value}" + + +def _assign_with_converter( + attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter +) -> str: + """ + Unless *attr_name* has an on_setattr hook, use normal assignment after + conversion. Otherwise relegate to _setattr_with_converter. + """ + if has_on_setattr: + return _setattr_with_converter(attr_name, value_var, True, converter) + + return f"self.{attr_name} = {converter._fmt_converter_call(attr_name, value_var)}" + + +def _determine_setters( + frozen: bool, slots: bool, base_attr_map: dict[str, type] +): + """ + Determine the correct setter functions based on whether a class is frozen + and/or slotted. + """ + if frozen is True: + if slots is True: + return (), _setattr, _setattr_with_converter + + # Dict frozen classes assign directly to __dict__. + # But only if the attribute doesn't come from an ancestor slot + # class. + # Note _inst_dict will be used again below if cache_hash is True + + def fmt_setter( + attr_name: str, value_var: str, has_on_setattr: bool + ) -> str: + if _is_slot_attr(attr_name, base_attr_map): + return _setattr(attr_name, value_var, has_on_setattr) + + return f"_inst_dict['{attr_name}'] = {value_var}" + + def fmt_setter_with_converter( + attr_name: str, + value_var: str, + has_on_setattr: bool, + converter: Converter, + ) -> str: + if has_on_setattr or _is_slot_attr(attr_name, base_attr_map): + return _setattr_with_converter( + attr_name, value_var, has_on_setattr, converter + ) + + return f"_inst_dict['{attr_name}'] = {converter._fmt_converter_call(attr_name, value_var)}" + + return ( + ("_inst_dict = self.__dict__",), + fmt_setter, + fmt_setter_with_converter, + ) + + # Not frozen -- we can just assign directly. + return (), _assign, _assign_with_converter + + +def _attrs_to_init_script( + attrs: list[Attribute], + is_frozen: bool, + is_slotted: bool, + call_pre_init: bool, + pre_init_has_args: bool, + call_post_init: bool, + does_cache_hash: bool, + base_attr_map: dict[str, type], + is_exc: bool, + needs_cached_setattr: bool, + has_cls_on_setattr: bool, + method_name: str, +) -> tuple[str, dict, dict]: + """ + Return a script of an initializer for *attrs*, a dict of globals, and + annotations for the initializer. + + The globals are required by the generated script. + """ + lines = ["self.__attrs_pre_init__()"] if call_pre_init else [] + + if needs_cached_setattr: + lines.append( + # Circumvent the __setattr__ descriptor to save one lookup per + # assignment. Note _setattr will be used again below if + # does_cache_hash is True. + "_setattr = _cached_setattr_get(self)" + ) + + extra_lines, fmt_setter, fmt_setter_with_converter = _determine_setters( + is_frozen, is_slotted, base_attr_map + ) + lines.extend(extra_lines) + + args = [] + kw_only_args = [] + attrs_to_validate = [] + + # This is a dictionary of names to validator and converter callables. + # Injecting this into __init__ globals lets us avoid lookups. + names_for_globals = {} + annotations = {"return": None} + + for a in attrs: + if a.validator: + attrs_to_validate.append(a) + + attr_name = a.name + has_on_setattr = a.on_setattr is not None or ( + a.on_setattr is not setters.NO_OP and has_cls_on_setattr + ) + # a.alias is set to maybe-mangled attr_name in _ClassBuilder if not + # explicitly provided + arg_name = a.alias + + has_factory = isinstance(a.default, Factory) + maybe_self = "self" if has_factory and a.default.takes_self else "" + + if a.converter and not isinstance(a.converter, Converter): + converter = Converter(a.converter) + else: + converter = a.converter + + if a.init is False: + if has_factory: + init_factory_name = _INIT_FACTORY_PAT % (a.name,) + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, + init_factory_name + f"({maybe_self})", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + fmt_setter( + attr_name, + init_factory_name + f"({maybe_self})", + has_on_setattr, + ) + ) + names_for_globals[init_factory_name] = a.default.factory + elif converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, + f"attr_dict['{attr_name}'].default", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + fmt_setter( + attr_name, + f"attr_dict['{attr_name}'].default", + has_on_setattr, + ) + ) + elif a.default is not NOTHING and not has_factory: + arg = f"{arg_name}=attr_dict['{attr_name}'].default" + if a.kw_only: + kw_only_args.append(arg) + else: + args.append(arg) + + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) + + elif has_factory: + arg = f"{arg_name}=NOTHING" + if a.kw_only: + kw_only_args.append(arg) + else: + args.append(arg) + lines.append(f"if {arg_name} is not NOTHING:") + + init_factory_name = _INIT_FACTORY_PAT % (a.name,) + if converter is not None: + lines.append( + " " + + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + lines.append("else:") + lines.append( + " " + + fmt_setter_with_converter( + attr_name, + init_factory_name + "(" + maybe_self + ")", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + " " + fmt_setter(attr_name, arg_name, has_on_setattr) + ) + lines.append("else:") + lines.append( + " " + + fmt_setter( + attr_name, + init_factory_name + "(" + maybe_self + ")", + has_on_setattr, + ) + ) + names_for_globals[init_factory_name] = a.default.factory + else: + if a.kw_only: + kw_only_args.append(arg_name) + else: + args.append(arg_name) + + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) + + if a.init is True: + if a.type is not None and converter is None: + annotations[arg_name] = a.type + elif converter is not None and converter._first_param_type: + # Use the type from the converter if present. + annotations[arg_name] = converter._first_param_type + + if attrs_to_validate: # we can skip this if there are no validators. + names_for_globals["_config"] = _config + lines.append("if _config._run_validators is True:") + for a in attrs_to_validate: + val_name = "__attr_validator_" + a.name + attr_name = "__attr_" + a.name + lines.append(f" {val_name}(self, {attr_name}, self.{a.name})") + names_for_globals[val_name] = a.validator + names_for_globals[attr_name] = a + + if call_post_init: + lines.append("self.__attrs_post_init__()") + + # Because this is set only after __attrs_post_init__ is called, a crash + # will result if post-init tries to access the hash code. This seemed + # preferable to setting this beforehand, in which case alteration to field + # values during post-init combined with post-init accessing the hash code + # would result in silent bugs. + if does_cache_hash: + if is_frozen: + if is_slotted: + init_hash_cache = f"_setattr('{_HASH_CACHE_FIELD}', None)" + else: + init_hash_cache = f"_inst_dict['{_HASH_CACHE_FIELD}'] = None" + else: + init_hash_cache = f"self.{_HASH_CACHE_FIELD} = None" + lines.append(init_hash_cache) + + # For exceptions we rely on BaseException.__init__ for proper + # initialization. + if is_exc: + vals = ",".join(f"self.{a.name}" for a in attrs if a.init) + + lines.append(f"BaseException.__init__(self, {vals})") + + args = ", ".join(args) + pre_init_args = args + if kw_only_args: + # leading comma & kw_only args + args += f"{', ' if args else ''}*, {', '.join(kw_only_args)}" + pre_init_kw_only_args = ", ".join( + [ + f"{kw_arg_name}={kw_arg_name}" + # We need to remove the defaults from the kw_only_args. + for kw_arg_name in (kwa.split("=")[0] for kwa in kw_only_args) + ] + ) + pre_init_args += ", " if pre_init_args else "" + pre_init_args += pre_init_kw_only_args + + if call_pre_init and pre_init_has_args: + # If pre init method has arguments, pass same arguments as `__init__`. + lines[0] = f"self.__attrs_pre_init__({pre_init_args})" + + # Python 3.7 doesn't allow backslashes in f strings. + NL = "\n " + return ( + f"""def {method_name}(self, {args}): + {NL.join(lines) if lines else 'pass'} +""", + names_for_globals, + annotations, + ) + + +def _default_init_alias_for(name: str) -> str: + """ + The default __init__ parameter name for a field. + + This performs private-name adjustment via leading-unscore stripping, + and is the default value of Attribute.alias if not provided. + """ + + return name.lstrip("_") + + +class Attribute: + """ + *Read-only* representation of an attribute. + + .. warning:: + + You should never instantiate this class yourself. + + The class has *all* arguments of `attr.ib` (except for ``factory`` which is + only syntactic sugar for ``default=Factory(...)`` plus the following: + + - ``name`` (`str`): The name of the attribute. + - ``alias`` (`str`): The __init__ parameter name of the attribute, after + any explicit overrides and default private-attribute-name handling. + - ``inherited`` (`bool`): Whether or not that attribute has been inherited + from a base class. + - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The + callables that are used for comparing and ordering objects by this + attribute, respectively. These are set by passing a callable to + `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also + :ref:`comparison customization `. + + Instances of this class are frequently used for introspection purposes + like: + + - `fields` returns a tuple of them. + - Validators get them passed as the first argument. + - The :ref:`field transformer ` hook receives a list of + them. + - The ``alias`` property exposes the __init__ parameter name of the field, + with any overrides and default private-attribute handling applied. + + + .. versionadded:: 20.1.0 *inherited* + .. versionadded:: 20.1.0 *on_setattr* + .. versionchanged:: 20.2.0 *inherited* is not taken into account for + equality checks and hashing anymore. + .. versionadded:: 21.1.0 *eq_key* and *order_key* + .. versionadded:: 22.2.0 *alias* + + For the full version history of the fields, see `attr.ib`. + """ + + __slots__ = ( + "name", + "default", + "validator", + "repr", + "eq", + "eq_key", + "order", + "order_key", + "hash", + "init", + "metadata", + "type", + "converter", + "kw_only", + "inherited", + "on_setattr", + "alias", + ) + + def __init__( + self, + name, + default, + validator, + repr, + cmp, # XXX: unused, remove along with other cmp code. + hash, + init, + inherited, + metadata=None, + type=None, + converter=None, + kw_only=False, + eq=None, + eq_key=None, + order=None, + order_key=None, + on_setattr=None, + alias=None, + ): + eq, eq_key, order, order_key = _determine_attrib_eq_order( + cmp, eq_key or eq, order_key or order, True + ) + + # Cache this descriptor here to speed things up later. + bound_setattr = _OBJ_SETATTR.__get__(self) + + # Despite the big red warning, people *do* instantiate `Attribute` + # themselves. + bound_setattr("name", name) + bound_setattr("default", default) + bound_setattr("validator", validator) + bound_setattr("repr", repr) + bound_setattr("eq", eq) + bound_setattr("eq_key", eq_key) + bound_setattr("order", order) + bound_setattr("order_key", order_key) + bound_setattr("hash", hash) + bound_setattr("init", init) + bound_setattr("converter", converter) + bound_setattr( + "metadata", + ( + types.MappingProxyType(dict(metadata)) # Shallow copy + if metadata + else _EMPTY_METADATA_SINGLETON + ), + ) + bound_setattr("type", type) + bound_setattr("kw_only", kw_only) + bound_setattr("inherited", inherited) + bound_setattr("on_setattr", on_setattr) + bound_setattr("alias", alias) + + def __setattr__(self, name, value): + raise FrozenInstanceError() + + @classmethod + def from_counting_attr(cls, name, ca, type=None): + # type holds the annotated value. deal with conflicts: + if type is None: + type = ca.type + elif ca.type is not None: + msg = "Type annotation and type argument cannot both be present" + raise ValueError(msg) + inst_dict = { + k: getattr(ca, k) + for k in Attribute.__slots__ + if k + not in ( + "name", + "validator", + "default", + "type", + "inherited", + ) # exclude methods and deprecated alias + } + return cls( + name=name, + validator=ca._validator, + default=ca._default, + type=type, + cmp=None, + inherited=False, + **inst_dict, + ) + + # Don't use attrs.evolve since fields(Attribute) doesn't work + def evolve(self, **changes): + """ + Copy *self* and apply *changes*. + + This works similarly to `attrs.evolve` but that function does not work + with {class}`Attribute`. + + It is mainly meant to be used for `transform-fields`. + + .. versionadded:: 20.3.0 + """ + new = copy.copy(self) + + new._setattrs(changes.items()) + + return new + + # Don't use _add_pickle since fields(Attribute) doesn't work + def __getstate__(self): + """ + Play nice with pickle. + """ + return tuple( + getattr(self, name) if name != "metadata" else dict(self.metadata) + for name in self.__slots__ + ) + + def __setstate__(self, state): + """ + Play nice with pickle. + """ + self._setattrs(zip(self.__slots__, state)) + + def _setattrs(self, name_values_pairs): + bound_setattr = _OBJ_SETATTR.__get__(self) + for name, value in name_values_pairs: + if name != "metadata": + bound_setattr(name, value) + else: + bound_setattr( + name, + ( + types.MappingProxyType(dict(value)) + if value + else _EMPTY_METADATA_SINGLETON + ), + ) + + +_a = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=(name != "metadata"), + init=True, + inherited=False, + alias=_default_init_alias_for(name), + ) + for name in Attribute.__slots__ +] + +Attribute = _add_hash( + _add_eq( + _add_repr(Attribute, attrs=_a), + attrs=[a for a in _a if a.name != "inherited"], + ), + attrs=[a for a in _a if a.hash and a.name != "inherited"], +) + + +class _CountingAttr: + """ + Intermediate representation of attributes that uses a counter to preserve + the order in which the attributes have been defined. + + *Internal* data structure of the attrs library. Running into is most + likely the result of a bug like a forgotten `@attr.s` decorator. + """ + + __slots__ = ( + "counter", + "_default", + "repr", + "eq", + "eq_key", + "order", + "order_key", + "hash", + "init", + "metadata", + "_validator", + "converter", + "type", + "kw_only", + "on_setattr", + "alias", + ) + __attrs_attrs__ = ( + *tuple( + Attribute( + name=name, + alias=_default_init_alias_for(name), + default=NOTHING, + validator=None, + repr=True, + cmp=None, + hash=True, + init=True, + kw_only=False, + eq=True, + eq_key=None, + order=False, + order_key=None, + inherited=False, + on_setattr=None, + ) + for name in ( + "counter", + "_default", + "repr", + "eq", + "order", + "hash", + "init", + "on_setattr", + "alias", + ) + ), + Attribute( + name="metadata", + alias="metadata", + default=None, + validator=None, + repr=True, + cmp=None, + hash=False, + init=True, + kw_only=False, + eq=True, + eq_key=None, + order=False, + order_key=None, + inherited=False, + on_setattr=None, + ), + ) + cls_counter = 0 + + def __init__( + self, + default, + validator, + repr, + cmp, + hash, + init, + converter, + metadata, + type, + kw_only, + eq, + eq_key, + order, + order_key, + on_setattr, + alias, + ): + _CountingAttr.cls_counter += 1 + self.counter = _CountingAttr.cls_counter + self._default = default + self._validator = validator + self.converter = converter + self.repr = repr + self.eq = eq + self.eq_key = eq_key + self.order = order + self.order_key = order_key + self.hash = hash + self.init = init + self.metadata = metadata + self.type = type + self.kw_only = kw_only + self.on_setattr = on_setattr + self.alias = alias + + def validator(self, meth): + """ + Decorator that adds *meth* to the list of validators. + + Returns *meth* unchanged. + + .. versionadded:: 17.1.0 + """ + if self._validator is None: + self._validator = meth + else: + self._validator = and_(self._validator, meth) + return meth + + def default(self, meth): + """ + Decorator that allows to set the default for an attribute. + + Returns *meth* unchanged. + + Raises: + DefaultAlreadySetError: If default has been set before. + + .. versionadded:: 17.1.0 + """ + if self._default is not NOTHING: + raise DefaultAlreadySetError() + + self._default = Factory(meth, takes_self=True) + + return meth + + +_CountingAttr = _add_eq(_add_repr(_CountingAttr)) + + +class Factory: + """ + Stores a factory callable. + + If passed as the default value to `attrs.field`, the factory is used to + generate a new value. + + Args: + factory (typing.Callable): + A callable that takes either none or exactly one mandatory + positional argument depending on *takes_self*. + + takes_self (bool): + Pass the partially initialized instance that is being initialized + as a positional argument. + + .. versionadded:: 17.1.0 *takes_self* + """ + + __slots__ = ("factory", "takes_self") + + def __init__(self, factory, takes_self=False): + self.factory = factory + self.takes_self = takes_self + + def __getstate__(self): + """ + Play nice with pickle. + """ + return tuple(getattr(self, name) for name in self.__slots__) + + def __setstate__(self, state): + """ + Play nice with pickle. + """ + for name, value in zip(self.__slots__, state): + setattr(self, name, value) + + +_f = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=True, + init=True, + inherited=False, + ) + for name in Factory.__slots__ +] + +Factory = _add_hash(_add_eq(_add_repr(Factory, attrs=_f), attrs=_f), attrs=_f) + + +class Converter: + """ + Stores a converter callable. + + Allows for the wrapped converter to take additional arguments. The + arguments are passed in the order they are documented. + + Args: + converter (Callable): A callable that converts the passed value. + + takes_self (bool): + Pass the partially initialized instance that is being initialized + as a positional argument. (default: `False`) + + takes_field (bool): + Pass the field definition (an :class:`Attribute`) into the + converter as a positional argument. (default: `False`) + + .. versionadded:: 24.1.0 + """ + + __slots__ = ( + "converter", + "takes_self", + "takes_field", + "_first_param_type", + "_global_name", + "__call__", + ) + + def __init__(self, converter, *, takes_self=False, takes_field=False): + self.converter = converter + self.takes_self = takes_self + self.takes_field = takes_field + + ex = _AnnotationExtractor(converter) + self._first_param_type = ex.get_first_param_type() + + if not (self.takes_self or self.takes_field): + self.__call__ = lambda value, _, __: self.converter(value) + elif self.takes_self and not self.takes_field: + self.__call__ = lambda value, instance, __: self.converter( + value, instance + ) + elif not self.takes_self and self.takes_field: + self.__call__ = lambda value, __, field: self.converter( + value, field + ) + else: + self.__call__ = lambda value, instance, field: self.converter( + value, instance, field + ) + + rt = ex.get_return_type() + if rt is not None: + self.__call__.__annotations__["return"] = rt + + @staticmethod + def _get_global_name(attr_name: str) -> str: + """ + Return the name that a converter for an attribute name *attr_name* + would have. + """ + return f"__attr_converter_{attr_name}" + + def _fmt_converter_call(self, attr_name: str, value_var: str) -> str: + """ + Return a string that calls the converter for an attribute name + *attr_name* and the value in variable named *value_var* according to + `self.takes_self` and `self.takes_field`. + """ + if not (self.takes_self or self.takes_field): + return f"{self._get_global_name(attr_name)}({value_var})" + + if self.takes_self and self.takes_field: + return f"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])" + + if self.takes_self: + return f"{self._get_global_name(attr_name)}({value_var}, self)" + + return f"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])" + + def __getstate__(self): + """ + Return a dict containing only converter and takes_self -- the rest gets + computed when loading. + """ + return { + "converter": self.converter, + "takes_self": self.takes_self, + "takes_field": self.takes_field, + } + + def __setstate__(self, state): + """ + Load instance from state. + """ + self.__init__(**state) + + +_f = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=True, + init=True, + inherited=False, + ) + for name in ("converter", "takes_self", "takes_field") +] + +Converter = _add_hash( + _add_eq(_add_repr(Converter, attrs=_f), attrs=_f), attrs=_f +) + + +def make_class( + name, attrs, bases=(object,), class_body=None, **attributes_arguments +): + r""" + A quick way to create a new class called *name* with *attrs*. + + Args: + name (str): The name for the new class. + + attrs( list | dict): + A list of names or a dictionary of mappings of names to `attr.ib`\ + s / `attrs.field`\ s. + + The order is deduced from the order of the names or attributes + inside *attrs*. Otherwise the order of the definition of the + attributes is used. + + bases (tuple[type, ...]): Classes that the new class will subclass. + + class_body (dict): + An optional dictionary of class attributes for the new class. + + attributes_arguments: Passed unmodified to `attr.s`. + + Returns: + type: A new class with *attrs*. + + .. versionadded:: 17.1.0 *bases* + .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained. + .. versionchanged:: 23.2.0 *class_body* + """ + if isinstance(attrs, dict): + cls_dict = attrs + elif isinstance(attrs, (list, tuple)): + cls_dict = {a: attrib() for a in attrs} + else: + msg = "attrs argument must be a dict or a list." + raise TypeError(msg) + + pre_init = cls_dict.pop("__attrs_pre_init__", None) + post_init = cls_dict.pop("__attrs_post_init__", None) + user_init = cls_dict.pop("__init__", None) + + body = {} + if class_body is not None: + body.update(class_body) + if pre_init is not None: + body["__attrs_pre_init__"] = pre_init + if post_init is not None: + body["__attrs_post_init__"] = post_init + if user_init is not None: + body["__init__"] = user_init + + type_ = types.new_class(name, bases, {}, lambda ns: ns.update(body)) + + # For pickling to work, the __module__ variable needs to be set to the + # frame where the class is created. Bypass this step in environments where + # sys._getframe is not defined (Jython for example) or sys._getframe is not + # defined for arguments greater than 0 (IronPython). + with contextlib.suppress(AttributeError, ValueError): + type_.__module__ = sys._getframe(1).f_globals.get( + "__name__", "__main__" + ) + + # We do it here for proper warnings with meaningful stacklevel. + cmp = attributes_arguments.pop("cmp", None) + ( + attributes_arguments["eq"], + attributes_arguments["order"], + ) = _determine_attrs_eq_order( + cmp, + attributes_arguments.get("eq"), + attributes_arguments.get("order"), + True, + ) + + cls = _attrs(these=cls_dict, **attributes_arguments)(type_) + # Only add type annotations now or "_attrs()" will complain: + cls.__annotations__ = { + k: v.type for k, v in cls_dict.items() if v.type is not None + } + return cls + + +# These are required by within this module so we define them here and merely +# import into .validators / .converters. + + +@attrs(slots=True, unsafe_hash=True) +class _AndValidator: + """ + Compose many validators to a single one. + """ + + _validators = attrib() + + def __call__(self, inst, attr, value): + for v in self._validators: + v(inst, attr, value) + + +def and_(*validators): + """ + A validator that composes multiple validators into one. + + When called on a value, it runs all wrapped validators. + + Args: + validators (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of validators. + + .. versionadded:: 17.1.0 + """ + vals = [] + for validator in validators: + vals.extend( + validator._validators + if isinstance(validator, _AndValidator) + else [validator] + ) + + return _AndValidator(tuple(vals)) + + +def pipe(*converters): + """ + A converter that composes multiple converters into one. + + When called on a value, it runs all wrapped converters, returning the + *last* value. + + Type annotations will be inferred from the wrapped converters', if they + have any. + + converters (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of converters. + + .. versionadded:: 20.1.0 + """ + + def pipe_converter(val, inst, field): + for c in converters: + val = c(val, inst, field) if isinstance(c, Converter) else c(val) + + return val + + if not converters: + # If the converter list is empty, pipe_converter is the identity. + A = typing.TypeVar("A") + pipe_converter.__annotations__.update({"val": A, "return": A}) + else: + # Get parameter type from first converter. + t = _AnnotationExtractor(converters[0]).get_first_param_type() + if t: + pipe_converter.__annotations__["val"] = t + + last = converters[-1] + if not PY_3_11_PLUS and isinstance(last, Converter): + last = last.__call__ + + # Get return type from last converter. + rt = _AnnotationExtractor(last).get_return_type() + if rt: + pipe_converter.__annotations__["return"] = rt + + return Converter(pipe_converter, takes_self=True, takes_field=True) diff --git a/env/Lib/site-packages/attr/_next_gen.py b/env/Lib/site-packages/attr/_next_gen.py new file mode 100644 index 0000000..dbb65cc --- /dev/null +++ b/env/Lib/site-packages/attr/_next_gen.py @@ -0,0 +1,631 @@ +# SPDX-License-Identifier: MIT + +""" +These are keyword-only APIs that call `attr.s` and `attr.ib` with different +default values. +""" + + +from functools import partial + +from . import setters +from ._funcs import asdict as _asdict +from ._funcs import astuple as _astuple +from ._make import ( + _DEFAULT_ON_SETATTR, + NOTHING, + _frozen_setattrs, + attrib, + attrs, +) +from .exceptions import UnannotatedAttributeError + + +def define( + maybe_cls=None, + *, + these=None, + repr=None, + unsafe_hash=None, + hash=None, + init=None, + slots=True, + frozen=False, + weakref_slot=True, + str=False, + auto_attribs=None, + kw_only=False, + cache_hash=False, + auto_exc=True, + eq=None, + order=False, + auto_detect=True, + getstate_setstate=None, + on_setattr=None, + field_transformer=None, + match_args=True, +): + r""" + A class decorator that adds :term:`dunder methods` according to + :term:`fields ` specified using :doc:`type annotations `, + `field()` calls, or the *these* argument. + + Since *attrs* patches or replaces an existing class, you cannot use + `object.__init_subclass__` with *attrs* classes, because it runs too early. + As a replacement, you can define ``__attrs_init_subclass__`` on your class. + It will be called by *attrs* classes that subclass it after they're + created. See also :ref:`init-subclass`. + + Args: + slots (bool): + Create a :term:`slotted class ` that's more + memory-efficient. Slotted classes are generally superior to the + default dict classes, but have some gotchas you should know about, + so we encourage you to read the :term:`glossary entry `. + + auto_detect (bool): + Instead of setting the *init*, *repr*, *eq*, and *hash* arguments + explicitly, assume they are set to True **unless any** of the + involved methods for one of the arguments is implemented in the + *current* class (meaning, it is *not* inherited from some base + class). + + So, for example by implementing ``__eq__`` on a class yourself, + *attrs* will deduce ``eq=False`` and will create *neither* + ``__eq__`` *nor* ``__ne__`` (but Python classes come with a + sensible ``__ne__`` by default, so it *should* be enough to only + implement ``__eq__`` in most cases). + + Passing True or False` to *init*, *repr*, *eq*, *cmp*, or *hash* + overrides whatever *auto_detect* would determine. + + auto_exc (bool): + If the class subclasses `BaseException` (which implicitly includes + any subclass of any exception), the following happens to behave + like a well-behaved Python exception class: + + - the values for *eq*, *order*, and *hash* are ignored and the + instances compare and hash by the instance's ids [#]_ , + - all attributes that are either passed into ``__init__`` or have a + default value are additionally available as a tuple in the + ``args`` attribute, + - the value of *str* is ignored leaving ``__str__`` to base + classes. + + .. [#] + Note that *attrs* will *not* remove existing implementations of + ``__hash__`` or the equality methods. It just won't add own + ones. + + on_setattr (~typing.Callable | list[~typing.Callable] | None | ~typing.Literal[attrs.setters.NO_OP]): + A callable that is run whenever the user attempts to set an + attribute (either by assignment like ``i.x = 42`` or by using + `setattr` like ``setattr(i, "x", 42)``). It receives the same + arguments as validators: the instance, the attribute that is being + modified, and the new value. + + If no exception is raised, the attribute is set to the return value + of the callable. + + If a list of callables is passed, they're automatically wrapped in + an `attrs.setters.pipe`. + + If left None, the default behavior is to run converters and + validators whenever an attribute is set. + + init (bool): + Create a ``__init__`` method that initializes the *attrs* + attributes. Leading underscores are stripped for the argument name, + unless an alias is set on the attribute. + + .. seealso:: + `init` shows advanced ways to customize the generated + ``__init__`` method, including executing code before and after. + + repr(bool): + Create a ``__repr__`` method with a human readable representation + of *attrs* attributes. + + str (bool): + Create a ``__str__`` method that is identical to ``__repr__``. This + is usually not necessary except for `Exception`\ s. + + eq (bool | None): + If True or None (default), add ``__eq__`` and ``__ne__`` methods + that check two instances for equality. + + .. seealso:: + `comparison` describes how to customize the comparison behavior + going as far comparing NumPy arrays. + + order (bool | None): + If True, add ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` + methods that behave like *eq* above and allow instances to be + ordered. + + They compare the instances as if they were tuples of their *attrs* + attributes if and only if the types of both classes are + *identical*. + + If `None` mirror value of *eq*. + + .. seealso:: `comparison` + + cmp (bool | None): + Setting *cmp* is equivalent to setting *eq* and *order* to the same + value. Must not be mixed with *eq* or *order*. + + unsafe_hash (bool | None): + If None (default), the ``__hash__`` method is generated according + how *eq* and *frozen* are set. + + 1. If *both* are True, *attrs* will generate a ``__hash__`` for + you. + 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set + to None, marking it unhashable (which it is). + 3. If *eq* is False, ``__hash__`` will be left untouched meaning + the ``__hash__`` method of the base class will be used. If the + base class is `object`, this means it will fall back to id-based + hashing. + + Although not recommended, you can decide for yourself and force + *attrs* to create one (for example, if the class is immutable even + though you didn't freeze it programmatically) by passing True or + not. Both of these cases are rather special and should be used + carefully. + + .. seealso:: + + - Our documentation on `hashing`, + - Python's documentation on `object.__hash__`, + - and the `GitHub issue that led to the default \ behavior + `_ for more + details. + + hash (bool | None): + Deprecated alias for *unsafe_hash*. *unsafe_hash* takes precedence. + + cache_hash (bool): + Ensure that the object's hash code is computed only once and stored + on the object. If this is set to True, hashing must be either + explicitly or implicitly enabled for this class. If the hash code + is cached, avoid any reassignments of fields involved in hash code + computation or mutations of the objects those fields point to after + object creation. If such changes occur, the behavior of the + object's hash code is undefined. + + frozen (bool): + Make instances immutable after initialization. If someone attempts + to modify a frozen instance, `attrs.exceptions.FrozenInstanceError` + is raised. + + .. note:: + + 1. This is achieved by installing a custom ``__setattr__`` + method on your class, so you can't implement your own. + + 2. True immutability is impossible in Python. + + 3. This *does* have a minor a runtime performance `impact + ` when initializing new instances. In other + words: ``__init__`` is slightly slower with ``frozen=True``. + + 4. If a class is frozen, you cannot modify ``self`` in + ``__attrs_post_init__`` or a self-written ``__init__``. You + can circumvent that limitation by using + ``object.__setattr__(self, "attribute_name", value)``. + + 5. Subclasses of a frozen class are frozen too. + + kw_only (bool): + Make all attributes keyword-only in the generated ``__init__`` (if + *init* is False, this parameter is ignored). + + weakref_slot (bool): + Make instances weak-referenceable. This has no effect unless + *slots* is True. + + field_transformer (~typing.Callable | None): + A function that is called with the original class object and all + fields right before *attrs* finalizes the class. You can use this, + for example, to automatically add converters or validators to + fields based on their types. + + .. seealso:: `transform-fields` + + match_args (bool): + If True (default), set ``__match_args__`` on the class to support + :pep:`634` (*Structural Pattern Matching*). It is a tuple of all + non-keyword-only ``__init__`` parameter names on Python 3.10 and + later. Ignored on older Python versions. + + collect_by_mro (bool): + If True, *attrs* collects attributes from base classes correctly + according to the `method resolution order + `_. If False, *attrs* + will mimic the (wrong) behavior of `dataclasses` and :pep:`681`. + + See also `issue #428 + `_. + + getstate_setstate (bool | None): + .. note:: + + This is usually only interesting for slotted classes and you + should probably just set *auto_detect* to True. + + If True, ``__getstate__`` and ``__setstate__`` are generated and + attached to the class. This is necessary for slotted classes to be + pickleable. If left None, it's True by default for slotted classes + and False for dict classes. + + If *auto_detect* is True, and *getstate_setstate* is left None, and + **either** ``__getstate__`` or ``__setstate__`` is detected + directly on the class (meaning: not inherited), it is set to False + (this is usually what you want). + + auto_attribs (bool | None): + If True, look at type annotations to determine which attributes to + use, like `dataclasses`. If False, it will only look for explicit + :func:`field` class attributes, like classic *attrs*. + + If left None, it will guess: + + 1. If any attributes are annotated and no unannotated + `attrs.field`\ s are found, it assumes *auto_attribs=True*. + 2. Otherwise it assumes *auto_attribs=False* and tries to collect + `attrs.field`\ s. + + If *attrs* decides to look at type annotations, **all** fields + **must** be annotated. If *attrs* encounters a field that is set to + a :func:`field` / `attr.ib` but lacks a type annotation, an + `attrs.exceptions.UnannotatedAttributeError` is raised. Use + ``field_name: typing.Any = field(...)`` if you don't want to set a + type. + + .. warning:: + + For features that use the attribute name to create decorators + (for example, :ref:`validators `), you still *must* + assign :func:`field` / `attr.ib` to them. Otherwise Python will + either not find the name or try to use the default value to + call, for example, ``validator`` on it. + + Attributes annotated as `typing.ClassVar`, and attributes that are + neither annotated nor set to an `field()` are **ignored**. + + these (dict[str, object]): + A dictionary of name to the (private) return value of `field()` + mappings. This is useful to avoid the definition of your attributes + within the class body because you can't (for example, if you want + to add ``__repr__`` methods to Django models) or don't want to. + + If *these* is not `None`, *attrs* will *not* search the class body + for attributes and will *not* remove any attributes from it. + + The order is deduced from the order of the attributes inside + *these*. + + Arguably, this is a rather obscure feature. + + .. versionadded:: 20.1.0 + .. versionchanged:: 21.3.0 Converters are also run ``on_setattr``. + .. versionadded:: 22.2.0 + *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance). + .. versionchanged:: 24.1.0 + Instances are not compared as tuples of attributes anymore, but using a + big ``and`` condition. This is faster and has more correct behavior for + uncomparable values like `math.nan`. + .. versionadded:: 24.1.0 + If a class has an *inherited* classmethod called + ``__attrs_init_subclass__``, it is executed after the class is created. + .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*. + + .. note:: + + The main differences to the classic `attr.s` are: + + - Automatically detect whether or not *auto_attribs* should be `True` + (c.f. *auto_attribs* parameter). + - Converters and validators run when attributes are set by default -- + if *frozen* is `False`. + - *slots=True* + + Usually, this has only upsides and few visible effects in everyday + programming. But it *can* lead to some surprising behaviors, so + please make sure to read :term:`slotted classes`. + + - *auto_exc=True* + - *auto_detect=True* + - *order=False* + - Some options that were only relevant on Python 2 or were kept around + for backwards-compatibility have been removed. + + """ + + def do_it(cls, auto_attribs): + return attrs( + maybe_cls=cls, + these=these, + repr=repr, + hash=hash, + unsafe_hash=unsafe_hash, + init=init, + slots=slots, + frozen=frozen, + weakref_slot=weakref_slot, + str=str, + auto_attribs=auto_attribs, + kw_only=kw_only, + cache_hash=cache_hash, + auto_exc=auto_exc, + eq=eq, + order=order, + auto_detect=auto_detect, + collect_by_mro=True, + getstate_setstate=getstate_setstate, + on_setattr=on_setattr, + field_transformer=field_transformer, + match_args=match_args, + ) + + def wrap(cls): + """ + Making this a wrapper ensures this code runs during class creation. + + We also ensure that frozen-ness of classes is inherited. + """ + nonlocal frozen, on_setattr + + had_on_setattr = on_setattr not in (None, setters.NO_OP) + + # By default, mutable classes convert & validate on setattr. + if frozen is False and on_setattr is None: + on_setattr = _DEFAULT_ON_SETATTR + + # However, if we subclass a frozen class, we inherit the immutability + # and disable on_setattr. + for base_cls in cls.__bases__: + if base_cls.__setattr__ is _frozen_setattrs: + if had_on_setattr: + msg = "Frozen classes can't use on_setattr (frozen-ness was inherited)." + raise ValueError(msg) + + on_setattr = setters.NO_OP + break + + if auto_attribs is not None: + return do_it(cls, auto_attribs) + + try: + return do_it(cls, True) + except UnannotatedAttributeError: + return do_it(cls, False) + + # maybe_cls's type depends on the usage of the decorator. It's a class + # if it's used as `@attrs` but `None` if used as `@attrs()`. + if maybe_cls is None: + return wrap + + return wrap(maybe_cls) + + +mutable = define +frozen = partial(define, frozen=True, on_setattr=None) + + +def field( + *, + default=NOTHING, + validator=None, + repr=True, + hash=None, + init=True, + metadata=None, + type=None, + converter=None, + factory=None, + kw_only=False, + eq=None, + order=None, + on_setattr=None, + alias=None, +): + """ + Create a new :term:`field` / :term:`attribute` on a class. + + .. warning:: + + Does **nothing** unless the class is also decorated with + `attrs.define` (or similar)! + + Args: + default: + A value that is used if an *attrs*-generated ``__init__`` is used + and no value is passed while instantiating or the attribute is + excluded using ``init=False``. + + If the value is an instance of `attrs.Factory`, its callable will + be used to construct a new value (useful for mutable data types + like lists or dicts). + + If a default is not set (or set manually to `attrs.NOTHING`), a + value *must* be supplied when instantiating; otherwise a + `TypeError` will be raised. + + .. seealso:: `defaults` + + factory (~typing.Callable): + Syntactic sugar for ``default=attr.Factory(factory)``. + + validator (~typing.Callable | list[~typing.Callable]): + Callable that is called by *attrs*-generated ``__init__`` methods + after the instance has been initialized. They receive the + initialized instance, the :func:`~attrs.Attribute`, and the passed + value. + + The return value is *not* inspected so the validator has to throw + an exception itself. + + If a `list` is passed, its items are treated as validators and must + all pass. + + Validators can be globally disabled and re-enabled using + `attrs.validators.get_disabled` / `attrs.validators.set_disabled`. + + The validator can also be set using decorator notation as shown + below. + + .. seealso:: :ref:`validators` + + repr (bool | ~typing.Callable): + Include this attribute in the generated ``__repr__`` method. If + True, include the attribute; if False, omit it. By default, the + built-in ``repr()`` function is used. To override how the attribute + value is formatted, pass a ``callable`` that takes a single value + and returns a string. Note that the resulting string is used as-is, + which means it will be used directly *instead* of calling + ``repr()`` (the default). + + eq (bool | ~typing.Callable): + If True (default), include this attribute in the generated + ``__eq__`` and ``__ne__`` methods that check two instances for + equality. To override how the attribute value is compared, pass a + callable that takes a single value and returns the value to be + compared. + + .. seealso:: `comparison` + + order (bool | ~typing.Callable): + If True (default), include this attributes in the generated + ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods. To + override how the attribute value is ordered, pass a callable that + takes a single value and returns the value to be ordered. + + .. seealso:: `comparison` + + cmp(bool | ~typing.Callable): + Setting *cmp* is equivalent to setting *eq* and *order* to the same + value. Must not be mixed with *eq* or *order*. + + .. seealso:: `comparison` + + hash (bool | None): + Include this attribute in the generated ``__hash__`` method. If + None (default), mirror *eq*'s value. This is the correct behavior + according the Python spec. Setting this value to anything else + than None is *discouraged*. + + .. seealso:: `hashing` + + init (bool): + Include this attribute in the generated ``__init__`` method. + + It is possible to set this to False and set a default value. In + that case this attributed is unconditionally initialized with the + specified default value or factory. + + .. seealso:: `init` + + converter (typing.Callable | Converter): + A callable that is called by *attrs*-generated ``__init__`` methods + to convert attribute's value to the desired format. + + If a vanilla callable is passed, it is given the passed-in value as + the only positional argument. It is possible to receive additional + arguments by wrapping the callable in a `Converter`. + + Either way, the returned value will be used as the new value of the + attribute. The value is converted before being passed to the + validator, if any. + + .. seealso:: :ref:`converters` + + metadata (dict | None): + An arbitrary mapping, to be used by third-party code. + + .. seealso:: `extending-metadata`. + + type (type): + The type of the attribute. Nowadays, the preferred method to + specify the type is using a variable annotation (see :pep:`526`). + This argument is provided for backwards-compatibility and for usage + with `make_class`. Regardless of the approach used, the type will + be stored on ``Attribute.type``. + + Please note that *attrs* doesn't do anything with this metadata by + itself. You can use it as part of your own code or for `static type + checking `. + + kw_only (bool): + Make this attribute keyword-only in the generated ``__init__`` (if + ``init`` is False, this parameter is ignored). + + on_setattr (~typing.Callable | list[~typing.Callable] | None | ~typing.Literal[attrs.setters.NO_OP]): + Allows to overwrite the *on_setattr* setting from `attr.s`. If left + None, the *on_setattr* value from `attr.s` is used. Set to + `attrs.setters.NO_OP` to run **no** `setattr` hooks for this + attribute -- regardless of the setting in `define()`. + + alias (str | None): + Override this attribute's parameter name in the generated + ``__init__`` method. If left None, default to ``name`` stripped + of leading underscores. See `private-attributes`. + + .. versionadded:: 20.1.0 + .. versionchanged:: 21.1.0 + *eq*, *order*, and *cmp* also accept a custom callable + .. versionadded:: 22.2.0 *alias* + .. versionadded:: 23.1.0 + The *type* parameter has been re-added; mostly for `attrs.make_class`. + Please note that type checkers ignore this metadata. + + .. seealso:: + + `attr.ib` + """ + return attrib( + default=default, + validator=validator, + repr=repr, + hash=hash, + init=init, + metadata=metadata, + type=type, + converter=converter, + factory=factory, + kw_only=kw_only, + eq=eq, + order=order, + on_setattr=on_setattr, + alias=alias, + ) + + +def asdict(inst, *, recurse=True, filter=None, value_serializer=None): + """ + Same as `attr.asdict`, except that collections types are always retained + and dict is always used as *dict_factory*. + + .. versionadded:: 21.3.0 + """ + return _asdict( + inst=inst, + recurse=recurse, + filter=filter, + value_serializer=value_serializer, + retain_collection_types=True, + ) + + +def astuple(inst, *, recurse=True, filter=None): + """ + Same as `attr.astuple`, except that collections types are always retained + and `tuple` is always used as the *tuple_factory*. + + .. versionadded:: 21.3.0 + """ + return _astuple( + inst=inst, recurse=recurse, filter=filter, retain_collection_types=True + ) diff --git a/env/Lib/site-packages/attr/_typing_compat.pyi b/env/Lib/site-packages/attr/_typing_compat.pyi new file mode 100644 index 0000000..ca7b71e --- /dev/null +++ b/env/Lib/site-packages/attr/_typing_compat.pyi @@ -0,0 +1,15 @@ +from typing import Any, ClassVar, Protocol + +# MYPY is a special constant in mypy which works the same way as `TYPE_CHECKING`. +MYPY = False + +if MYPY: + # A protocol to be able to statically accept an attrs class. + class AttrsInstance_(Protocol): + __attrs_attrs__: ClassVar[Any] + +else: + # For type checkers without plug-in support use an empty protocol that + # will (hopefully) be combined into a union. + class AttrsInstance_(Protocol): + pass diff --git a/env/Lib/site-packages/attr/_version_info.py b/env/Lib/site-packages/attr/_version_info.py new file mode 100644 index 0000000..51a1312 --- /dev/null +++ b/env/Lib/site-packages/attr/_version_info.py @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: MIT + + +from functools import total_ordering + +from ._funcs import astuple +from ._make import attrib, attrs + + +@total_ordering +@attrs(eq=False, order=False, slots=True, frozen=True) +class VersionInfo: + """ + A version object that can be compared to tuple of length 1--4: + + >>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2) + True + >>> attr.VersionInfo(19, 1, 0, "final") < (19, 1, 1) + True + >>> vi = attr.VersionInfo(19, 2, 0, "final") + >>> vi < (19, 1, 1) + False + >>> vi < (19,) + False + >>> vi == (19, 2,) + True + >>> vi == (19, 2, 1) + False + + .. versionadded:: 19.2 + """ + + year = attrib(type=int) + minor = attrib(type=int) + micro = attrib(type=int) + releaselevel = attrib(type=str) + + @classmethod + def _from_version_string(cls, s): + """ + Parse *s* and return a _VersionInfo. + """ + v = s.split(".") + if len(v) == 3: + v.append("final") + + return cls( + year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3] + ) + + def _ensure_tuple(self, other): + """ + Ensure *other* is a tuple of a valid length. + + Returns a possibly transformed *other* and ourselves as a tuple of + the same length as *other*. + """ + + if self.__class__ is other.__class__: + other = astuple(other) + + if not isinstance(other, tuple): + raise NotImplementedError + + if not (1 <= len(other) <= 4): + raise NotImplementedError + + return astuple(self)[: len(other)], other + + def __eq__(self, other): + try: + us, them = self._ensure_tuple(other) + except NotImplementedError: + return NotImplemented + + return us == them + + def __lt__(self, other): + try: + us, them = self._ensure_tuple(other) + except NotImplementedError: + return NotImplemented + + # Since alphabetically "dev0" < "final" < "post1" < "post2", we don't + # have to do anything special with releaselevel for now. + return us < them diff --git a/env/Lib/site-packages/attr/_version_info.pyi b/env/Lib/site-packages/attr/_version_info.pyi new file mode 100644 index 0000000..45ced08 --- /dev/null +++ b/env/Lib/site-packages/attr/_version_info.pyi @@ -0,0 +1,9 @@ +class VersionInfo: + @property + def year(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def micro(self) -> int: ... + @property + def releaselevel(self) -> str: ... diff --git a/env/Lib/site-packages/attr/converters.py b/env/Lib/site-packages/attr/converters.py new file mode 100644 index 0000000..9238311 --- /dev/null +++ b/env/Lib/site-packages/attr/converters.py @@ -0,0 +1,151 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful converters. +""" + + +import typing + +from ._compat import _AnnotationExtractor +from ._make import NOTHING, Factory, pipe + + +__all__ = [ + "default_if_none", + "optional", + "pipe", + "to_bool", +] + + +def optional(converter): + """ + A converter that allows an attribute to be optional. An optional attribute + is one which can be set to `None`. + + Type annotations will be inferred from the wrapped converter's, if it has + any. + + Args: + converter (typing.Callable): + the converter that is used for non-`None` values. + + .. versionadded:: 17.1.0 + """ + + def optional_converter(val): + if val is None: + return None + return converter(val) + + xtr = _AnnotationExtractor(converter) + + t = xtr.get_first_param_type() + if t: + optional_converter.__annotations__["val"] = typing.Optional[t] + + rt = xtr.get_return_type() + if rt: + optional_converter.__annotations__["return"] = typing.Optional[rt] + + return optional_converter + + +def default_if_none(default=NOTHING, factory=None): + """ + A converter that allows to replace `None` values by *default* or the result + of *factory*. + + Args: + default: + Value to be used if `None` is passed. Passing an instance of + `attrs.Factory` is supported, however the ``takes_self`` option is + *not*. + + factory (typing.Callable): + A callable that takes no parameters whose result is used if `None` + is passed. + + Raises: + TypeError: If **neither** *default* or *factory* is passed. + + TypeError: If **both** *default* and *factory* are passed. + + ValueError: + If an instance of `attrs.Factory` is passed with + ``takes_self=True``. + + .. versionadded:: 18.2.0 + """ + if default is NOTHING and factory is None: + msg = "Must pass either `default` or `factory`." + raise TypeError(msg) + + if default is not NOTHING and factory is not None: + msg = "Must pass either `default` or `factory` but not both." + raise TypeError(msg) + + if factory is not None: + default = Factory(factory) + + if isinstance(default, Factory): + if default.takes_self: + msg = "`takes_self` is not supported by default_if_none." + raise ValueError(msg) + + def default_if_none_converter(val): + if val is not None: + return val + + return default.factory() + + else: + + def default_if_none_converter(val): + if val is not None: + return val + + return default + + return default_if_none_converter + + +def to_bool(val): + """ + Convert "boolean" strings (for example, from environment variables) to real + booleans. + + Values mapping to `True`: + + - ``True`` + - ``"true"`` / ``"t"`` + - ``"yes"`` / ``"y"`` + - ``"on"`` + - ``"1"`` + - ``1`` + + Values mapping to `False`: + + - ``False`` + - ``"false"`` / ``"f"`` + - ``"no"`` / ``"n"`` + - ``"off"`` + - ``"0"`` + - ``0`` + + Raises: + ValueError: For any other value. + + .. versionadded:: 21.3.0 + """ + if isinstance(val, str): + val = val.lower() + + if val in (True, "true", "t", "yes", "y", "on", "1", 1): + return True + if val in (False, "false", "f", "no", "n", "off", "0", 0): + return False + + msg = f"Cannot convert value to bool: {val!r}" + raise ValueError(msg) diff --git a/env/Lib/site-packages/attr/converters.pyi b/env/Lib/site-packages/attr/converters.pyi new file mode 100644 index 0000000..9ef478f --- /dev/null +++ b/env/Lib/site-packages/attr/converters.pyi @@ -0,0 +1,13 @@ +from typing import Callable, TypeVar, overload + +from attrs import _ConverterType + +_T = TypeVar("_T") + +def pipe(*validators: _ConverterType) -> _ConverterType: ... +def optional(converter: _ConverterType) -> _ConverterType: ... +@overload +def default_if_none(default: _T) -> _ConverterType: ... +@overload +def default_if_none(*, factory: Callable[[], _T]) -> _ConverterType: ... +def to_bool(val: str) -> bool: ... diff --git a/env/Lib/site-packages/attr/exceptions.py b/env/Lib/site-packages/attr/exceptions.py new file mode 100644 index 0000000..3b7abb8 --- /dev/null +++ b/env/Lib/site-packages/attr/exceptions.py @@ -0,0 +1,95 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + +from typing import ClassVar + + +class FrozenError(AttributeError): + """ + A frozen/immutable instance or attribute have been attempted to be + modified. + + It mirrors the behavior of ``namedtuples`` by using the same error message + and subclassing `AttributeError`. + + .. versionadded:: 20.1.0 + """ + + msg = "can't set attribute" + args: ClassVar[tuple[str]] = [msg] + + +class FrozenInstanceError(FrozenError): + """ + A frozen instance has been attempted to be modified. + + .. versionadded:: 16.1.0 + """ + + +class FrozenAttributeError(FrozenError): + """ + A frozen attribute has been attempted to be modified. + + .. versionadded:: 20.1.0 + """ + + +class AttrsAttributeNotFoundError(ValueError): + """ + An *attrs* function couldn't find an attribute that the user asked for. + + .. versionadded:: 16.2.0 + """ + + +class NotAnAttrsClassError(ValueError): + """ + A non-*attrs* class has been passed into an *attrs* function. + + .. versionadded:: 16.2.0 + """ + + +class DefaultAlreadySetError(RuntimeError): + """ + A default has been set when defining the field and is attempted to be reset + using the decorator. + + .. versionadded:: 17.1.0 + """ + + +class UnannotatedAttributeError(RuntimeError): + """ + A class with ``auto_attribs=True`` has a field without a type annotation. + + .. versionadded:: 17.3.0 + """ + + +class PythonTooOldError(RuntimeError): + """ + It was attempted to use an *attrs* feature that requires a newer Python + version. + + .. versionadded:: 18.2.0 + """ + + +class NotCallableError(TypeError): + """ + A field requiring a callable has been set with a value that is not + callable. + + .. versionadded:: 19.2.0 + """ + + def __init__(self, msg, value): + super(TypeError, self).__init__(msg, value) + self.msg = msg + self.value = value + + def __str__(self): + return str(self.msg) diff --git a/env/Lib/site-packages/attr/exceptions.pyi b/env/Lib/site-packages/attr/exceptions.pyi new file mode 100644 index 0000000..f268011 --- /dev/null +++ b/env/Lib/site-packages/attr/exceptions.pyi @@ -0,0 +1,17 @@ +from typing import Any + +class FrozenError(AttributeError): + msg: str = ... + +class FrozenInstanceError(FrozenError): ... +class FrozenAttributeError(FrozenError): ... +class AttrsAttributeNotFoundError(ValueError): ... +class NotAnAttrsClassError(ValueError): ... +class DefaultAlreadySetError(RuntimeError): ... +class UnannotatedAttributeError(RuntimeError): ... +class PythonTooOldError(RuntimeError): ... + +class NotCallableError(TypeError): + msg: str = ... + value: Any = ... + def __init__(self, msg: str, value: Any) -> None: ... diff --git a/env/Lib/site-packages/attr/filters.py b/env/Lib/site-packages/attr/filters.py new file mode 100644 index 0000000..689b170 --- /dev/null +++ b/env/Lib/site-packages/attr/filters.py @@ -0,0 +1,72 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful filters for `attrs.asdict` and `attrs.astuple`. +""" + +from ._make import Attribute + + +def _split_what(what): + """ + Returns a tuple of `frozenset`s of classes and attributes. + """ + return ( + frozenset(cls for cls in what if isinstance(cls, type)), + frozenset(cls for cls in what if isinstance(cls, str)), + frozenset(cls for cls in what if isinstance(cls, Attribute)), + ) + + +def include(*what): + """ + Create a filter that only allows *what*. + + Args: + what (list[type, str, attrs.Attribute]): + What to include. Can be a type, a name, or an attribute. + + Returns: + Callable: + A callable that can be passed to `attrs.asdict`'s and + `attrs.astuple`'s *filter* argument. + + .. versionchanged:: 23.1.0 Accept strings with field names. + """ + cls, names, attrs = _split_what(what) + + def include_(attribute, value): + return ( + value.__class__ in cls + or attribute.name in names + or attribute in attrs + ) + + return include_ + + +def exclude(*what): + """ + Create a filter that does **not** allow *what*. + + Args: + what (list[type, str, attrs.Attribute]): + What to exclude. Can be a type, a name, or an attribute. + + Returns: + Callable: + A callable that can be passed to `attrs.asdict`'s and + `attrs.astuple`'s *filter* argument. + + .. versionchanged:: 23.3.0 Accept field name string as input argument + """ + cls, names, attrs = _split_what(what) + + def exclude_(attribute, value): + return not ( + value.__class__ in cls + or attribute.name in names + or attribute in attrs + ) + + return exclude_ diff --git a/env/Lib/site-packages/attr/filters.pyi b/env/Lib/site-packages/attr/filters.pyi new file mode 100644 index 0000000..974abdc --- /dev/null +++ b/env/Lib/site-packages/attr/filters.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from . import Attribute, _FilterType + +def include(*what: type | str | Attribute[Any]) -> _FilterType[Any]: ... +def exclude(*what: type | str | Attribute[Any]) -> _FilterType[Any]: ... diff --git a/env/Lib/site-packages/attr/py.typed b/env/Lib/site-packages/attr/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/attr/setters.py b/env/Lib/site-packages/attr/setters.py new file mode 100644 index 0000000..a9ce016 --- /dev/null +++ b/env/Lib/site-packages/attr/setters.py @@ -0,0 +1,79 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly used hooks for on_setattr. +""" + +from . import _config +from .exceptions import FrozenAttributeError + + +def pipe(*setters): + """ + Run all *setters* and return the return value of the last one. + + .. versionadded:: 20.1.0 + """ + + def wrapped_pipe(instance, attrib, new_value): + rv = new_value + + for setter in setters: + rv = setter(instance, attrib, rv) + + return rv + + return wrapped_pipe + + +def frozen(_, __, ___): + """ + Prevent an attribute to be modified. + + .. versionadded:: 20.1.0 + """ + raise FrozenAttributeError() + + +def validate(instance, attrib, new_value): + """ + Run *attrib*'s validator on *new_value* if it has one. + + .. versionadded:: 20.1.0 + """ + if _config._run_validators is False: + return new_value + + v = attrib.validator + if not v: + return new_value + + v(instance, attrib, new_value) + + return new_value + + +def convert(instance, attrib, new_value): + """ + Run *attrib*'s converter -- if it has one -- on *new_value* and return the + result. + + .. versionadded:: 20.1.0 + """ + c = attrib.converter + if c: + # This can be removed once we drop 3.8 and use attrs.Converter instead. + from ._make import Converter + + if not isinstance(c, Converter): + return c(new_value) + + return c(new_value, instance, attrib) + + return new_value + + +# Sentinel for disabling class-wide *on_setattr* hooks for certain attributes. +# Sphinx's autodata stopped working, so the docstring is inlined in the API +# docs. +NO_OP = object() diff --git a/env/Lib/site-packages/attr/setters.pyi b/env/Lib/site-packages/attr/setters.pyi new file mode 100644 index 0000000..73abf36 --- /dev/null +++ b/env/Lib/site-packages/attr/setters.pyi @@ -0,0 +1,20 @@ +from typing import Any, NewType, NoReturn, TypeVar + +from . import Attribute +from attrs import _OnSetAttrType + +_T = TypeVar("_T") + +def frozen( + instance: Any, attribute: Attribute[Any], new_value: Any +) -> NoReturn: ... +def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ... +def validate(instance: Any, attribute: Attribute[_T], new_value: _T) -> _T: ... + +# convert is allowed to return Any, because they can be chained using pipe. +def convert( + instance: Any, attribute: Attribute[Any], new_value: Any +) -> Any: ... + +_NoOpType = NewType("_NoOpType", object) +NO_OP: _NoOpType diff --git a/env/Lib/site-packages/attr/validators.py b/env/Lib/site-packages/attr/validators.py new file mode 100644 index 0000000..8a56717 --- /dev/null +++ b/env/Lib/site-packages/attr/validators.py @@ -0,0 +1,711 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful validators. +""" + + +import operator +import re + +from contextlib import contextmanager +from re import Pattern + +from ._config import get_run_validators, set_run_validators +from ._make import _AndValidator, and_, attrib, attrs +from .converters import default_if_none +from .exceptions import NotCallableError + + +__all__ = [ + "and_", + "deep_iterable", + "deep_mapping", + "disabled", + "ge", + "get_disabled", + "gt", + "in_", + "instance_of", + "is_callable", + "le", + "lt", + "matches_re", + "max_len", + "min_len", + "not_", + "optional", + "or_", + "set_disabled", +] + + +def set_disabled(disabled): + """ + Globally disable or enable running validators. + + By default, they are run. + + Args: + disabled (bool): If `True`, disable running all validators. + + .. warning:: + + This function is not thread-safe! + + .. versionadded:: 21.3.0 + """ + set_run_validators(not disabled) + + +def get_disabled(): + """ + Return a bool indicating whether validators are currently disabled or not. + + Returns: + bool:`True` if validators are currently disabled. + + .. versionadded:: 21.3.0 + """ + return not get_run_validators() + + +@contextmanager +def disabled(): + """ + Context manager that disables running validators within its context. + + .. warning:: + + This context manager is not thread-safe! + + .. versionadded:: 21.3.0 + """ + set_run_validators(False) + try: + yield + finally: + set_run_validators(True) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _InstanceOfValidator: + type = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not isinstance(value, self.type): + msg = f"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r})." + raise TypeError( + msg, + attr, + self.type, + value, + ) + + def __repr__(self): + return f"" + + +def instance_of(type): + """ + A validator that raises a `TypeError` if the initializer is called with a + wrong type for this particular attribute (checks are performed using + `isinstance` therefore it's also valid to pass a tuple of types). + + Args: + type (type | tuple[type]): The type to check for. + + Raises: + TypeError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected type, and the value it got. + """ + return _InstanceOfValidator(type) + + +@attrs(repr=False, frozen=True, slots=True) +class _MatchesReValidator: + pattern = attrib() + match_func = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.match_func(value): + msg = f"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)" + raise ValueError( + msg, + attr, + self.pattern, + value, + ) + + def __repr__(self): + return f"" + + +def matches_re(regex, flags=0, func=None): + r""" + A validator that raises `ValueError` if the initializer is called with a + string that doesn't match *regex*. + + Args: + regex (str, re.Pattern): + A regex string or precompiled pattern to match against + + flags (int): + Flags that will be passed to the underlying re function (default 0) + + func (typing.Callable): + Which underlying `re` function to call. Valid options are + `re.fullmatch`, `re.search`, and `re.match`; the default `None` + means `re.fullmatch`. For performance reasons, the pattern is + always precompiled using `re.compile`. + + .. versionadded:: 19.2.0 + .. versionchanged:: 21.3.0 *regex* can be a pre-compiled pattern. + """ + valid_funcs = (re.fullmatch, None, re.search, re.match) + if func not in valid_funcs: + msg = "'func' must be one of {}.".format( + ", ".join( + sorted(e and e.__name__ or "None" for e in set(valid_funcs)) + ) + ) + raise ValueError(msg) + + if isinstance(regex, Pattern): + if flags: + msg = "'flags' can only be used with a string pattern; pass flags to re.compile() instead" + raise TypeError(msg) + pattern = regex + else: + pattern = re.compile(regex, flags) + + if func is re.match: + match_func = pattern.match + elif func is re.search: + match_func = pattern.search + else: + match_func = pattern.fullmatch + + return _MatchesReValidator(pattern, match_func) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _OptionalValidator: + validator = attrib() + + def __call__(self, inst, attr, value): + if value is None: + return + + self.validator(inst, attr, value) + + def __repr__(self): + return f"" + + +def optional(validator): + """ + A validator that makes an attribute optional. An optional attribute is one + which can be set to `None` in addition to satisfying the requirements of + the sub-validator. + + Args: + validator + (typing.Callable | tuple[typing.Callable] | list[typing.Callable]): + A validator (or validators) that is used for non-`None` values. + + .. versionadded:: 15.1.0 + .. versionchanged:: 17.1.0 *validator* can be a list of validators. + .. versionchanged:: 23.1.0 *validator* can also be a tuple of validators. + """ + if isinstance(validator, (list, tuple)): + return _OptionalValidator(_AndValidator(validator)) + + return _OptionalValidator(validator) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _InValidator: + options = attrib() + _original_options = attrib(hash=False) + + def __call__(self, inst, attr, value): + try: + in_options = value in self.options + except TypeError: # e.g. `1 in "abc"` + in_options = False + + if not in_options: + msg = f"'{attr.name}' must be in {self._original_options!r} (got {value!r})" + raise ValueError( + msg, + attr, + self._original_options, + value, + ) + + def __repr__(self): + return f"" + + +def in_(options): + """ + A validator that raises a `ValueError` if the initializer is called with a + value that does not belong in the *options* provided. + + The check is performed using ``value in options``, so *options* has to + support that operation. + + To keep the validator hashable, dicts, lists, and sets are transparently + transformed into a `tuple`. + + Args: + options: Allowed options. + + Raises: + ValueError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected options, and the value it got. + + .. versionadded:: 17.1.0 + .. versionchanged:: 22.1.0 + The ValueError was incomplete until now and only contained the human + readable error message. Now it contains all the information that has + been promised since 17.1.0. + .. versionchanged:: 24.1.0 + *options* that are a list, dict, or a set are now transformed into a + tuple to keep the validator hashable. + """ + repr_options = options + if isinstance(options, (list, dict, set)): + options = tuple(options) + + return _InValidator(options, repr_options) + + +@attrs(repr=False, slots=False, unsafe_hash=True) +class _IsCallableValidator: + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not callable(value): + message = ( + "'{name}' must be callable " + "(got {value!r} that is a {actual!r})." + ) + raise NotCallableError( + msg=message.format( + name=attr.name, value=value, actual=value.__class__ + ), + value=value, + ) + + def __repr__(self): + return "" + + +def is_callable(): + """ + A validator that raises a `attrs.exceptions.NotCallableError` if the + initializer is called with a value for this particular attribute that is + not callable. + + .. versionadded:: 19.1.0 + + Raises: + attrs.exceptions.NotCallableError: + With a human readable error message containing the attribute + (`attrs.Attribute`) name, and the value it got. + """ + return _IsCallableValidator() + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _DeepIterable: + member_validator = attrib(validator=is_callable()) + iterable_validator = attrib( + default=None, validator=optional(is_callable()) + ) + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if self.iterable_validator is not None: + self.iterable_validator(inst, attr, value) + + for member in value: + self.member_validator(inst, attr, member) + + def __repr__(self): + iterable_identifier = ( + "" + if self.iterable_validator is None + else f" {self.iterable_validator!r}" + ) + return ( + f"" + ) + + +def deep_iterable(member_validator, iterable_validator=None): + """ + A validator that performs deep validation of an iterable. + + Args: + member_validator: Validator to apply to iterable members. + + iterable_validator: + Validator to apply to iterable itself (optional). + + Raises + TypeError: if any sub-validators fail + + .. versionadded:: 19.1.0 + """ + if isinstance(member_validator, (list, tuple)): + member_validator = and_(*member_validator) + return _DeepIterable(member_validator, iterable_validator) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _DeepMapping: + key_validator = attrib(validator=is_callable()) + value_validator = attrib(validator=is_callable()) + mapping_validator = attrib(default=None, validator=optional(is_callable())) + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if self.mapping_validator is not None: + self.mapping_validator(inst, attr, value) + + for key in value: + self.key_validator(inst, attr, key) + self.value_validator(inst, attr, value[key]) + + def __repr__(self): + return f"" + + +def deep_mapping(key_validator, value_validator, mapping_validator=None): + """ + A validator that performs deep validation of a dictionary. + + Args: + key_validator: Validator to apply to dictionary keys. + + value_validator: Validator to apply to dictionary values. + + mapping_validator: + Validator to apply to top-level mapping attribute (optional). + + .. versionadded:: 19.1.0 + + Raises: + TypeError: if any sub-validators fail + """ + return _DeepMapping(key_validator, value_validator, mapping_validator) + + +@attrs(repr=False, frozen=True, slots=True) +class _NumberValidator: + bound = attrib() + compare_op = attrib() + compare_func = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.compare_func(value, self.bound): + msg = f"'{attr.name}' must be {self.compare_op} {self.bound}: {value}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def lt(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number larger or equal to *val*. + + The validator uses `operator.lt` to compare the values. + + Args: + val: Exclusive upper bound for values. + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, "<", operator.lt) + + +def le(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number greater than *val*. + + The validator uses `operator.le` to compare the values. + + Args: + val: Inclusive upper bound for values. + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, "<=", operator.le) + + +def ge(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number smaller than *val*. + + The validator uses `operator.ge` to compare the values. + + Args: + val: Inclusive lower bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, ">=", operator.ge) + + +def gt(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number smaller or equal to *val*. + + The validator uses `operator.ge` to compare the values. + + Args: + val: Exclusive lower bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, ">", operator.gt) + + +@attrs(repr=False, frozen=True, slots=True) +class _MaxLengthValidator: + max_length = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if len(value) > self.max_length: + msg = f"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def max_len(length): + """ + A validator that raises `ValueError` if the initializer is called + with a string or iterable that is longer than *length*. + + Args: + length (int): Maximum length of the string or iterable + + .. versionadded:: 21.3.0 + """ + return _MaxLengthValidator(length) + + +@attrs(repr=False, frozen=True, slots=True) +class _MinLengthValidator: + min_length = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if len(value) < self.min_length: + msg = f"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def min_len(length): + """ + A validator that raises `ValueError` if the initializer is called + with a string or iterable that is shorter than *length*. + + Args: + length (int): Minimum length of the string or iterable + + .. versionadded:: 22.1.0 + """ + return _MinLengthValidator(length) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _SubclassOfValidator: + type = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not issubclass(value, self.type): + msg = f"'{attr.name}' must be a subclass of {self.type!r} (got {value!r})." + raise TypeError( + msg, + attr, + self.type, + value, + ) + + def __repr__(self): + return f"" + + +def _subclass_of(type): + """ + A validator that raises a `TypeError` if the initializer is called with a + wrong type for this particular attribute (checks are performed using + `issubclass` therefore it's also valid to pass a tuple of types). + + Args: + type (type | tuple[type, ...]): The type(s) to check for. + + Raises: + TypeError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected type, and the value it got. + """ + return _SubclassOfValidator(type) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _NotValidator: + validator = attrib() + msg = attrib( + converter=default_if_none( + "not_ validator child '{validator!r}' " + "did not raise a captured error" + ) + ) + exc_types = attrib( + validator=deep_iterable( + member_validator=_subclass_of(Exception), + iterable_validator=instance_of(tuple), + ), + ) + + def __call__(self, inst, attr, value): + try: + self.validator(inst, attr, value) + except self.exc_types: + pass # suppress error to invert validity + else: + raise ValueError( + self.msg.format( + validator=self.validator, + exc_types=self.exc_types, + ), + attr, + self.validator, + value, + self.exc_types, + ) + + def __repr__(self): + return f"" + + +def not_(validator, *, msg=None, exc_types=(ValueError, TypeError)): + """ + A validator that wraps and logically 'inverts' the validator passed to it. + It will raise a `ValueError` if the provided validator *doesn't* raise a + `ValueError` or `TypeError` (by default), and will suppress the exception + if the provided validator *does*. + + Intended to be used with existing validators to compose logic without + needing to create inverted variants, for example, ``not_(in_(...))``. + + Args: + validator: A validator to be logically inverted. + + msg (str): + Message to raise if validator fails. Formatted with keys + ``exc_types`` and ``validator``. + + exc_types (tuple[type, ...]): + Exception type(s) to capture. Other types raised by child + validators will not be intercepted and pass through. + + Raises: + ValueError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the validator that failed to raise an + exception, the value it got, and the expected exception types. + + .. versionadded:: 22.2.0 + """ + try: + exc_types = tuple(exc_types) + except TypeError: + exc_types = (exc_types,) + return _NotValidator(validator, msg, exc_types) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _OrValidator: + validators = attrib() + + def __call__(self, inst, attr, value): + for v in self.validators: + try: + v(inst, attr, value) + except Exception: # noqa: BLE001, PERF203, S112 + continue + else: + return + + msg = f"None of {self.validators!r} satisfied for value {value!r}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def or_(*validators): + """ + A validator that composes multiple validators into one. + + When called on a value, it runs all wrapped validators until one of them is + satisfied. + + Args: + validators (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of validators. + + Raises: + ValueError: + If no validator is satisfied. Raised with a human-readable error + message listing all the wrapped validators and the value that + failed all of them. + + .. versionadded:: 24.1.0 + """ + vals = [] + for v in validators: + vals.extend(v.validators if isinstance(v, _OrValidator) else [v]) + + return _OrValidator(tuple(vals)) diff --git a/env/Lib/site-packages/attr/validators.pyi b/env/Lib/site-packages/attr/validators.pyi new file mode 100644 index 0000000..a314110 --- /dev/null +++ b/env/Lib/site-packages/attr/validators.pyi @@ -0,0 +1,83 @@ +from typing import ( + Any, + AnyStr, + Callable, + Container, + ContextManager, + Iterable, + Mapping, + Match, + Pattern, + TypeVar, + overload, +) + +from attrs import _ValidatorType +from attrs import _ValidatorArgType + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_I = TypeVar("_I", bound=Iterable) +_K = TypeVar("_K") +_V = TypeVar("_V") +_M = TypeVar("_M", bound=Mapping) + +def set_disabled(run: bool) -> None: ... +def get_disabled() -> bool: ... +def disabled() -> ContextManager[None]: ... + +# To be more precise on instance_of use some overloads. +# If there are more than 3 items in the tuple then we fall back to Any +@overload +def instance_of(type: type[_T]) -> _ValidatorType[_T]: ... +@overload +def instance_of(type: tuple[type[_T]]) -> _ValidatorType[_T]: ... +@overload +def instance_of( + type: tuple[type[_T1], type[_T2]] +) -> _ValidatorType[_T1 | _T2]: ... +@overload +def instance_of( + type: tuple[type[_T1], type[_T2], type[_T3]] +) -> _ValidatorType[_T1 | _T2 | _T3]: ... +@overload +def instance_of(type: tuple[type, ...]) -> _ValidatorType[Any]: ... +def optional( + validator: ( + _ValidatorType[_T] + | list[_ValidatorType[_T]] + | tuple[_ValidatorType[_T]] + ), +) -> _ValidatorType[_T | None]: ... +def in_(options: Container[_T]) -> _ValidatorType[_T]: ... +def and_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ... +def matches_re( + regex: Pattern[AnyStr] | AnyStr, + flags: int = ..., + func: Callable[[AnyStr, AnyStr, int], Match[AnyStr] | None] | None = ..., +) -> _ValidatorType[AnyStr]: ... +def deep_iterable( + member_validator: _ValidatorArgType[_T], + iterable_validator: _ValidatorType[_I] | None = ..., +) -> _ValidatorType[_I]: ... +def deep_mapping( + key_validator: _ValidatorType[_K], + value_validator: _ValidatorType[_V], + mapping_validator: _ValidatorType[_M] | None = ..., +) -> _ValidatorType[_M]: ... +def is_callable() -> _ValidatorType[_T]: ... +def lt(val: _T) -> _ValidatorType[_T]: ... +def le(val: _T) -> _ValidatorType[_T]: ... +def ge(val: _T) -> _ValidatorType[_T]: ... +def gt(val: _T) -> _ValidatorType[_T]: ... +def max_len(length: int) -> _ValidatorType[_T]: ... +def min_len(length: int) -> _ValidatorType[_T]: ... +def not_( + validator: _ValidatorType[_T], + *, + msg: str | None = None, + exc_types: type[Exception] | Iterable[type[Exception]] = ..., +) -> _ValidatorType[_T]: ... +def or_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ... diff --git a/env/Lib/site-packages/attrs-24.2.0.dist-info/INSTALLER b/env/Lib/site-packages/attrs-24.2.0.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/attrs-24.2.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/attrs-24.2.0.dist-info/METADATA b/env/Lib/site-packages/attrs-24.2.0.dist-info/METADATA new file mode 100644 index 0000000..a85b378 --- /dev/null +++ b/env/Lib/site-packages/attrs-24.2.0.dist-info/METADATA @@ -0,0 +1,242 @@ +Metadata-Version: 2.3 +Name: attrs +Version: 24.2.0 +Summary: Classes Without Boilerplate +Project-URL: Documentation, https://www.attrs.org/ +Project-URL: Changelog, https://www.attrs.org/en/stable/changelog.html +Project-URL: GitHub, https://github.com/python-attrs/attrs +Project-URL: Funding, https://github.com/sponsors/hynek +Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-attrs?utm_source=pypi-attrs&utm_medium=pypi +Author-email: Hynek Schlawack +License-Expression: MIT +License-File: LICENSE +Keywords: attribute,boilerplate,class +Classifier: Development Status :: 5 - Production/Stable +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Typing :: Typed +Requires-Python: >=3.7 +Requires-Dist: importlib-metadata; python_version < '3.8' +Provides-Extra: benchmark +Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'benchmark' +Requires-Dist: hypothesis; extra == 'benchmark' +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.9') and extra == 'benchmark' +Requires-Dist: pympler; extra == 'benchmark' +Requires-Dist: pytest-codspeed; extra == 'benchmark' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.9' and python_version < '3.13') and extra == 'benchmark' +Requires-Dist: pytest-xdist[psutil]; extra == 'benchmark' +Requires-Dist: pytest>=4.3.0; extra == 'benchmark' +Provides-Extra: cov +Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'cov' +Requires-Dist: coverage[toml]>=5.3; extra == 'cov' +Requires-Dist: hypothesis; extra == 'cov' +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.9') and extra == 'cov' +Requires-Dist: pympler; extra == 'cov' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.9' and python_version < '3.13') and extra == 'cov' +Requires-Dist: pytest-xdist[psutil]; extra == 'cov' +Requires-Dist: pytest>=4.3.0; extra == 'cov' +Provides-Extra: dev +Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'dev' +Requires-Dist: hypothesis; extra == 'dev' +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.9') and extra == 'dev' +Requires-Dist: pre-commit; extra == 'dev' +Requires-Dist: pympler; extra == 'dev' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.9' and python_version < '3.13') and extra == 'dev' +Requires-Dist: pytest-xdist[psutil]; extra == 'dev' +Requires-Dist: pytest>=4.3.0; extra == 'dev' +Provides-Extra: docs +Requires-Dist: cogapp; extra == 'docs' +Requires-Dist: furo; extra == 'docs' +Requires-Dist: myst-parser; extra == 'docs' +Requires-Dist: sphinx; extra == 'docs' +Requires-Dist: sphinx-notfound-page; extra == 'docs' +Requires-Dist: sphinxcontrib-towncrier; extra == 'docs' +Requires-Dist: towncrier<24.7; extra == 'docs' +Provides-Extra: tests +Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'tests' +Requires-Dist: hypothesis; extra == 'tests' +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.9') and extra == 'tests' +Requires-Dist: pympler; extra == 'tests' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.9' and python_version < '3.13') and extra == 'tests' +Requires-Dist: pytest-xdist[psutil]; extra == 'tests' +Requires-Dist: pytest>=4.3.0; extra == 'tests' +Provides-Extra: tests-mypy +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.9') and extra == 'tests-mypy' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.9' and python_version < '3.13') and extra == 'tests-mypy' +Description-Content-Type: text/markdown + +

    + + attrs + +

    + + +*attrs* is the Python package that will bring back the **joy** of **writing classes** by relieving you from the drudgery of implementing object protocols (aka [dunder methods](https://www.attrs.org/en/latest/glossary.html#term-dunder-methods)). +[Trusted by NASA](https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/personalizing-your-profile#list-of-qualifying-repositories-for-mars-2020-helicopter-contributor-achievement) for Mars missions since 2020! + +Its main goal is to help you to write **concise** and **correct** software without slowing down your code. + + +## Sponsors + +*attrs* would not be possible without our [amazing sponsors](https://github.com/sponsors/hynek). +Especially those generously supporting us at the *The Organization* tier and higher: + + + +

    + + + + + + + + +

    + + + +

    + Please consider joining them to help make attrs’s maintenance more sustainable! +

    + + + +## Example + +*attrs* gives you a class decorator and a way to declaratively define the attributes on that class: + + + +```pycon +>>> from attrs import asdict, define, make_class, Factory + +>>> @define +... class SomeClass: +... a_number: int = 42 +... list_of_numbers: list[int] = Factory(list) +... +... def hard_math(self, another_number): +... return self.a_number + sum(self.list_of_numbers) * another_number + + +>>> sc = SomeClass(1, [1, 2, 3]) +>>> sc +SomeClass(a_number=1, list_of_numbers=[1, 2, 3]) + +>>> sc.hard_math(3) +19 +>>> sc == SomeClass(1, [1, 2, 3]) +True +>>> sc != SomeClass(2, [3, 2, 1]) +True + +>>> asdict(sc) +{'a_number': 1, 'list_of_numbers': [1, 2, 3]} + +>>> SomeClass() +SomeClass(a_number=42, list_of_numbers=[]) + +>>> C = make_class("C", ["a", "b"]) +>>> C("foo", "bar") +C(a='foo', b='bar') +``` + +After *declaring* your attributes, *attrs* gives you: + +- a concise and explicit overview of the class's attributes, +- a nice human-readable `__repr__`, +- equality-checking methods, +- an initializer, +- and much more, + +*without* writing dull boilerplate code again and again and *without* runtime performance penalties. + +--- + +This example uses *attrs*'s modern APIs that have been introduced in version 20.1.0, and the *attrs* package import name that has been added in version 21.3.0. +The classic APIs (`@attr.s`, `attr.ib`, plus their serious-business aliases) and the `attr` package import name will remain **indefinitely**. + +Check out [*On The Core API Names*](https://www.attrs.org/en/latest/names.html) for an in-depth explanation! + + +### Hate Type Annotations!? + +No problem! +Types are entirely **optional** with *attrs*. +Simply assign `attrs.field()` to the attributes instead of annotating them with types: + +```python +from attrs import define, field + +@define +class SomeClass: + a_number = field(default=42) + list_of_numbers = field(factory=list) +``` + + +## Data Classes + +On the tin, *attrs* might remind you of `dataclasses` (and indeed, `dataclasses` [are a descendant](https://hynek.me/articles/import-attrs/) of *attrs*). +In practice it does a lot more and is more flexible. +For instance, it allows you to define [special handling of NumPy arrays for equality checks](https://www.attrs.org/en/stable/comparison.html#customization), allows more ways to [plug into the initialization process](https://www.attrs.org/en/stable/init.html#hooking-yourself-into-initialization), has a replacement for `__init_subclass__`, and allows for stepping through the generated methods using a debugger. + +For more details, please refer to our [comparison page](https://www.attrs.org/en/stable/why.html#data-classes), but generally speaking, we are more likely to commit crimes against nature to make things work that one would expect to work, but that are quite complicated in practice. + + +## Project Information + +- [**Changelog**](https://www.attrs.org/en/stable/changelog.html) +- [**Documentation**](https://www.attrs.org/) +- [**PyPI**](https://pypi.org/project/attrs/) +- [**Source Code**](https://github.com/python-attrs/attrs) +- [**Contributing**](https://github.com/python-attrs/attrs/blob/main/.github/CONTRIBUTING.md) +- [**Third-party Extensions**](https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs) +- **Get Help**: use the `python-attrs` tag on [Stack Overflow](https://stackoverflow.com/questions/tagged/python-attrs) + + +### *attrs* for Enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of *attrs* and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. +Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. +[Learn more](https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek). + +## Release Information + +### Deprecations + +- Given the amount of warnings raised in the broader ecosystem, we've decided to only soft-deprecate the *hash* argument to `@define` / `@attr.s`. + Please don't use it in new code, but we don't intend to remove it anymore. + [#1330](https://github.com/python-attrs/attrs/issues/1330) + + +### Changes + +- `attrs.converters.pipe()` (and its syntactic sugar of passing a list for `attrs.field()`'s / `attr.ib()`'s *converter* argument) works again when passing `attrs.setters.convert` to *on_setattr* (which is default for `attrs.define`). + [#1328](https://github.com/python-attrs/attrs/issues/1328) +- Restored support for PEP [649](https://peps.python.org/pep-0649/) / [749](https://peps.python.org/pep-0749/)-implementing Pythons -- currently 3.14-dev. + [#1329](https://github.com/python-attrs/attrs/issues/1329) + + + +--- + +[Full changelog →](https://www.attrs.org/en/stable/changelog.html) diff --git a/env/Lib/site-packages/attrs-24.2.0.dist-info/RECORD b/env/Lib/site-packages/attrs-24.2.0.dist-info/RECORD new file mode 100644 index 0000000..f4876cb --- /dev/null +++ b/env/Lib/site-packages/attrs-24.2.0.dist-info/RECORD @@ -0,0 +1,55 @@ +attr/__init__.py,sha256=l8Ewh5KZE7CCY0i1iDfSCnFiUTIkBVoqsXjX9EZnIVA,2087 +attr/__init__.pyi,sha256=aTVHBPX6krCGvbQvOl_UKqEzmi2HFsaIVm2WKmAiqVs,11434 +attr/__pycache__/__init__.cpython-311.pyc,, +attr/__pycache__/_cmp.cpython-311.pyc,, +attr/__pycache__/_compat.cpython-311.pyc,, +attr/__pycache__/_config.cpython-311.pyc,, +attr/__pycache__/_funcs.cpython-311.pyc,, +attr/__pycache__/_make.cpython-311.pyc,, +attr/__pycache__/_next_gen.cpython-311.pyc,, +attr/__pycache__/_version_info.cpython-311.pyc,, +attr/__pycache__/converters.cpython-311.pyc,, +attr/__pycache__/exceptions.cpython-311.pyc,, +attr/__pycache__/filters.cpython-311.pyc,, +attr/__pycache__/setters.cpython-311.pyc,, +attr/__pycache__/validators.cpython-311.pyc,, +attr/_cmp.py,sha256=3umHiBtgsEYtvNP_8XrQwTCdFoZIX4DEur76N-2a3X8,4123 +attr/_cmp.pyi,sha256=U-_RU_UZOyPUEQzXE6RMYQQcjkZRY25wTH99sN0s7MM,368 +attr/_compat.py,sha256=n2Uk3c-ywv0PkFfGlvqR7SzDXp4NOhWmNV_ZK6YfWoM,2958 +attr/_config.py,sha256=z81Vt-GeT_2taxs1XZfmHx9TWlSxjPb6eZH1LTGsS54,843 +attr/_funcs.py,sha256=SGDmNlED1TM3tgO9Ap2mfRfVI24XEAcrNQs7o2eBXHQ,17386 +attr/_make.py,sha256=BjENJz5eJoojJVbCoupWjXLLEZJ7VID89lisLbQUlmQ,91479 +attr/_next_gen.py,sha256=dhGb96VFg4kXBkS9Zdz1A2uxVJ99q_RT1hw3kLA9-uI,24630 +attr/_typing_compat.pyi,sha256=XDP54TUn-ZKhD62TOQebmzrwFyomhUCoGRpclb6alRA,469 +attr/_version_info.py,sha256=exSqb3b5E-fMSsgZAlEw9XcLpEgobPORCZpcaEglAM4,2121 +attr/_version_info.pyi,sha256=x_M3L3WuB7r_ULXAWjx959udKQ4HLB8l-hsc1FDGNvk,209 +attr/converters.py,sha256=vNa58pZi9V6uxBzl4t1QrHbQfkT4iRFAodyXe7lcgg0,3506 +attr/converters.pyi,sha256=mpDoVFO3Cpx8xYSSV0iZFl7IAHuoNBglxKfxHvLj_sY,410 +attr/exceptions.py,sha256=HRFq4iybmv7-DcZwyjl6M1euM2YeJVK_hFxuaBGAngI,1977 +attr/exceptions.pyi,sha256=zZq8bCUnKAy9mDtBEw42ZhPhAUIHoTKedDQInJD883M,539 +attr/filters.py,sha256=ZBiKWLp3R0LfCZsq7X11pn9WX8NslS2wXM4jsnLOGc8,1795 +attr/filters.pyi,sha256=3J5BG-dTxltBk1_-RuNRUHrv2qu1v8v4aDNAQ7_mifA,208 +attr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +attr/setters.py,sha256=faMQeiBo_nbXYnPaQ1pq8PXeA7Zr-uNsVsPMiKCmxhc,1619 +attr/setters.pyi,sha256=NnVkaFU1BB4JB8E4JuXyrzTUgvtMpj8p3wBdJY7uix4,584 +attr/validators.py,sha256=985eTP6RHyon61YEauMJgyNy1rEOhJWiSXMJgRxPtrQ,20045 +attr/validators.pyi,sha256=LjKf7AoXZfvGSfT3LRs61Qfln94konYyMUPoJJjOxK4,2502 +attrs-24.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +attrs-24.2.0.dist-info/METADATA,sha256=3Jgk4lr9Y1SAqAcwOLPN_mpW0wc6VOGm-yHt1LsPIHw,11524 +attrs-24.2.0.dist-info/RECORD,, +attrs-24.2.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87 +attrs-24.2.0.dist-info/licenses/LICENSE,sha256=iCEVyV38KvHutnFPjsbVy8q_Znyv-HKfQkINpj9xTp8,1109 +attrs/__init__.py,sha256=5FHo-EMFOX-g4ialSK4fwOjuoHzLISJDZCwoOl02Ty8,1071 +attrs/__init__.pyi,sha256=o3l92VsD9kHz8sldEtb_tllBTs3TeL-vIBMTxo2Zc_4,7703 +attrs/__pycache__/__init__.cpython-311.pyc,, +attrs/__pycache__/converters.cpython-311.pyc,, +attrs/__pycache__/exceptions.cpython-311.pyc,, +attrs/__pycache__/filters.cpython-311.pyc,, +attrs/__pycache__/setters.cpython-311.pyc,, +attrs/__pycache__/validators.cpython-311.pyc,, +attrs/converters.py,sha256=8kQljrVwfSTRu8INwEk8SI0eGrzmWftsT7rM0EqyohM,76 +attrs/exceptions.py,sha256=ACCCmg19-vDFaDPY9vFl199SPXCQMN_bENs4DALjzms,76 +attrs/filters.py,sha256=VOUMZug9uEU6dUuA0dF1jInUK0PL3fLgP0VBS5d-CDE,73 +attrs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +attrs/setters.py,sha256=eL1YidYQV3T2h9_SYIZSZR1FAcHGb1TuCTy0E0Lv2SU,73 +attrs/validators.py,sha256=xcy6wD5TtTkdCG1f4XWbocPSO0faBjk5IfVJfP6SUj0,76 diff --git a/env/Lib/site-packages/attrs-24.2.0.dist-info/WHEEL b/env/Lib/site-packages/attrs-24.2.0.dist-info/WHEEL new file mode 100644 index 0000000..cdd68a4 --- /dev/null +++ b/env/Lib/site-packages/attrs-24.2.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.25.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/env/Lib/site-packages/attrs-24.2.0.dist-info/licenses/LICENSE b/env/Lib/site-packages/attrs-24.2.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000..2bd6453 --- /dev/null +++ b/env/Lib/site-packages/attrs-24.2.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Hynek Schlawack and the attrs contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/env/Lib/site-packages/attrs/__init__.py b/env/Lib/site-packages/attrs/__init__.py new file mode 100644 index 0000000..963b197 --- /dev/null +++ b/env/Lib/site-packages/attrs/__init__.py @@ -0,0 +1,67 @@ +# SPDX-License-Identifier: MIT + +from attr import ( + NOTHING, + Attribute, + AttrsInstance, + Converter, + Factory, + _make_getattr, + assoc, + cmp_using, + define, + evolve, + field, + fields, + fields_dict, + frozen, + has, + make_class, + mutable, + resolve_types, + validate, +) +from attr._next_gen import asdict, astuple + +from . import converters, exceptions, filters, setters, validators + + +__all__ = [ + "__author__", + "__copyright__", + "__description__", + "__doc__", + "__email__", + "__license__", + "__title__", + "__url__", + "__version__", + "__version_info__", + "asdict", + "assoc", + "astuple", + "Attribute", + "AttrsInstance", + "cmp_using", + "Converter", + "converters", + "define", + "evolve", + "exceptions", + "Factory", + "field", + "fields_dict", + "fields", + "filters", + "frozen", + "has", + "make_class", + "mutable", + "NOTHING", + "resolve_types", + "setters", + "validate", + "validators", +] + +__getattr__ = _make_getattr(__name__) diff --git a/env/Lib/site-packages/attrs/__init__.pyi b/env/Lib/site-packages/attrs/__init__.pyi new file mode 100644 index 0000000..b2670de --- /dev/null +++ b/env/Lib/site-packages/attrs/__init__.pyi @@ -0,0 +1,252 @@ +import sys + +from typing import ( + Any, + Callable, + Mapping, + Sequence, + overload, + TypeVar, +) + +# Because we need to type our own stuff, we have to make everything from +# attr explicitly public too. +from attr import __author__ as __author__ +from attr import __copyright__ as __copyright__ +from attr import __description__ as __description__ +from attr import __email__ as __email__ +from attr import __license__ as __license__ +from attr import __title__ as __title__ +from attr import __url__ as __url__ +from attr import __version__ as __version__ +from attr import __version_info__ as __version_info__ +from attr import assoc as assoc +from attr import Attribute as Attribute +from attr import AttrsInstance as AttrsInstance +from attr import cmp_using as cmp_using +from attr import converters as converters +from attr import Converter as Converter +from attr import evolve as evolve +from attr import exceptions as exceptions +from attr import Factory as Factory +from attr import fields as fields +from attr import fields_dict as fields_dict +from attr import filters as filters +from attr import has as has +from attr import make_class as make_class +from attr import NOTHING as NOTHING +from attr import resolve_types as resolve_types +from attr import setters as setters +from attr import validate as validate +from attr import validators as validators +from attr import attrib, asdict as asdict, astuple as astuple + +if sys.version_info >= (3, 11): + from typing import dataclass_transform +else: + from typing_extensions import dataclass_transform + +_T = TypeVar("_T") +_C = TypeVar("_C", bound=type) + +_EqOrderType = bool | Callable[[Any], Any] +_ValidatorType = Callable[[Any, "Attribute[_T]", _T], Any] +_ConverterType = Callable[[Any], Any] +_ReprType = Callable[[Any], str] +_ReprArgType = bool | _ReprType +_OnSetAttrType = Callable[[Any, "Attribute[Any]", Any], Any] +_OnSetAttrArgType = _OnSetAttrType | list[_OnSetAttrType] | setters._NoOpType +_FieldTransformer = Callable[ + [type, list["Attribute[Any]"]], list["Attribute[Any]"] +] +# FIXME: in reality, if multiple validators are passed they must be in a list +# or tuple, but those are invariant and so would prevent subtypes of +# _ValidatorType from working when passed in a list or tuple. +_ValidatorArgType = _ValidatorType[_T] | Sequence[_ValidatorType[_T]] + +@overload +def field( + *, + default: None = ..., + validator: None = ..., + repr: _ReprArgType = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + converter: None = ..., + factory: None = ..., + kw_only: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., + type: type | None = ..., +) -> Any: ... + +# This form catches an explicit None or no default and infers the type from the +# other arguments. +@overload +def field( + *, + default: None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + converter: _ConverterType | Converter[Any, _T] | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., + type: type | None = ..., +) -> _T: ... + +# This form catches an explicit default argument. +@overload +def field( + *, + default: _T, + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + converter: _ConverterType | Converter[Any, _T] | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., + type: type | None = ..., +) -> _T: ... + +# This form covers type=non-Type: e.g. forward references (str), Any +@overload +def field( + *, + default: _T | None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + converter: _ConverterType | Converter[Any, _T] | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., + type: type | None = ..., +) -> Any: ... +@overload +@dataclass_transform(field_specifiers=(attrib, field)) +def define( + maybe_cls: _C, + *, + these: dict[str, Any] | None = ..., + repr: bool = ..., + unsafe_hash: bool | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + auto_detect: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., +) -> _C: ... +@overload +@dataclass_transform(field_specifiers=(attrib, field)) +def define( + maybe_cls: None = ..., + *, + these: dict[str, Any] | None = ..., + repr: bool = ..., + unsafe_hash: bool | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + auto_detect: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., +) -> Callable[[_C], _C]: ... + +mutable = define + +@overload +@dataclass_transform(frozen_default=True, field_specifiers=(attrib, field)) +def frozen( + maybe_cls: _C, + *, + these: dict[str, Any] | None = ..., + repr: bool = ..., + unsafe_hash: bool | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + auto_detect: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., +) -> _C: ... +@overload +@dataclass_transform(frozen_default=True, field_specifiers=(attrib, field)) +def frozen( + maybe_cls: None = ..., + *, + these: dict[str, Any] | None = ..., + repr: bool = ..., + unsafe_hash: bool | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + auto_detect: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., +) -> Callable[[_C], _C]: ... diff --git a/env/Lib/site-packages/attrs/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/attrs/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..86a70ec Binary files /dev/null and b/env/Lib/site-packages/attrs/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attrs/__pycache__/converters.cpython-311.pyc b/env/Lib/site-packages/attrs/__pycache__/converters.cpython-311.pyc new file mode 100644 index 0000000..e157c92 Binary files /dev/null and b/env/Lib/site-packages/attrs/__pycache__/converters.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attrs/__pycache__/exceptions.cpython-311.pyc b/env/Lib/site-packages/attrs/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000..db6153c Binary files /dev/null and b/env/Lib/site-packages/attrs/__pycache__/exceptions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attrs/__pycache__/filters.cpython-311.pyc b/env/Lib/site-packages/attrs/__pycache__/filters.cpython-311.pyc new file mode 100644 index 0000000..57e1aa4 Binary files /dev/null and b/env/Lib/site-packages/attrs/__pycache__/filters.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attrs/__pycache__/setters.cpython-311.pyc b/env/Lib/site-packages/attrs/__pycache__/setters.cpython-311.pyc new file mode 100644 index 0000000..f6caa89 Binary files /dev/null and b/env/Lib/site-packages/attrs/__pycache__/setters.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attrs/__pycache__/validators.cpython-311.pyc b/env/Lib/site-packages/attrs/__pycache__/validators.cpython-311.pyc new file mode 100644 index 0000000..cab9246 Binary files /dev/null and b/env/Lib/site-packages/attrs/__pycache__/validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/attrs/converters.py b/env/Lib/site-packages/attrs/converters.py new file mode 100644 index 0000000..7821f6c --- /dev/null +++ b/env/Lib/site-packages/attrs/converters.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.converters import * # noqa: F403 diff --git a/env/Lib/site-packages/attrs/exceptions.py b/env/Lib/site-packages/attrs/exceptions.py new file mode 100644 index 0000000..3323f9d --- /dev/null +++ b/env/Lib/site-packages/attrs/exceptions.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.exceptions import * # noqa: F403 diff --git a/env/Lib/site-packages/attrs/filters.py b/env/Lib/site-packages/attrs/filters.py new file mode 100644 index 0000000..3080f48 --- /dev/null +++ b/env/Lib/site-packages/attrs/filters.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.filters import * # noqa: F403 diff --git a/env/Lib/site-packages/attrs/py.typed b/env/Lib/site-packages/attrs/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/attrs/setters.py b/env/Lib/site-packages/attrs/setters.py new file mode 100644 index 0000000..f3d73bb --- /dev/null +++ b/env/Lib/site-packages/attrs/setters.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.setters import * # noqa: F403 diff --git a/env/Lib/site-packages/attrs/validators.py b/env/Lib/site-packages/attrs/validators.py new file mode 100644 index 0000000..037e124 --- /dev/null +++ b/env/Lib/site-packages/attrs/validators.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.validators import * # noqa: F403 diff --git a/env/Lib/site-packages/frozenlist-1.4.1.dist-info/INSTALLER b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/frozenlist-1.4.1.dist-info/LICENSE b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/LICENSE new file mode 100644 index 0000000..7082a2d --- /dev/null +++ b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2013-2019 Nikolay Kim and Andrew Svetlov + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/env/Lib/site-packages/frozenlist-1.4.1.dist-info/METADATA b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/METADATA new file mode 100644 index 0000000..60603d5 --- /dev/null +++ b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/METADATA @@ -0,0 +1,420 @@ +Metadata-Version: 2.1 +Name: frozenlist +Version: 1.4.1 +Summary: A list-like structure which implements collections.abc.MutableSequence +Home-page: https://github.com/aio-libs/frozenlist +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache 2 +Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org +Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org +Project-URL: CI: Github Actions, https://github.com/aio-libs/frozenlist/actions +Project-URL: Code of Conduct, https://github.com/aio-libs/.github/blob/master/CODE_OF_CONDUCT.md +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/frozenlist +Project-URL: Docs: Changelog, https://github.com/aio-libs/frozenlist/blob/master/CHANGES.rst#changelog +Project-URL: Docs: RTD, https://frozenlist.aio-libs.org +Project-URL: GitHub: issues, https://github.com/aio-libs/frozenlist/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/frozenlist +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Requires-Python: >=3.8 +Description-Content-Type: text/x-rst +License-File: LICENSE + +frozenlist +========== + +.. image:: https://github.com/aio-libs/frozenlist/workflows/CI/badge.svg + :target: https://github.com/aio-libs/frozenlist/actions + :alt: GitHub status for master branch + +.. image:: https://codecov.io/gh/aio-libs/frozenlist/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/frozenlist + :alt: codecov.io status for master branch + +.. image:: https://img.shields.io/pypi/v/frozenlist.svg?logo=Python&logoColor=white + :target: https://pypi.org/project/frozenlist + :alt: frozenlist @ PyPI + +.. image:: https://readthedocs.org/projects/frozenlist/badge/?version=latest + :target: https://frozenlist.aio-libs.org + :alt: Read The Docs build status badge + +.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs:matrix.org + :alt: Matrix Room — #aio-libs:matrix.org + +.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs-space:matrix.org + :alt: Matrix Space — #aio-libs-space:matrix.org + +Introduction +------------ + +``frozenlist.FrozenList`` is a list-like structure which implements +``collections.abc.MutableSequence``. The list is *mutable* until ``FrozenList.freeze`` +is called, after which list modifications raise ``RuntimeError``: + + +>>> from frozenlist import FrozenList +>>> fl = FrozenList([17, 42]) +>>> fl.append('spam') +>>> fl.append('Vikings') +>>> fl + +>>> fl.freeze() +>>> fl + +>>> fl.frozen +True +>>> fl.append("Monty") +Traceback (most recent call last): + File "", line 1, in + File "frozenlist/_frozenlist.pyx", line 97, in frozenlist._frozenlist.FrozenList.append + self._check_frozen() + File "frozenlist/_frozenlist.pyx", line 19, in frozenlist._frozenlist.FrozenList._check_frozen + raise RuntimeError("Cannot modify frozen list.") +RuntimeError: Cannot modify frozen list. + + +FrozenList is also hashable, but only when frozen. Otherwise it also throws a RuntimeError: + + +>>> fl = FrozenList([17, 42, 'spam']) +>>> hash(fl) +Traceback (most recent call last): + File "", line 1, in + File "frozenlist/_frozenlist.pyx", line 111, in frozenlist._frozenlist.FrozenList.__hash__ + raise RuntimeError("Cannot hash unfrozen list.") +RuntimeError: Cannot hash unfrozen list. +>>> fl.freeze() +>>> hash(fl) +3713081631934410656 +>>> dictionary = {fl: 'Vikings'} # frozen fl can be a dict key +>>> dictionary +{: 'Vikings'} + + +Installation +------------ + +:: + + $ pip install frozenlist + +The library requires Python 3.8 or newer. + + +Documentation +------------- + +https://frozenlist.aio-libs.org + +Communication channels +---------------------- + +We have a *Matrix Space* `#aio-libs-space:matrix.org +`_ which is +also accessible via Gitter. + +Requirements +------------ + +- Python >= 3.8 + +License +------- + +``frozenlist`` is offered under the Apache 2 license. + +Source code +----------- + +The project is hosted on GitHub_ + +Please file an issue in the `bug tracker +`_ if you have found a bug +or have some suggestions to improve the library. + +.. _GitHub: https://github.com/aio-libs/frozenlist + +========= +Changelog +========= + +.. + You should *NOT* be adding new change log entries to this file, this + file is managed by towncrier. You *may* edit previous change logs to + fix problems like typo corrections or such. + To add a new change log entry, please see + https://pip.pypa.io/en/latest/development/contributing/#news-entries + we named the news folder "changes". + + WARNING: Don't drop the next directive! + +.. towncrier release notes start + +1.4.1 (2023-12-15) +================== + +Packaging updates and notes for downstreams +------------------------------------------- + +- Declared Python 3.12 and PyPy 3.8-3.10 supported officially + in the distribution package metadata. + + + *Related issues and pull requests on GitHub:* + `#553 `__. + +- Replaced the packaging is replaced from an old-fashioned ``setup.py`` to an + in-tree `PEP 517 `__ build backend -- by `@webknjaz `__. + + Whenever the end-users or downstream packagers need to build ``frozenlist`` + from source (a Git checkout or an sdist), they may pass a ``config_settings`` + flag ``pure-python``. If this flag is not set, a C-extension will be built + and included into the distribution. + + Here is how this can be done with ``pip``: + + .. code-block:: console + + $ python3 -m pip install . --config-settings=pure-python= + + This will also work with ``-e | --editable``. + + The same can be achieved via ``pypa/build``: + + .. code-block:: console + + $ python3 -m build --config-setting=pure-python= + + Adding ``-w | --wheel`` can force ``pypa/build`` produce a wheel from source + directly, as opposed to building an ``sdist`` and then building from it. + + + *Related issues and pull requests on GitHub:* + `#560 `__. + + +Contributor-facing changes +-------------------------- + +- It is now possible to request line tracing in Cython builds using the + ``with-cython-tracing`` `PEP 517 `__ config setting + -- `@webknjaz `__. + + This can be used in CI and development environment to measure coverage + on Cython modules, but is not normally useful to the end-users or + downstream packagers. + + Here's a usage example: + + .. code-block:: console + + $ python3 -Im pip install . --config-settings=with-cython-tracing=true + + For editable installs, this setting is on by default. Otherwise, it's + off unless requested explicitly. + + The following produces C-files required for the Cython coverage + plugin to map the measurements back to the PYX-files: + + .. code-block:: console + + $ python -Im pip install -e . + + Alternatively, the ``FROZENLIST_CYTHON_TRACING=1`` environment variable + can be set to do the same as the `PEP 517 `__ config setting. + + + *Related issues and pull requests on GitHub:* + `#560 `__. + +- Coverage collection has been implemented for the Cython modules + -- by `@webknjaz `__. + + It will also be reported to Codecov from any non-release CI jobs. + + + *Related issues and pull requests on GitHub:* + `#561 `__. + +- A step-by-step ``Release Guide`` guide has + been added, describing how to release *frozenlist* -- by `@webknjaz `__. + + This is primarily targeting the maintainers. + + + *Related issues and pull requests on GitHub:* + `#563 `__. + +- Detailed ``Contributing Guidelines`` on + authoring the changelog fragments have been published in the + documentation -- by `@webknjaz `__. + + + *Related issues and pull requests on GitHub:* + `#564 `__. + + +---- + + +1.4.0 (2023-07-12) +================== + +The published source distribution package became buildable +under Python 3.12. + + +---- + + +Bugfixes +-------- + +- Removed an unused ``typing.Tuple`` import + `#411 `_ + + +Deprecations and Removals +------------------------- + +- Dropped Python 3.7 support. + `#413 `_ + + +Misc +---- + +- `#410 `_, `#433 `_ + + +---- + + +1.3.3 (2022-11-08) +================== + +- Fixed CI runs when creating a new release, where new towncrier versions + fail when the current version section is already present. + + +---- + + +1.3.2 (2022-11-08) +================== + +Misc +---- + +- Updated the CI runs to better check for test results and to avoid deprecated syntax. `#327 `_ + + +---- + + +1.3.1 (2022-08-02) +================== + +The published source distribution package became buildable +under Python 3.11. + + +---- + + +1.3.0 (2022-01-18) +================== + +Bugfixes +-------- + +- Do not install C sources with binary distributions. + `#250 `_ + + +Deprecations and Removals +------------------------- + +- Dropped Python 3.6 support + `#274 `_ + + +---- + + +1.2.0 (2021-10-16) +================== + +Features +-------- + +- ``FrozenList`` now supports being used as a generic type as per PEP 585, e.g. ``frozen_int_list: FrozenList[int]`` (requires Python 3.9 or newer). + `#172 `_ +- Added support for Python 3.10. + `#227 `_ +- Started shipping platform-specific wheels with the ``musl`` tag targeting typical Alpine Linux runtimes. + `#227 `_ +- Started shipping platform-specific arm64 wheels for Apple Silicon. + `#227 `_ + + +---- + + +1.1.1 (2020-11-14) +================== + +Bugfixes +-------- + +- Provide x86 Windows wheels. + `#169 `_ + + +---- + + +1.1.0 (2020-10-13) +================== + +Features +-------- + +- Add support for hashing of a frozen list. + `#136 `_ + +- Support Python 3.8 and 3.9. + +- Provide wheels for ``aarch64``, ``i686``, ``ppc64le``, ``s390x`` architectures on + Linux as well as ``x86_64``. + + +---- + + +1.0.0 (2019-11-09) +================== + +Deprecations and Removals +------------------------- + +- Dropped support for Python 3.5; only 3.6, 3.7 and 3.8 are supported going forward. + `#24 `_ diff --git a/env/Lib/site-packages/frozenlist-1.4.1.dist-info/RECORD b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/RECORD new file mode 100644 index 0000000..6a206e6 --- /dev/null +++ b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/RECORD @@ -0,0 +1,12 @@ +frozenlist-1.4.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +frozenlist-1.4.1.dist-info/LICENSE,sha256=b9UkPpLdf5jsacesN3co50kFcJ_1J6W_mNbQJjwE9bY,11332 +frozenlist-1.4.1.dist-info/METADATA,sha256=WdGawzRX-kmYknJIJ9gpGgcerMabLYAsSKg62FF8258,12556 +frozenlist-1.4.1.dist-info/RECORD,, +frozenlist-1.4.1.dist-info/WHEEL,sha256=badvNS-y9fEq0X-qzdZYvql_JFjI7Xfw-wR8FsjoK0I,102 +frozenlist-1.4.1.dist-info/top_level.txt,sha256=jivtxsPXA3nK3WBWW2LW5Mtu_GHt8UZA13NeCs2cKuA,11 +frozenlist/__init__.py,sha256=hrSQhfujMaz1BWlHfwuVFrPD02-pCK7jG4e9FaCZCmM,2316 +frozenlist/__init__.pyi,sha256=vMEoES1xGegPtVXoCi9XydEeHsyuIq-KdeXwP5PdsaA,1470 +frozenlist/__pycache__/__init__.cpython-311.pyc,, +frozenlist/_frozenlist.cp311-win_amd64.pyd,sha256=D3U4RBwWaCSGGO4V0RQUzmhkLCy90WNrkD7O-s-IZS0,86016 +frozenlist/_frozenlist.pyx,sha256=9V4Z1En6TZwgFD26d-sjxyhUzUm338H1Qiz4-i5ukv0,2983 +frozenlist/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7 diff --git a/env/Lib/site-packages/frozenlist-1.4.1.dist-info/WHEEL b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/WHEEL new file mode 100644 index 0000000..6d16045 --- /dev/null +++ b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/env/Lib/site-packages/frozenlist-1.4.1.dist-info/top_level.txt b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/top_level.txt new file mode 100644 index 0000000..52f13fc --- /dev/null +++ b/env/Lib/site-packages/frozenlist-1.4.1.dist-info/top_level.txt @@ -0,0 +1 @@ +frozenlist diff --git a/env/Lib/site-packages/frozenlist/__init__.py b/env/Lib/site-packages/frozenlist/__init__.py new file mode 100644 index 0000000..c0f7136 --- /dev/null +++ b/env/Lib/site-packages/frozenlist/__init__.py @@ -0,0 +1,95 @@ +import os +import sys +import types +from collections.abc import MutableSequence +from functools import total_ordering +from typing import Type + +__version__ = "1.4.1" + +__all__ = ("FrozenList", "PyFrozenList") # type: Tuple[str, ...] + + +NO_EXTENSIONS = bool(os.environ.get("FROZENLIST_NO_EXTENSIONS")) # type: bool + + +@total_ordering +class FrozenList(MutableSequence): + __slots__ = ("_frozen", "_items") + + if sys.version_info >= (3, 9): + __class_getitem__ = classmethod(types.GenericAlias) + else: + + @classmethod + def __class_getitem__(cls: Type["FrozenList"]) -> Type["FrozenList"]: + return cls + + def __init__(self, items=None): + self._frozen = False + if items is not None: + items = list(items) + else: + items = [] + self._items = items + + @property + def frozen(self): + return self._frozen + + def freeze(self): + self._frozen = True + + def __getitem__(self, index): + return self._items[index] + + def __setitem__(self, index, value): + if self._frozen: + raise RuntimeError("Cannot modify frozen list.") + self._items[index] = value + + def __delitem__(self, index): + if self._frozen: + raise RuntimeError("Cannot modify frozen list.") + del self._items[index] + + def __len__(self): + return self._items.__len__() + + def __iter__(self): + return self._items.__iter__() + + def __reversed__(self): + return self._items.__reversed__() + + def __eq__(self, other): + return list(self) == other + + def __le__(self, other): + return list(self) <= other + + def insert(self, pos, item): + if self._frozen: + raise RuntimeError("Cannot modify frozen list.") + self._items.insert(pos, item) + + def __repr__(self): + return f"" + + def __hash__(self): + if self._frozen: + return hash(tuple(self)) + else: + raise RuntimeError("Cannot hash unfrozen list.") + + +PyFrozenList = FrozenList + + +if not NO_EXTENSIONS: + try: + from ._frozenlist import FrozenList as CFrozenList # type: ignore + except ImportError: # pragma: no cover + pass + else: + FrozenList = CFrozenList # type: ignore diff --git a/env/Lib/site-packages/frozenlist/__init__.pyi b/env/Lib/site-packages/frozenlist/__init__.pyi new file mode 100644 index 0000000..ae803ef --- /dev/null +++ b/env/Lib/site-packages/frozenlist/__init__.pyi @@ -0,0 +1,47 @@ +from typing import ( + Generic, + Iterable, + Iterator, + List, + MutableSequence, + Optional, + TypeVar, + Union, + overload, +) + +_T = TypeVar("_T") +_Arg = Union[List[_T], Iterable[_T]] + +class FrozenList(MutableSequence[_T], Generic[_T]): + def __init__(self, items: Optional[_Arg[_T]] = None) -> None: ... + @property + def frozen(self) -> bool: ... + def freeze(self) -> None: ... + @overload + def __getitem__(self, i: int) -> _T: ... + @overload + def __getitem__(self, s: slice) -> FrozenList[_T]: ... + @overload + def __setitem__(self, i: int, o: _T) -> None: ... + @overload + def __setitem__(self, s: slice, o: Iterable[_T]) -> None: ... + @overload + def __delitem__(self, i: int) -> None: ... + @overload + def __delitem__(self, i: slice) -> None: ... + def __len__(self) -> int: ... + def __iter__(self) -> Iterator[_T]: ... + def __reversed__(self) -> Iterator[_T]: ... + def __eq__(self, other: object) -> bool: ... + def __le__(self, other: FrozenList[_T]) -> bool: ... + def __ne__(self, other: object) -> bool: ... + def __lt__(self, other: FrozenList[_T]) -> bool: ... + def __ge__(self, other: FrozenList[_T]) -> bool: ... + def __gt__(self, other: FrozenList[_T]) -> bool: ... + def insert(self, pos: int, item: _T) -> None: ... + def __repr__(self) -> str: ... + def __hash__(self) -> int: ... + +# types for C accelerators are the same +CFrozenList = PyFrozenList = FrozenList diff --git a/env/Lib/site-packages/frozenlist/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/frozenlist/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..5b01b96 Binary files /dev/null and b/env/Lib/site-packages/frozenlist/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/frozenlist/_frozenlist.cp311-win_amd64.pyd b/env/Lib/site-packages/frozenlist/_frozenlist.cp311-win_amd64.pyd new file mode 100644 index 0000000..932a629 Binary files /dev/null and b/env/Lib/site-packages/frozenlist/_frozenlist.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/frozenlist/_frozenlist.pyx b/env/Lib/site-packages/frozenlist/_frozenlist.pyx new file mode 100644 index 0000000..9ee846c --- /dev/null +++ b/env/Lib/site-packages/frozenlist/_frozenlist.pyx @@ -0,0 +1,123 @@ +import sys +import types +from collections.abc import MutableSequence + + +cdef class FrozenList: + + if sys.version_info >= (3, 9): + __class_getitem__ = classmethod(types.GenericAlias) + else: + @classmethod + def __class_getitem__(cls): + return cls + + cdef readonly bint frozen + cdef list _items + + def __init__(self, items=None): + self.frozen = False + if items is not None: + items = list(items) + else: + items = [] + self._items = items + + cdef object _check_frozen(self): + if self.frozen: + raise RuntimeError("Cannot modify frozen list.") + + cdef inline object _fast_len(self): + return len(self._items) + + def freeze(self): + self.frozen = True + + def __getitem__(self, index): + return self._items[index] + + def __setitem__(self, index, value): + self._check_frozen() + self._items[index] = value + + def __delitem__(self, index): + self._check_frozen() + del self._items[index] + + def __len__(self): + return self._fast_len() + + def __iter__(self): + return self._items.__iter__() + + def __reversed__(self): + return self._items.__reversed__() + + def __richcmp__(self, other, op): + if op == 0: # < + return list(self) < other + if op == 1: # <= + return list(self) <= other + if op == 2: # == + return list(self) == other + if op == 3: # != + return list(self) != other + if op == 4: # > + return list(self) > other + if op == 5: # => + return list(self) >= other + + def insert(self, pos, item): + self._check_frozen() + self._items.insert(pos, item) + + def __contains__(self, item): + return item in self._items + + def __iadd__(self, items): + self._check_frozen() + self._items += list(items) + return self + + def index(self, item): + return self._items.index(item) + + def remove(self, item): + self._check_frozen() + self._items.remove(item) + + def clear(self): + self._check_frozen() + self._items.clear() + + def extend(self, items): + self._check_frozen() + self._items += list(items) + + def reverse(self): + self._check_frozen() + self._items.reverse() + + def pop(self, index=-1): + self._check_frozen() + return self._items.pop(index) + + def append(self, item): + self._check_frozen() + return self._items.append(item) + + def count(self, item): + return self._items.count(item) + + def __repr__(self): + return ''.format(self.frozen, + self._items) + + def __hash__(self): + if self.frozen: + return hash(tuple(self._items)) + else: + raise RuntimeError("Cannot hash unfrozen list.") + + +MutableSequence.register(FrozenList) diff --git a/env/Lib/site-packages/frozenlist/py.typed b/env/Lib/site-packages/frozenlist/py.typed new file mode 100644 index 0000000..f5642f7 --- /dev/null +++ b/env/Lib/site-packages/frozenlist/py.typed @@ -0,0 +1 @@ +Marker diff --git a/env/Lib/site-packages/logging-0.4.9.6.dist-info/INSTALLER b/env/Lib/site-packages/logging-0.4.9.6.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/logging-0.4.9.6.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/logging-0.4.9.6.dist-info/LICENSE b/env/Lib/site-packages/logging-0.4.9.6.dist-info/LICENSE new file mode 100644 index 0000000..f640612 --- /dev/null +++ b/env/Lib/site-packages/logging-0.4.9.6.dist-info/LICENSE @@ -0,0 +1,16 @@ +Copyright (C) 2001-2005 by Vinay Sajip. All Rights Reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Vinay Sajip +not be used in advertising or publicity pertaining to distribution +of the software without specific, written prior permission. + +VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL +VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN +AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/env/Lib/site-packages/logging-0.4.9.6.dist-info/METADATA b/env/Lib/site-packages/logging-0.4.9.6.dist-info/METADATA new file mode 100644 index 0000000..d60350b --- /dev/null +++ b/env/Lib/site-packages/logging-0.4.9.6.dist-info/METADATA @@ -0,0 +1,13 @@ +Metadata-Version: 2.1 +Name: logging +Version: 0.4.9.6 +Summary: A logging module for Python +Home-page: http://www.red-dove.com/python_logging.html +Author: Vinay Sajip +Author-email: vinay_sajip@red-dove.com +Maintainer: Vinay Sajip +Maintainer-email: vinay_sajip@red-dove.com +License: Copyright (C) 2001-2005 by Vinay Sajip. All Rights Reserved. See LICENSE for license. +License-File: LICENSE + +This module is intended to provide a standard error logging mechanism in Python as per PEP 282. diff --git a/env/Lib/site-packages/logging-0.4.9.6.dist-info/RECORD b/env/Lib/site-packages/logging-0.4.9.6.dist-info/RECORD new file mode 100644 index 0000000..fa93eb2 --- /dev/null +++ b/env/Lib/site-packages/logging-0.4.9.6.dist-info/RECORD @@ -0,0 +1,10 @@ +logging-0.4.9.6.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +logging-0.4.9.6.dist-info/LICENSE,sha256=jDH3McOJRccqR8zpa7TxggOa7J_Eqxsb8ccQrsWrPWI,976 +logging-0.4.9.6.dist-info/METADATA,sha256=XamZiq6Q-8gKsgcMAIyCtoLieQgYAP-TuxnFiIEcm-o,498 +logging-0.4.9.6.dist-info/RECORD,, +logging-0.4.9.6.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +logging-0.4.9.6.dist-info/WHEEL,sha256=Mdi9PDNwEZptOjTlUcAth7XJDFtKrHYaQMPulZeBCiQ,91 +logging-0.4.9.6.dist-info/top_level.txt,sha256=FIW2azcr5UzjdGze4ZuTamcDal2-CqKXgyxDBgqvAUY,8 +logging/__init__.py,sha256=6erb1Z4E8EwYvCk1NbK42hpMnYWQJEkWzofunY15Eso,46591 +logging/config.py,sha256=VtIiA8ojwWlLbOfydvKg8O6b8mzwnS6eJCu_W1h44Zs,12586 +logging/handlers.py,sha256=9_soecQk7mcyh6DO3tvaUF2XhSbeeIPXaWrdxFma6U0,37073 diff --git a/env/Lib/site-packages/logging-0.4.9.6.dist-info/REQUESTED b/env/Lib/site-packages/logging-0.4.9.6.dist-info/REQUESTED new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/logging-0.4.9.6.dist-info/WHEEL b/env/Lib/site-packages/logging-0.4.9.6.dist-info/WHEEL new file mode 100644 index 0000000..50e1e84 --- /dev/null +++ b/env/Lib/site-packages/logging-0.4.9.6.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (73.0.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/env/Lib/site-packages/logging-0.4.9.6.dist-info/top_level.txt b/env/Lib/site-packages/logging-0.4.9.6.dist-info/top_level.txt new file mode 100644 index 0000000..a694f50 --- /dev/null +++ b/env/Lib/site-packages/logging-0.4.9.6.dist-info/top_level.txt @@ -0,0 +1 @@ +logging diff --git a/env/Lib/site-packages/logging/__init__.py b/env/Lib/site-packages/logging/__init__.py new file mode 100644 index 0000000..0c23e82 --- /dev/null +++ b/env/Lib/site-packages/logging/__init__.py @@ -0,0 +1,1327 @@ +# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose and without fee is hereby granted, +# provided that the above copyright notice appear in all copies and that +# both that copyright notice and this permission notice appear in +# supporting documentation, and that the name of Vinay Sajip +# not be used in advertising or publicity pertaining to distribution +# of the software without specific, written prior permission. +# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL +# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +""" +Logging package for Python. Based on PEP 282 and comments thereto in +comp.lang.python, and influenced by Apache's log4j system. + +Should work under Python versions >= 1.5.2, except that source line +information is not available unless 'sys._getframe()' is. + +Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. + +To use, simply 'import logging' and log away! +""" + +import sys, os, types, time, string, cStringIO + +try: + import codecs +except ImportError: + codecs = None + +try: + import thread + import threading +except ImportError: + thread = None + +__author__ = "Vinay Sajip " +__status__ = "beta" +__version__ = "0.4.9.6" +__date__ = "02 March 2005" + +#--------------------------------------------------------------------------- +# Miscellaneous module data +#--------------------------------------------------------------------------- + +# +# _srcfile is used when walking the stack to check when we've got the first +# caller stack frame. +# +if string.lower(__file__[-4:]) in ['.pyc', '.pyo']: + _srcfile = __file__[:-4] + '.py' +else: + _srcfile = __file__ +_srcfile = os.path.normcase(_srcfile) + +# next bit filched from 1.5.2's inspect.py +def currentframe(): + """Return the frame object for the caller's stack frame.""" + try: + raise 'catch me' + except: + return sys.exc_traceback.tb_frame.f_back + +if hasattr(sys, '_getframe'): currentframe = sys._getframe +# done filching + +# _srcfile is only used in conjunction with sys._getframe(). +# To provide compatibility with older versions of Python, set _srcfile +# to None if _getframe() is not available; this value will prevent +# findCaller() from being called. +#if not hasattr(sys, "_getframe"): +# _srcfile = None + +# +#_startTime is used as the base when calculating the relative time of events +# +_startTime = time.time() + +# +#raiseExceptions is used to see if exceptions during handling should be +#propagated +# +raiseExceptions = 1 + +#--------------------------------------------------------------------------- +# Level related stuff +#--------------------------------------------------------------------------- +# +# Default levels and level names, these can be replaced with any positive set +# of values having corresponding names. There is a pseudo-level, NOTSET, which +# is only really there as a lower limit for user-defined levels. Handlers and +# loggers are initialized with NOTSET so that they will log all messages, even +# at user-defined levels. +# + +CRITICAL = 50 +FATAL = CRITICAL +ERROR = 40 +WARNING = 30 +WARN = WARNING +INFO = 20 +DEBUG = 10 +NOTSET = 0 + +_levelNames = { + CRITICAL : 'CRITICAL', + ERROR : 'ERROR', + WARNING : 'WARNING', + INFO : 'INFO', + DEBUG : 'DEBUG', + NOTSET : 'NOTSET', + 'CRITICAL' : CRITICAL, + 'ERROR' : ERROR, + 'WARN' : WARNING, + 'WARNING' : WARNING, + 'INFO' : INFO, + 'DEBUG' : DEBUG, + 'NOTSET' : NOTSET, +} + +def getLevelName(level): + """ + Return the textual representation of logging level 'level'. + + If the level is one of the predefined levels (CRITICAL, ERROR, WARNING, + INFO, DEBUG) then you get the corresponding string. If you have + associated levels with names using addLevelName then the name you have + associated with 'level' is returned. + + If a numeric value corresponding to one of the defined levels is passed + in, the corresponding string representation is returned. + + Otherwise, the string "Level %s" % level is returned. + """ + return _levelNames.get(level, ("Level %s" % level)) + +def addLevelName(level, levelName): + """ + Associate 'levelName' with 'level'. + + This is used when converting levels to text during message formatting. + """ + _acquireLock() + try: #unlikely to cause an exception, but you never know... + _levelNames[level] = levelName + _levelNames[levelName] = level + finally: + _releaseLock() + +#--------------------------------------------------------------------------- +# Thread-related stuff +#--------------------------------------------------------------------------- + +# +#_lock is used to serialize access to shared data structures in this module. +#This needs to be an RLock because fileConfig() creates Handlers and so +#might arbitrary user threads. Since Handler.__init__() updates the shared +#dictionary _handlers, it needs to acquire the lock. But if configuring, +#the lock would already have been acquired - so we need an RLock. +#The same argument applies to Loggers and Manager.loggerDict. +# +_lock = None + +def _acquireLock(): + """ + Acquire the module-level lock for serializing access to shared data. + + This should be released with _releaseLock(). + """ + global _lock + if (not _lock) and thread: + _lock = threading.RLock() + if _lock: + _lock.acquire() + +def _releaseLock(): + """ + Release the module-level lock acquired by calling _acquireLock(). + """ + if _lock: + _lock.release() + +#--------------------------------------------------------------------------- +# The logging record +#--------------------------------------------------------------------------- + +class LogRecord: + """ + A LogRecord instance represents an event being logged. + + LogRecord instances are created every time something is logged. They + contain all the information pertinent to the event being logged. The + main information passed in is in msg and args, which are combined + using str(msg) % args to create the message field of the record. The + record also includes information such as when the record was created, + the source line where the logging call was made, and any exception + information to be logged. + """ + def __init__(self, name, level, pathname, lineno, msg, args, exc_info): + """ + Initialize a logging record with interesting information. + """ + ct = time.time() + self.name = name + self.msg = msg + # + # The following statement allows passing of a dictionary as a sole + # argument, so that you can do something like + # logging.debug("a %(a)d b %(b)s", {'a':1, 'b':2}) + # Suggested by Stefan Behnel. + # Note that without the test for args[0], we get a problem because + # during formatting, we test to see if the arg is present using + # 'if self.args:'. If the event being logged is e.g. 'Value is %d' + # and if the passed arg fails 'if self.args:' then no formatting + # is done. For example, logger.warn('Value is %d', 0) would log + # 'Value is %d' instead of 'Value is 0'. + # For the use case of passing a dictionary, this should not be a + # problem. + if args and (len(args) == 1) and args[0] and (type(args[0]) == types.DictType): + args = args[0] + self.args = args + self.levelname = getLevelName(level) + self.levelno = level + self.pathname = pathname + try: + self.filename = os.path.basename(pathname) + self.module = os.path.splitext(self.filename)[0] + except: + self.filename = pathname + self.module = "Unknown module" + self.exc_info = exc_info + self.exc_text = None # used to cache the traceback text + self.lineno = lineno + self.created = ct + self.msecs = (ct - long(ct)) * 1000 + self.relativeCreated = (self.created - _startTime) * 1000 + if thread: + self.thread = thread.get_ident() + else: + self.thread = None + if hasattr(os, 'getpid'): + self.process = os.getpid() + else: + self.process = None + + def __str__(self): + return ''%(self.name, self.levelno, + self.pathname, self.lineno, self.msg) + + def getMessage(self): + """ + Return the message for this LogRecord. + + Return the message for this LogRecord after merging any user-supplied + arguments with the message. + """ + if not hasattr(types, "UnicodeType"): #if no unicode support... + msg = str(self.msg) + else: + try: + msg = str(self.msg) + except UnicodeError: + msg = self.msg #Defer encoding till later + if self.args: + msg = msg % self.args + return msg + +def makeLogRecord(dict): + """ + Make a LogRecord whose attributes are defined by the specified dictionary, + This function is useful for converting a logging event received over + a socket connection (which is sent as a dictionary) into a LogRecord + instance. + """ + rv = LogRecord(None, None, "", 0, "", (), None) + rv.__dict__.update(dict) + return rv + +#--------------------------------------------------------------------------- +# Formatter classes and functions +#--------------------------------------------------------------------------- + +class Formatter: + """ + Formatter instances are used to convert a LogRecord to text. + + Formatters need to know how a LogRecord is constructed. They are + responsible for converting a LogRecord to (usually) a string which can + be interpreted by either a human or an external system. The base Formatter + allows a formatting string to be specified. If none is supplied, the + default value of "%s(message)\\n" is used. + + The Formatter can be initialized with a format string which makes use of + knowledge of the LogRecord attributes - e.g. the default value mentioned + above makes use of the fact that the user's message and arguments are pre- + formatted into a LogRecord's message attribute. Currently, the useful + attributes in a LogRecord are described by: + + %(name)s Name of the logger (logging channel) + %(levelno)s Numeric logging level for the message (DEBUG, INFO, + WARNING, ERROR, CRITICAL) + %(levelname)s Text logging level for the message ("DEBUG", "INFO", + "WARNING", "ERROR", "CRITICAL") + %(pathname)s Full pathname of the source file where the logging + call was issued (if available) + %(filename)s Filename portion of pathname + %(module)s Module (name portion of filename) + %(lineno)d Source line number where the logging call was issued + (if available) + %(created)f Time when the LogRecord was created (time.time() + return value) + %(asctime)s Textual time when the LogRecord was created + %(msecs)d Millisecond portion of the creation time + %(relativeCreated)d Time in milliseconds when the LogRecord was created, + relative to the time the logging module was loaded + (typically at application startup time) + %(thread)d Thread ID (if available) + %(process)d Process ID (if available) + %(message)s The result of record.getMessage(), computed just as + the record is emitted + """ + + converter = time.localtime + + def __init__(self, fmt=None, datefmt=None): + """ + Initialize the formatter with specified format strings. + + Initialize the formatter either with the specified format string, or a + default as described above. Allow for specialized date formatting with + the optional datefmt argument (if omitted, you get the ISO8601 format). + """ + if fmt: + self._fmt = fmt + else: + self._fmt = "%(message)s" + self.datefmt = datefmt + + def formatTime(self, record, datefmt=None): + """ + Return the creation time of the specified LogRecord as formatted text. + + This method should be called from format() by a formatter which + wants to make use of a formatted time. This method can be overridden + in formatters to provide for any specific requirement, but the + basic behaviour is as follows: if datefmt (a string) is specified, + it is used with time.strftime() to format the creation time of the + record. Otherwise, the ISO8601 format is used. The resulting + string is returned. This function uses a user-configurable function + to convert the creation time to a tuple. By default, time.localtime() + is used; to change this for a particular formatter instance, set the + 'converter' attribute to a function with the same signature as + time.localtime() or time.gmtime(). To change it for all formatters, + for example if you want all logging times to be shown in GMT, + set the 'converter' attribute in the Formatter class. + """ + ct = self.converter(record.created) + if datefmt: + s = time.strftime(datefmt, ct) + else: + t = time.strftime("%Y-%m-%d %H:%M:%S", ct) + s = "%s,%03d" % (t, record.msecs) + return s + + def formatException(self, ei): + """ + Format and return the specified exception information as a string. + + This default implementation just uses + traceback.print_exception() + """ + import traceback + sio = cStringIO.StringIO() + traceback.print_exception(ei[0], ei[1], ei[2], None, sio) + s = sio.getvalue() + sio.close() + if s[-1] == "\n": + s = s[:-1] + return s + + def format(self, record): + """ + Format the specified record as text. + + The record's attribute dictionary is used as the operand to a + string formatting operation which yields the returned string. + Before formatting the dictionary, a couple of preparatory steps + are carried out. The message attribute of the record is computed + using LogRecord.getMessage(). If the formatting string contains + "%(asctime)", formatTime() is called to format the event time. + If there is exception information, it is formatted using + formatException() and appended to the message. + """ + record.message = record.getMessage() + if string.find(self._fmt,"%(asctime)") >= 0: + record.asctime = self.formatTime(record, self.datefmt) + s = self._fmt % record.__dict__ + if record.exc_info: + # Cache the traceback text to avoid converting it multiple times + # (it's constant anyway) + if not record.exc_text: + record.exc_text = self.formatException(record.exc_info) + if record.exc_text: + if s[-1] != "\n": + s = s + "\n" + s = s + record.exc_text + return s + +# +# The default formatter to use when no other is specified +# +_defaultFormatter = Formatter() + +class BufferingFormatter: + """ + A formatter suitable for formatting a number of records. + """ + def __init__(self, linefmt=None): + """ + Optionally specify a formatter which will be used to format each + individual record. + """ + if linefmt: + self.linefmt = linefmt + else: + self.linefmt = _defaultFormatter + + def formatHeader(self, records): + """ + Return the header string for the specified records. + """ + return "" + + def formatFooter(self, records): + """ + Return the footer string for the specified records. + """ + return "" + + def format(self, records): + """ + Format the specified records and return the result as a string. + """ + rv = "" + if len(records) > 0: + rv = rv + self.formatHeader(records) + for record in records: + rv = rv + self.linefmt.format(record) + rv = rv + self.formatFooter(records) + return rv + +#--------------------------------------------------------------------------- +# Filter classes and functions +#--------------------------------------------------------------------------- + +class Filter: + """ + Filter instances are used to perform arbitrary filtering of LogRecords. + + Loggers and Handlers can optionally use Filter instances to filter + records as desired. The base filter class only allows events which are + below a certain point in the logger hierarchy. For example, a filter + initialized with "A.B" will allow events logged by loggers "A.B", + "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If + initialized with the empty string, all events are passed. + """ + def __init__(self, name=''): + """ + Initialize a filter. + + Initialize with the name of the logger which, together with its + children, will have its events allowed through the filter. If no + name is specified, allow every event. + """ + self.name = name + self.nlen = len(name) + + def filter(self, record): + """ + Determine if the specified record is to be logged. + + Is the specified record to be logged? Returns 0 for no, nonzero for + yes. If deemed appropriate, the record may be modified in-place. + """ + if self.nlen == 0: + return 1 + elif self.name == record.name: + return 1 + elif string.find(record.name, self.name, 0, self.nlen) != 0: + return 0 + return (record.name[self.nlen] == ".") + +class Filterer: + """ + A base class for loggers and handlers which allows them to share + common code. + """ + def __init__(self): + """ + Initialize the list of filters to be an empty list. + """ + self.filters = [] + + def addFilter(self, filter): + """ + Add the specified filter to this handler. + """ + if not (filter in self.filters): + self.filters.append(filter) + + def removeFilter(self, filter): + """ + Remove the specified filter from this handler. + """ + if filter in self.filters: + self.filters.remove(filter) + + def filter(self, record): + """ + Determine if a record is loggable by consulting all the filters. + + The default is to allow the record to be logged; any filter can veto + this and the record is then dropped. Returns a zero value if a record + is to be dropped, else non-zero. + """ + rv = 1 + for f in self.filters: + if not f.filter(record): + rv = 0 + break + return rv + +#--------------------------------------------------------------------------- +# Handler classes and functions +#--------------------------------------------------------------------------- + +_handlers = {} #repository of handlers (for flushing when shutdown called) + +class Handler(Filterer): + """ + Handler instances dispatch logging events to specific destinations. + + The base handler class. Acts as a placeholder which defines the Handler + interface. Handlers can optionally use Formatter instances to format + records as desired. By default, no formatter is specified; in this case, + the 'raw' message as determined by record.message is logged. + """ + def __init__(self, level=NOTSET): + """ + Initializes the instance - basically setting the formatter to None + and the filter list to empty. + """ + Filterer.__init__(self) + self.level = level + self.formatter = None + #get the module data lock, as we're updating a shared structure. + _acquireLock() + try: #unlikely to raise an exception, but you never know... + _handlers[self] = 1 + finally: + _releaseLock() + self.createLock() + + def createLock(self): + """ + Acquire a thread lock for serializing access to the underlying I/O. + """ + if thread: + self.lock = thread.allocate_lock() + else: + self.lock = None + + def acquire(self): + """ + Acquire the I/O thread lock. + """ + if self.lock: + self.lock.acquire() + + def release(self): + """ + Release the I/O thread lock. + """ + if self.lock: + self.lock.release() + + def setLevel(self, level): + """ + Set the logging level of this handler. + """ + self.level = level + + def format(self, record): + """ + Format the specified record. + + If a formatter is set, use it. Otherwise, use the default formatter + for the module. + """ + if self.formatter: + fmt = self.formatter + else: + fmt = _defaultFormatter + return fmt.format(record) + + def emit(self, record): + """ + Do whatever it takes to actually log the specified logging record. + + This version is intended to be implemented by subclasses and so + raises a NotImplementedError. + """ + raise NotImplementedError, 'emit must be implemented '\ + 'by Handler subclasses' + + def handle(self, record): + """ + Conditionally emit the specified logging record. + + Emission depends on filters which may have been added to the handler. + Wrap the actual emission of the record with acquisition/release of + the I/O thread lock. Returns whether the filter passed the record for + emission. + """ + rv = self.filter(record) + if rv: + self.acquire() + try: + self.emit(record) + finally: + self.release() + return rv + + def setFormatter(self, fmt): + """ + Set the formatter for this handler. + """ + self.formatter = fmt + + def flush(self): + """ + Ensure all logging output has been flushed. + + This version does nothing and is intended to be implemented by + subclasses. + """ + pass + + def close(self): + """ + Tidy up any resources used by the handler. + + This version does removes the handler from an internal list + of handlers which is closed when shutdown() is called. Subclasses + should ensure that this gets called from overridden close() + methods. + """ + #get the module data lock, as we're updating a shared structure. + _acquireLock() + try: #unlikely to raise an exception, but you never know... + del _handlers[self] + finally: + _releaseLock() + + def handleError(self, record): + """ + Handle errors which occur during an emit() call. + + This method should be called from handlers when an exception is + encountered during an emit() call. If raiseExceptions is false, + exceptions get silently ignored. This is what is mostly wanted + for a logging system - most users will not care about errors in + the logging system, they are more interested in application errors. + You could, however, replace this with a custom handler if you wish. + The record which was being processed is passed in to this method. + """ + if raiseExceptions: + import traceback + ei = sys.exc_info() + traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr) + del ei + +class StreamHandler(Handler): + """ + A handler class which writes logging records, appropriately formatted, + to a stream. Note that this class does not close the stream, as + sys.stdout or sys.stderr may be used. + """ + def __init__(self, strm=None): + """ + Initialize the handler. + + If strm is not specified, sys.stderr is used. + """ + Handler.__init__(self) + if not strm: + strm = sys.stderr + self.stream = strm + self.formatter = None + + def flush(self): + """ + Flushes the stream. + """ + self.stream.flush() + + def emit(self, record): + """ + Emit a record. + + If a formatter is specified, it is used to format the record. + The record is then written to the stream with a trailing newline + [N.B. this may be removed depending on feedback]. If exception + information is present, it is formatted using + traceback.print_exception and appended to the stream. + """ + try: + msg = self.format(record) + fs = "%s\n" + if not hasattr(types, "UnicodeType"): #if no unicode support... + self.stream.write(fs % msg) + else: + try: + self.stream.write(fs % msg) + except UnicodeError: + self.stream.write(fs % msg.encode("UTF-8")) + self.flush() + except: + self.handleError(record) + +class FileHandler(StreamHandler): + """ + A handler class which writes formatted logging records to disk files. + """ + def __init__(self, filename, mode='a', encoding=None): + """ + Open the specified file and use it as the stream for logging. + """ + if codecs is None: + encoding = None + if encoding is None: + stream = open(filename, mode) + else: + stream = codecs.open(filename, mode, encoding) + StreamHandler.__init__(self, stream) + #keep the absolute path, otherwise derived classes which use this + #may come a cropper when the current directory changes + self.baseFilename = os.path.abspath(filename) + self.mode = mode + + def close(self): + """ + Closes the stream. + """ + self.flush() + self.stream.close() + StreamHandler.close(self) + +#--------------------------------------------------------------------------- +# Manager classes and functions +#--------------------------------------------------------------------------- + +class PlaceHolder: + """ + PlaceHolder instances are used in the Manager logger hierarchy to take + the place of nodes for which no loggers have been defined. This class is + intended for internal use only and not as part of the public API. + """ + def __init__(self, alogger): + """ + Initialize with the specified logger being a child of this placeholder. + """ + self.loggers = [alogger] + + def append(self, alogger): + """ + Add the specified logger as a child of this placeholder. + """ + if alogger not in self.loggers: + self.loggers.append(alogger) + +# +# Determine which class to use when instantiating loggers. +# +_loggerClass = None + +def setLoggerClass(klass): + """ + Set the class to be used when instantiating a logger. The class should + define __init__() such that only a name argument is required, and the + __init__() should call Logger.__init__() + """ + if klass != Logger: + if not issubclass(klass, Logger): + raise TypeError, "logger not derived from logging.Logger: " + \ + klass.__name__ + global _loggerClass + _loggerClass = klass + +def getLoggerClass(): + """ + Return the class to be used when instantiating a logger. + """ + + return _loggerClass + +class Manager: + """ + There is [under normal circumstances] just one Manager instance, which + holds the hierarchy of loggers. + """ + def __init__(self, rootnode): + """ + Initialize the manager with the root node of the logger hierarchy. + """ + self.root = rootnode + self.disable = 0 + self.emittedNoHandlerWarning = 0 + self.loggerDict = {} + + def getLogger(self, name): + """ + Get a logger with the specified name (channel name), creating it + if it doesn't yet exist. This name is a dot-separated hierarchical + name, such as "a", "a.b", "a.b.c" or similar. + + If a PlaceHolder existed for the specified name [i.e. the logger + didn't exist but a child of it did], replace it with the created + logger and fix up the parent/child references which pointed to the + placeholder to now point to the logger. + """ + rv = None + _acquireLock() + try: + if self.loggerDict.has_key(name): + rv = self.loggerDict[name] + if isinstance(rv, PlaceHolder): + ph = rv + rv = _loggerClass(name) + rv.manager = self + self.loggerDict[name] = rv + self._fixupChildren(ph, rv) + self._fixupParents(rv) + else: + rv = _loggerClass(name) + rv.manager = self + self.loggerDict[name] = rv + self._fixupParents(rv) + finally: + _releaseLock() + return rv + + def _fixupParents(self, alogger): + """ + Ensure that there are either loggers or placeholders all the way + from the specified logger to the root of the logger hierarchy. + """ + name = alogger.name + i = string.rfind(name, ".") + rv = None + while (i > 0) and not rv: + substr = name[:i] + if not self.loggerDict.has_key(substr): + self.loggerDict[substr] = PlaceHolder(alogger) + else: + obj = self.loggerDict[substr] + if isinstance(obj, Logger): + rv = obj + else: + assert isinstance(obj, PlaceHolder) + obj.append(alogger) + i = string.rfind(name, ".", 0, i - 1) + if not rv: + rv = self.root + alogger.parent = rv + + def _fixupChildren(self, ph, alogger): + """ + Ensure that children of the placeholder ph are connected to the + specified logger. + """ + for c in ph.loggers: + if string.find(c.parent.name, alogger.name) <> 0: + alogger.parent = c.parent + c.parent = alogger + +#--------------------------------------------------------------------------- +# Logger classes and functions +#--------------------------------------------------------------------------- + +class Logger(Filterer): + """ + Instances of the Logger class represent a single logging channel. A + "logging channel" indicates an area of an application. Exactly how an + "area" is defined is up to the application developer. Since an + application can have any number of areas, logging channels are identified + by a unique string. Application areas can be nested (e.g. an area + of "input processing" might include sub-areas "read CSV files", "read + XLS files" and "read Gnumeric files"). To cater for this natural nesting, + channel names are organized into a namespace hierarchy where levels are + separated by periods, much like the Java or Python package namespace. So + in the instance given above, channel names might be "input" for the upper + level, and "input.csv", "input.xls" and "input.gnu" for the sub-levels. + There is no arbitrary limit to the depth of nesting. + """ + def __init__(self, name, level=NOTSET): + """ + Initialize the logger with a name and an optional level. + """ + Filterer.__init__(self) + self.name = name + self.level = level + self.parent = None + self.propagate = 1 + self.handlers = [] + self.disabled = 0 + + def setLevel(self, level): + """ + Set the logging level of this logger. + """ + self.level = level + + def debug(self, msg, *args, **kwargs): + """ + Log 'msg % args' with severity 'DEBUG'. + + To pass exception information, use the keyword argument exc_info with + a true value, e.g. + + logger.debug("Houston, we have a %s", "thorny problem", exc_info=1) + """ + if self.manager.disable >= DEBUG: + return + if DEBUG >= self.getEffectiveLevel(): + apply(self._log, (DEBUG, msg, args), kwargs) + + def info(self, msg, *args, **kwargs): + """ + Log 'msg % args' with severity 'INFO'. + + To pass exception information, use the keyword argument exc_info with + a true value, e.g. + + logger.info("Houston, we have a %s", "interesting problem", exc_info=1) + """ + if self.manager.disable >= INFO: + return + if INFO >= self.getEffectiveLevel(): + apply(self._log, (INFO, msg, args), kwargs) + + def warning(self, msg, *args, **kwargs): + """ + Log 'msg % args' with severity 'WARNING'. + + To pass exception information, use the keyword argument exc_info with + a true value, e.g. + + logger.warning("Houston, we have a %s", "bit of a problem", exc_info=1) + """ + if self.manager.disable >= WARNING: + return + if self.isEnabledFor(WARNING): + apply(self._log, (WARNING, msg, args), kwargs) + + warn = warning + + def error(self, msg, *args, **kwargs): + """ + Log 'msg % args' with severity 'ERROR'. + + To pass exception information, use the keyword argument exc_info with + a true value, e.g. + + logger.error("Houston, we have a %s", "major problem", exc_info=1) + """ + if self.manager.disable >= ERROR: + return + if self.isEnabledFor(ERROR): + apply(self._log, (ERROR, msg, args), kwargs) + + def exception(self, msg, *args): + """ + Convenience method for logging an ERROR with exception information. + """ + apply(self.error, (msg,) + args, {'exc_info': 1}) + + def critical(self, msg, *args, **kwargs): + """ + Log 'msg % args' with severity 'CRITICAL'. + + To pass exception information, use the keyword argument exc_info with + a true value, e.g. + + logger.critical("Houston, we have a %s", "major disaster", exc_info=1) + """ + if self.manager.disable >= CRITICAL: + return + if CRITICAL >= self.getEffectiveLevel(): + apply(self._log, (CRITICAL, msg, args), kwargs) + + fatal = critical + + def log(self, level, msg, *args, **kwargs): + """ + Log 'msg % args' with the integer severity 'level'. + + To pass exception information, use the keyword argument exc_info with + a true value, e.g. + + logger.log(level, "We have a %s", "mysterious problem", exc_info=1) + """ + if type(level) != types.IntType: + if raiseExceptions: + raise TypeError, "level must be an integer" + else: + return + if self.manager.disable >= level: + return + if self.isEnabledFor(level): + apply(self._log, (level, msg, args), kwargs) + + def findCaller(self): + """ + Find the stack frame of the caller so that we can note the source + file name, line number and function name. + """ + f = currentframe().f_back + while 1: + co = f.f_code + filename = os.path.normcase(co.co_filename) + if filename == _srcfile: + f = f.f_back + continue + return filename, f.f_lineno, co.co_name + + def makeRecord(self, name, level, fn, lno, msg, args, exc_info): + """ + A factory method which can be overridden in subclasses to create + specialized LogRecords. + """ + return LogRecord(name, level, fn, lno, msg, args, exc_info) + + def _log(self, level, msg, args, exc_info=None): + """ + Low-level logging routine which creates a LogRecord and then calls + all the handlers of this logger to handle the record. + """ + if _srcfile: + fn, lno, func = self.findCaller() + else: + fn, lno, func = "(unknown file)", 0, "(unknown function)" + if exc_info: + if type(exc_info) != types.TupleType: + exc_info = sys.exc_info() + record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info) + self.handle(record) + + def handle(self, record): + """ + Call the handlers for the specified record. + + This method is used for unpickled records received from a socket, as + well as those created locally. Logger-level filtering is applied. + """ + if (not self.disabled) and self.filter(record): + self.callHandlers(record) + + def addHandler(self, hdlr): + """ + Add the specified handler to this logger. + """ + if not (hdlr in self.handlers): + self.handlers.append(hdlr) + + def removeHandler(self, hdlr): + """ + Remove the specified handler from this logger. + """ + if hdlr in self.handlers: + #hdlr.close() + self.handlers.remove(hdlr) + + def callHandlers(self, record): + """ + Pass a record to all relevant handlers. + + Loop through all handlers for this logger and its parents in the + logger hierarchy. If no handler was found, output a one-off error + message to sys.stderr. Stop searching up the hierarchy whenever a + logger with the "propagate" attribute set to zero is found - that + will be the last logger whose handlers are called. + """ + c = self + found = 0 + while c: + for hdlr in c.handlers: + found = found + 1 + if record.levelno >= hdlr.level: + hdlr.handle(record) + if not c.propagate: + c = None #break out + else: + c = c.parent + if (found == 0) and not self.manager.emittedNoHandlerWarning: + sys.stderr.write("No handlers could be found for logger" + " \"%s\"\n" % self.name) + self.manager.emittedNoHandlerWarning = 1 + + def getEffectiveLevel(self): + """ + Get the effective level for this logger. + + Loop through this logger and its parents in the logger hierarchy, + looking for a non-zero logging level. Return the first one found. + """ + logger = self + while logger: + if logger.level: + return logger.level + logger = logger.parent + return NOTSET + + def isEnabledFor(self, level): + """ + Is this logger enabled for level 'level'? + """ + if self.manager.disable >= level: + return 0 + return level >= self.getEffectiveLevel() + +class RootLogger(Logger): + """ + A root logger is not that different to any other logger, except that + it must have a logging level and there is only one instance of it in + the hierarchy. + """ + def __init__(self, level): + """ + Initialize the logger with the name "root". + """ + Logger.__init__(self, "root", level) + +_loggerClass = Logger + +root = RootLogger(WARNING) +Logger.root = root +Logger.manager = Manager(Logger.root) + +#--------------------------------------------------------------------------- +# Configuration classes and functions +#--------------------------------------------------------------------------- + +BASIC_FORMAT = "%(levelname)s:%(name)s:%(message)s" + +def basicConfig(**kwargs): + """ + Do basic configuration for the logging system. + + This function does nothing if the root logger already has handlers + configured. It is a convenience method intended for use by simple scripts + to do one-shot configuration of the logging package. + + The default behaviour is to create a StreamHandler which writes to + sys.stderr, set a formatter using the BASIC_FORMAT format string, and + add the handler to the root logger. + + A number of optional keyword arguments may be specified, which can alter + the default behaviour. + + filename Specifies that a FileHandler be created, using the specified + filename, rather than a StreamHandler. + filemode Specifies the mode to open the file, if filename is specified + (if filemode is unspecified, it defaults to 'a'). + format Use the specified format string for the handler. + datefmt Use the specified date/time format. + level Set the root logger level to the specified level. + stream Use the specified stream to initialize the StreamHandler. Note + that this argument is incompatible with 'filename' - if both + are present, 'stream' is ignored. + + Note that you could specify a stream created using open(filename, mode) + rather than passing the filename and mode in. However, it should be + remembered that StreamHandler does not close its stream (since it may be + using sys.stdout or sys.stderr), whereas FileHandler closes its stream + when the handler is closed. + """ + if len(root.handlers) == 0: + filename = kwargs.get("filename") + if filename: + mode = kwargs.get("filemode", 'a') + hdlr = FileHandler(filename, mode) + else: + stream = kwargs.get("stream") + hdlr = StreamHandler(stream) + fs = kwargs.get("format", BASIC_FORMAT) + dfs = kwargs.get("datefmt", None) + fmt = Formatter(fs, dfs) + hdlr.setFormatter(fmt) + root.addHandler(hdlr) + level = kwargs.get("level") + if level: + root.setLevel(level) + +#--------------------------------------------------------------------------- +# Utility functions at module level. +# Basically delegate everything to the root logger. +#--------------------------------------------------------------------------- + +def getLogger(name=None): + """ + Return a logger with the specified name, creating it if necessary. + + If no name is specified, return the root logger. + """ + if name: + return Logger.manager.getLogger(name) + else: + return root + +#def getRootLogger(): +# """ +# Return the root logger. +# +# Note that getLogger('') now does the same thing, so this function is +# deprecated and may disappear in the future. +# """ +# return root + +def critical(msg, *args, **kwargs): + """ + Log a message with severity 'CRITICAL' on the root logger. + """ + if len(root.handlers) == 0: + basicConfig() + apply(root.critical, (msg,)+args, kwargs) + +fatal = critical + +def error(msg, *args, **kwargs): + """ + Log a message with severity 'ERROR' on the root logger. + """ + if len(root.handlers) == 0: + basicConfig() + apply(root.error, (msg,)+args, kwargs) + +def exception(msg, *args): + """ + Log a message with severity 'ERROR' on the root logger, + with exception information. + """ + apply(error, (msg,)+args, {'exc_info': 1}) + +def warning(msg, *args, **kwargs): + """ + Log a message with severity 'WARNING' on the root logger. + """ + if len(root.handlers) == 0: + basicConfig() + apply(root.warning, (msg,)+args, kwargs) + +warn = warning + +def info(msg, *args, **kwargs): + """ + Log a message with severity 'INFO' on the root logger. + """ + if len(root.handlers) == 0: + basicConfig() + apply(root.info, (msg,)+args, kwargs) + +def debug(msg, *args, **kwargs): + """ + Log a message with severity 'DEBUG' on the root logger. + """ + if len(root.handlers) == 0: + basicConfig() + apply(root.debug, (msg,)+args, kwargs) + +def log(level, msg, *args, **kwargs): + """ + Log 'msg % args' with the integer severity 'level' on the root logger. + """ + if len(root.handlers) == 0: + basicConfig() + apply(root.log, (level, msg)+args, kwargs) + +def disable(level): + """ + Disable all logging calls less severe than 'level'. + """ + root.manager.disable = level + +def shutdown(): + """ + Perform any cleanup actions in the logging system (e.g. flushing + buffers). + + Should be called at application exit. + """ + for h in _handlers.keys(): + #errors might occur, for example, if files are locked + #we just ignore them + try: + h.flush() + h.close() + except: + pass + +#Let's try and shutdown automatically on application exit... +try: + import atexit + atexit.register(shutdown) +except ImportError: # for Python versions < 2.0 + def exithook(status, old_exit=sys.exit): + try: + shutdown() + finally: + old_exit(status) + + sys.exit = exithook diff --git a/env/Lib/site-packages/logging/handlers.py b/env/Lib/site-packages/logging/handlers.py new file mode 100644 index 0000000..0801699 --- /dev/null +++ b/env/Lib/site-packages/logging/handlers.py @@ -0,0 +1,975 @@ +# Copyright 2001-2005 by Vinay Sajip. All Rights Reserved. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose and without fee is hereby granted, +# provided that the above copyright notice appear in all copies and that +# both that copyright notice and this permission notice appear in +# supporting documentation, and that the name of Vinay Sajip +# not be used in advertising or publicity pertaining to distribution +# of the software without specific, written prior permission. +# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL +# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER +# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +""" +Additional handlers for the logging package for Python. The core package is +based on PEP 282 and comments thereto in comp.lang.python, and influenced by +Apache's log4j system. + +Should work under Python versions >= 1.5.2, except that source line +information is not available unless 'sys._getframe()' is. + +Copyright (C) 2001-2004 Vinay Sajip. All Rights Reserved. + +To use, simply 'import logging' and log away! +""" + +import sys, logging, socket, types, os, string, cPickle, struct, time, glob + +try: + import codecs +except ImportError: + codecs = None + +# +# Some constants... +# + +DEFAULT_TCP_LOGGING_PORT = 9020 +DEFAULT_UDP_LOGGING_PORT = 9021 +DEFAULT_HTTP_LOGGING_PORT = 9022 +DEFAULT_SOAP_LOGGING_PORT = 9023 +SYSLOG_UDP_PORT = 514 + +class BaseRotatingHandler(logging.FileHandler): + """ + Base class for handlers that rotate log files at a certain point. + Not meant to be instantiated directly. Instead, use RotatingFileHandler + or TimedRotatingFileHandler. + """ + def __init__(self, filename, mode, encoding=None): + """ + Use the specified filename for streamed logging + """ + if codecs is None: + encoding = None + logging.FileHandler.__init__(self, filename, mode, encoding) + self.mode = mode + self.encoding = encoding + + def emit(self, record): + """ + Emit a record. + + Output the record to the file, catering for rollover as described + in doRollover(). + """ + try: + if self.shouldRollover(record): + self.doRollover() + logging.FileHandler.emit(self, record) + except: + self.handleError(record) + +class RotatingFileHandler(BaseRotatingHandler): + """ + Handler for logging to a set of files, which switches from one file + to the next when the current file reaches a certain size. + """ + def __init__(self, filename, mode='a', maxBytes=0, backupCount=0, encoding=None): + """ + Open the specified file and use it as the stream for logging. + + By default, the file grows indefinitely. You can specify particular + values of maxBytes and backupCount to allow the file to rollover at + a predetermined size. + + Rollover occurs whenever the current log file is nearly maxBytes in + length. If backupCount is >= 1, the system will successively create + new files with the same pathname as the base file, but with extensions + ".1", ".2" etc. appended to it. For example, with a backupCount of 5 + and a base file name of "app.log", you would get "app.log", + "app.log.1", "app.log.2", ... through to "app.log.5". The file being + written to is always "app.log" - when it gets filled up, it is closed + and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. + exist, then they are renamed to "app.log.2", "app.log.3" etc. + respectively. + + If maxBytes is zero, rollover never occurs. + """ + if maxBytes > 0: + mode = 'a' # doesn't make sense otherwise! + BaseRotatingHandler.__init__(self, filename, mode, encoding) + self.maxBytes = maxBytes + self.backupCount = backupCount + + def doRollover(self): + """ + Do a rollover, as described in __init__(). + """ + + self.stream.close() + if self.backupCount > 0: + for i in range(self.backupCount - 1, 0, -1): + sfn = "%s.%d" % (self.baseFilename, i) + dfn = "%s.%d" % (self.baseFilename, i + 1) + if os.path.exists(sfn): + #print "%s -> %s" % (sfn, dfn) + if os.path.exists(dfn): + os.remove(dfn) + os.rename(sfn, dfn) + dfn = self.baseFilename + ".1" + if os.path.exists(dfn): + os.remove(dfn) + os.rename(self.baseFilename, dfn) + #print "%s -> %s" % (self.baseFilename, dfn) + if self.encoding: + self.stream = codecs.open(self.baseFilename, 'w', self.encoding) + else: + self.stream = open(self.baseFilename, 'w') + + def shouldRollover(self, record): + """ + Determine if rollover should occur. + + Basically, see if the supplied record would cause the file to exceed + the size limit we have. + """ + if self.maxBytes > 0: # are we rolling over? + msg = "%s\n" % self.format(record) + self.stream.seek(0, 2) #due to non-posix-compliant Windows feature + if self.stream.tell() + len(msg) >= self.maxBytes: + return 1 + return 0 + +class TimedRotatingFileHandler(BaseRotatingHandler): + """ + Handler for logging to a file, rotating the log file at certain timed + intervals. + + If backupCount is > 0, when rollover is done, no more than backupCount + files are kept - the oldest ones are deleted. + """ + def __init__(self, filename, when='h', interval=1, backupCount=0, encoding=None): + BaseRotatingHandler.__init__(self, filename, 'a', encoding) + self.when = string.upper(when) + self.backupCount = backupCount + # Calculate the real rollover interval, which is just the number of + # seconds between rollovers. Also set the filename suffix used when + # a rollover occurs. Current 'when' events supported: + # S - Seconds + # M - Minutes + # H - Hours + # D - Days + # midnight - roll over at midnight + # W{0-6} - roll over on a certain day; 0 - Monday + # + # Case of the 'when' specifier is not important; lower or upper case + # will work. + currentTime = int(time.time()) + if self.when == 'S': + self.interval = 1 # one second + self.suffix = "%Y-%m-%d_%H-%M-%S" + elif self.when == 'M': + self.interval = 60 # one minute + self.suffix = "%Y-%m-%d_%H-%M" + elif self.when == 'H': + self.interval = 60 * 60 # one hour + self.suffix = "%Y-%m-%d_%H" + elif self.when == 'D' or self.when == 'MIDNIGHT': + self.interval = 60 * 60 * 24 # one day + self.suffix = "%Y-%m-%d" + elif self.when.startswith('W'): + self.interval = 60 * 60 * 24 * 7 # one week + if len(self.when) != 2: + raise ValueError("You must specify a day for weekly rollover from 0 to 6 (0 is Monday): %s" % self.when) + if self.when[1] < '0' or self.when[1] > '6': + raise ValueError("Invalid day specified for weekly rollover: %s" % self.when) + self.dayOfWeek = int(self.when[1]) + self.suffix = "%Y-%m-%d" + else: + raise ValueError("Invalid rollover interval specified: %s" % self.when) + + self.interval = self.interval * interval # multiply by units requested + self.rolloverAt = currentTime + self.interval + + # If we are rolling over at midnight or weekly, then the interval is already known. + # What we need to figure out is WHEN the next interval is. In other words, + # if you are rolling over at midnight, then your base interval is 1 day, + # but you want to start that one day clock at midnight, not now. So, we + # have to fudge the rolloverAt value in order to trigger the first rollover + # at the right time. After that, the regular interval will take care of + # the rest. Note that this code doesn't care about leap seconds. :) + if self.when == 'MIDNIGHT' or self.when.startswith('W'): + # This could be done with less code, but I wanted it to be clear + t = time.localtime(currentTime) + currentHour = t[3] + currentMinute = t[4] + currentSecond = t[5] + # r is the number of seconds left between now and midnight + r = (24 - currentHour) * 60 * 60 # number of hours in seconds + r = r + (59 - currentMinute) * 60 # plus the number of minutes (in secs) + r = r + (59 - currentSecond) # plus the number of seconds + self.rolloverAt = currentTime + r + # If we are rolling over on a certain day, add in the number of days until + # the next rollover, but offset by 1 since we just calculated the time + # until the next day starts. There are three cases: + # Case 1) The day to rollover is today; in this case, do nothing + # Case 2) The day to rollover is further in the interval (i.e., today is + # day 2 (Wednesday) and rollover is on day 6 (Sunday). Days to + # next rollover is simply 6 - 2 - 1, or 3. + # Case 3) The day to rollover is behind us in the interval (i.e., today + # is day 5 (Saturday) and rollover is on day 3 (Thursday). + # Days to rollover is 6 - 5 + 3, or 4. In this case, it's the + # number of days left in the current week (1) plus the number + # of days in the next week until the rollover day (3). + if when.startswith('W'): + day = t[6] # 0 is Monday + if day > self.dayOfWeek: + daysToWait = (day - self.dayOfWeek) - 1 + self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24)) + if day < self.dayOfWeek: + daysToWait = (6 - self.dayOfWeek) + day + self.rolloverAt = self.rolloverAt + (daysToWait * (60 * 60 * 24)) + + #print "Will rollover at %d, %d seconds from now" % (self.rolloverAt, self.rolloverAt - currentTime) + + def shouldRollover(self, record): + """ + Determine if rollover should occur + + record is not used, as we are just comparing times, but it is needed so + the method siguratures are the same + """ + t = int(time.time()) + if t >= self.rolloverAt: + return 1 + #print "No need to rollover: %d, %d" % (t, self.rolloverAt) + return 0 + + def doRollover(self): + """ + do a rollover; in this case, a date/time stamp is appended to the filename + when the rollover happens. However, you want the file to be named for the + start of the interval, not the current time. If there is a backup count, + then we have to get a list of matching filenames, sort them and remove + the one with the oldest suffix. + """ + self.stream.close() + # get the time that this sequence started at and make it a TimeTuple + t = self.rolloverAt - self.interval + timeTuple = time.localtime(t) + dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple) + if os.path.exists(dfn): + os.remove(dfn) + os.rename(self.baseFilename, dfn) + if self.backupCount > 0: + # find the oldest log file and delete it + s = glob.glob(self.baseFilename + ".20*") + if len(s) > self.backupCount: + s.sort() + os.remove(s[0]) + #print "%s -> %s" % (self.baseFilename, dfn) + if self.encoding: + self.stream = codecs.open(self.baseFilename, 'w', self.encoding) + else: + self.stream = open(self.baseFilename, 'w') + self.rolloverAt = int(time.time()) + self.interval + +class SocketHandler(logging.Handler): + """ + A handler class which writes logging records, in pickle format, to + a streaming socket. The socket is kept open across logging calls. + If the peer resets it, an attempt is made to reconnect on the next call. + The pickle which is sent is that of the LogRecord's attribute dictionary + (__dict__), so that the receiver does not need to have the logging module + installed in order to process the logging event. + + To unpickle the record at the receiving end into a LogRecord, use the + makeLogRecord function. + """ + + def __init__(self, host, port): + """ + Initializes the handler with a specific host address and port. + + The attribute 'closeOnError' is set to 1 - which means that if + a socket error occurs, the socket is silently closed and then + reopened on the next logging call. + """ + logging.Handler.__init__(self) + self.host = host + self.port = port + self.sock = None + self.closeOnError = 0 + self.retryTime = None + # + # Exponential backoff parameters. + # + self.retryStart = 1.0 + self.retryMax = 30.0 + self.retryFactor = 2.0 + + def makeSocket(self): + """ + A factory method which allows subclasses to define the precise + type of socket they want. + """ + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((self.host, self.port)) + return s + + def createSocket(self): + """ + Try to create a socket, using an exponential backoff with + a max retry time. Thanks to Robert Olson for the original patch + (SF #815911) which has been slightly refactored. + """ + now = time.time() + # Either retryTime is None, in which case this + # is the first time back after a disconnect, or + # we've waited long enough. + if self.retryTime is None: + attempt = 1 + else: + attempt = (now >= self.retryTime) + if attempt: + try: + self.sock = self.makeSocket() + self.retryTime = None # next time, no delay before trying + except: + #Creation failed, so set the retry time and return. + if self.retryTime is None: + self.retryPeriod = self.retryStart + else: + self.retryPeriod = self.retryPeriod * self.retryFactor + if self.retryPeriod > self.retryMax: + self.retryPeriod = self.retryMax + self.retryTime = now + self.retryPeriod + + def send(self, s): + """ + Send a pickled string to the socket. + + This function allows for partial sends which can happen when the + network is busy. + """ + if self.sock is None: + self.createSocket() + #self.sock can be None either because we haven't reached the retry + #time yet, or because we have reached the retry time and retried, + #but are still unable to connect. + if self.sock: + try: + if hasattr(self.sock, "sendall"): + self.sock.sendall(s) + else: + sentsofar = 0 + left = len(s) + while left > 0: + sent = self.sock.send(s[sentsofar:]) + sentsofar = sentsofar + sent + left = left - sent + except socket.error: + self.sock.close() + self.sock = None # so we can call createSocket next time + + def makePickle(self, record): + """ + Pickles the record in binary format with a length prefix, and + returns it ready for transmission across the socket. + """ + ei = record.exc_info + if ei: + dummy = self.format(record) # just to get traceback text into record.exc_text + record.exc_info = None # to avoid Unpickleable error + s = cPickle.dumps(record.__dict__, 1) + if ei: + record.exc_info = ei # for next handler + slen = struct.pack(">L", len(s)) + return slen + s + + def handleError(self, record): + """ + Handle an error during logging. + + An error has occurred during logging. Most likely cause - + connection lost. Close the socket so that we can retry on the + next event. + """ + if self.closeOnError and self.sock: + self.sock.close() + self.sock = None #try to reconnect next time + else: + logging.Handler.handleError(self, record) + + def emit(self, record): + """ + Emit a record. + + Pickles the record and writes it to the socket in binary format. + If there is an error with the socket, silently drop the packet. + If there was a problem with the socket, re-establishes the + socket. + """ + try: + s = self.makePickle(record) + self.send(s) + except: + self.handleError(record) + + def close(self): + """ + Closes the socket. + """ + if self.sock: + self.sock.close() + self.sock = None + logging.Handler.close(self) + +class DatagramHandler(SocketHandler): + """ + A handler class which writes logging records, in pickle format, to + a datagram socket. The pickle which is sent is that of the LogRecord's + attribute dictionary (__dict__), so that the receiver does not need to + have the logging module installed in order to process the logging event. + + To unpickle the record at the receiving end into a LogRecord, use the + makeLogRecord function. + + """ + def __init__(self, host, port): + """ + Initializes the handler with a specific host address and port. + """ + SocketHandler.__init__(self, host, port) + self.closeOnError = 0 + + def makeSocket(self): + """ + The factory method of SocketHandler is here overridden to create + a UDP socket (SOCK_DGRAM). + """ + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + return s + + def send(self, s): + """ + Send a pickled string to a socket. + + This function no longer allows for partial sends which can happen + when the network is busy - UDP does not guarantee delivery and + can deliver packets out of sequence. + """ + if self.sock is None: + self.createSocket() + self.sock.sendto(s, (self.host, self.port)) + +class SysLogHandler(logging.Handler): + """ + A handler class which sends formatted logging records to a syslog + server. Based on Sam Rushing's syslog module: + http://www.nightmare.com/squirl/python-ext/misc/syslog.py + Contributed by Nicolas Untz (after which minor refactoring changes + have been made). + """ + + # from : + # ====================================================================== + # priorities/facilities are encoded into a single 32-bit quantity, where + # the bottom 3 bits are the priority (0-7) and the top 28 bits are the + # facility (0-big number). Both the priorities and the facilities map + # roughly one-to-one to strings in the syslogd(8) source code. This + # mapping is included in this file. + # + # priorities (these are ordered) + + LOG_EMERG = 0 # system is unusable + LOG_ALERT = 1 # action must be taken immediately + LOG_CRIT = 2 # critical conditions + LOG_ERR = 3 # error conditions + LOG_WARNING = 4 # warning conditions + LOG_NOTICE = 5 # normal but significant condition + LOG_INFO = 6 # informational + LOG_DEBUG = 7 # debug-level messages + + # facility codes + LOG_KERN = 0 # kernel messages + LOG_USER = 1 # random user-level messages + LOG_MAIL = 2 # mail system + LOG_DAEMON = 3 # system daemons + LOG_AUTH = 4 # security/authorization messages + LOG_SYSLOG = 5 # messages generated internally by syslogd + LOG_LPR = 6 # line printer subsystem + LOG_NEWS = 7 # network news subsystem + LOG_UUCP = 8 # UUCP subsystem + LOG_CRON = 9 # clock daemon + LOG_AUTHPRIV = 10 # security/authorization messages (private) + + # other codes through 15 reserved for system use + LOG_LOCAL0 = 16 # reserved for local use + LOG_LOCAL1 = 17 # reserved for local use + LOG_LOCAL2 = 18 # reserved for local use + LOG_LOCAL3 = 19 # reserved for local use + LOG_LOCAL4 = 20 # reserved for local use + LOG_LOCAL5 = 21 # reserved for local use + LOG_LOCAL6 = 22 # reserved for local use + LOG_LOCAL7 = 23 # reserved for local use + + priority_names = { + "alert": LOG_ALERT, + "crit": LOG_CRIT, + "critical": LOG_CRIT, + "debug": LOG_DEBUG, + "emerg": LOG_EMERG, + "err": LOG_ERR, + "error": LOG_ERR, # DEPRECATED + "info": LOG_INFO, + "notice": LOG_NOTICE, + "panic": LOG_EMERG, # DEPRECATED + "warn": LOG_WARNING, # DEPRECATED + "warning": LOG_WARNING, + } + + facility_names = { + "auth": LOG_AUTH, + "authpriv": LOG_AUTHPRIV, + "cron": LOG_CRON, + "daemon": LOG_DAEMON, + "kern": LOG_KERN, + "lpr": LOG_LPR, + "mail": LOG_MAIL, + "news": LOG_NEWS, + "security": LOG_AUTH, # DEPRECATED + "syslog": LOG_SYSLOG, + "user": LOG_USER, + "uucp": LOG_UUCP, + "local0": LOG_LOCAL0, + "local1": LOG_LOCAL1, + "local2": LOG_LOCAL2, + "local3": LOG_LOCAL3, + "local4": LOG_LOCAL4, + "local5": LOG_LOCAL5, + "local6": LOG_LOCAL6, + "local7": LOG_LOCAL7, + } + + def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER): + """ + Initialize a handler. + + If address is specified as a string, UNIX socket is used. + If facility is not specified, LOG_USER is used. + """ + logging.Handler.__init__(self) + + self.address = address + self.facility = facility + if type(address) == types.StringType: + self._connect_unixsocket(address) + self.unixsocket = 1 + else: + self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.unixsocket = 0 + + self.formatter = None + + def _connect_unixsocket(self, address): + self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) + # syslog may require either DGRAM or STREAM sockets + try: + self.socket.connect(address) + except socket.error: + self.socket.close() + self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + self.socket.connect(address) + + # curious: when talking to the unix-domain '/dev/log' socket, a + # zero-terminator seems to be required. this string is placed + # into a class variable so that it can be overridden if + # necessary. + log_format_string = '<%d>%s\000' + + def encodePriority (self, facility, priority): + """ + Encode the facility and priority. You can pass in strings or + integers - if strings are passed, the facility_names and + priority_names mapping dictionaries are used to convert them to + integers. + """ + if type(facility) == types.StringType: + facility = self.facility_names[facility] + if type(priority) == types.StringType: + priority = self.priority_names[priority] + return (facility << 3) | priority + + def close (self): + """ + Closes the socket. + """ + if self.unixsocket: + self.socket.close() + logging.Handler.close(self) + + def emit(self, record): + """ + Emit a record. + + The record is formatted, and then sent to the syslog server. If + exception information is present, it is NOT sent to the server. + """ + msg = self.format(record) + """ + We need to convert record level to lowercase, maybe this will + change in the future. + """ + msg = self.log_format_string % ( + self.encodePriority(self.facility, + string.lower(record.levelname)), + msg) + try: + if self.unixsocket: + try: + self.socket.send(msg) + except socket.error: + self._connect_unixsocket(self.address) + self.socket.send(msg) + else: + self.socket.sendto(msg, self.address) + except: + self.handleError(record) + +class SMTPHandler(logging.Handler): + """ + A handler class which sends an SMTP email for each logging event. + """ + def __init__(self, mailhost, fromaddr, toaddrs, subject): + """ + Initialize the handler. + + Initialize the instance with the from and to addresses and subject + line of the email. To specify a non-standard SMTP port, use the + (host, port) tuple format for the mailhost argument. + """ + logging.Handler.__init__(self) + if type(mailhost) == types.TupleType: + host, port = mailhost + self.mailhost = host + self.mailport = port + else: + self.mailhost = mailhost + self.mailport = None + self.fromaddr = fromaddr + if type(toaddrs) == types.StringType: + toaddrs = [toaddrs] + self.toaddrs = toaddrs + self.subject = subject + + def getSubject(self, record): + """ + Determine the subject for the email. + + If you want to specify a subject line which is record-dependent, + override this method. + """ + return self.subject + + weekdayname = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] + + monthname = [None, + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + + def date_time(self): + """ + Return the current date and time formatted for a MIME header. + Needed for Python 1.5.2 (no email package available) + """ + year, month, day, hh, mm, ss, wd, y, z = time.gmtime(time.time()) + s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( + self.weekdayname[wd], + day, self.monthname[month], year, + hh, mm, ss) + return s + + def emit(self, record): + """ + Emit a record. + + Format the record and send it to the specified addressees. + """ + try: + import smtplib + try: + from email.Utils import formatdate + except: + formatdate = self.date_time + port = self.mailport + if not port: + port = smtplib.SMTP_PORT + smtp = smtplib.SMTP(self.mailhost, port) + msg = self.format(record) + msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( + self.fromaddr, + string.join(self.toaddrs, ","), + self.getSubject(record), + formatdate(), msg) + smtp.sendmail(self.fromaddr, self.toaddrs, msg) + smtp.quit() + except: + self.handleError(record) + +class NTEventLogHandler(logging.Handler): + """ + A handler class which sends events to the NT Event Log. Adds a + registry entry for the specified application name. If no dllname is + provided, win32service.pyd (which contains some basic message + placeholders) is used. Note that use of these placeholders will make + your event logs big, as the entire message source is held in the log. + If you want slimmer logs, you have to pass in the name of your own DLL + which contains the message definitions you want to use in the event log. + """ + def __init__(self, appname, dllname=None, logtype="Application"): + logging.Handler.__init__(self) + try: + import win32evtlogutil, win32evtlog + self.appname = appname + self._welu = win32evtlogutil + if not dllname: + dllname = os.path.split(self._welu.__file__) + dllname = os.path.split(dllname[0]) + dllname = os.path.join(dllname[0], r'win32service.pyd') + self.dllname = dllname + self.logtype = logtype + self._welu.AddSourceToRegistry(appname, dllname, logtype) + self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE + self.typemap = { + logging.DEBUG : win32evtlog.EVENTLOG_INFORMATION_TYPE, + logging.INFO : win32evtlog.EVENTLOG_INFORMATION_TYPE, + logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE, + logging.ERROR : win32evtlog.EVENTLOG_ERROR_TYPE, + logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE, + } + except ImportError: + print "The Python Win32 extensions for NT (service, event "\ + "logging) appear not to be available." + self._welu = None + + def getMessageID(self, record): + """ + Return the message ID for the event record. If you are using your + own messages, you could do this by having the msg passed to the + logger being an ID rather than a formatting string. Then, in here, + you could use a dictionary lookup to get the message ID. This + version returns 1, which is the base message ID in win32service.pyd. + """ + return 1 + + def getEventCategory(self, record): + """ + Return the event category for the record. + + Override this if you want to specify your own categories. This version + returns 0. + """ + return 0 + + def getEventType(self, record): + """ + Return the event type for the record. + + Override this if you want to specify your own types. This version does + a mapping using the handler's typemap attribute, which is set up in + __init__() to a dictionary which contains mappings for DEBUG, INFO, + WARNING, ERROR and CRITICAL. If you are using your own levels you will + either need to override this method or place a suitable dictionary in + the handler's typemap attribute. + """ + return self.typemap.get(record.levelno, self.deftype) + + def emit(self, record): + """ + Emit a record. + + Determine the message ID, event category and event type. Then + log the message in the NT event log. + """ + if self._welu: + try: + id = self.getMessageID(record) + cat = self.getEventCategory(record) + type = self.getEventType(record) + msg = self.format(record) + self._welu.ReportEvent(self.appname, id, cat, type, [msg]) + except: + self.handleError(record) + + def close(self): + """ + Clean up this handler. + + You can remove the application name from the registry as a + source of event log entries. However, if you do this, you will + not be able to see the events as you intended in the Event Log + Viewer - it needs to be able to access the registry to get the + DLL name. + """ + #self._welu.RemoveSourceFromRegistry(self.appname, self.logtype) + logging.Handler.close(self) + +class HTTPHandler(logging.Handler): + """ + A class which sends records to a Web server, using either GET or + POST semantics. + """ + def __init__(self, host, url, method="GET"): + """ + Initialize the instance with the host, the request URL, and the method + ("GET" or "POST") + """ + logging.Handler.__init__(self) + method = string.upper(method) + if method not in ["GET", "POST"]: + raise ValueError, "method must be GET or POST" + self.host = host + self.url = url + self.method = method + + def mapLogRecord(self, record): + """ + Default implementation of mapping the log record into a dict + that is sent as the CGI data. Overwrite in your class. + Contributed by Franz Glasner. + """ + return record.__dict__ + + def emit(self, record): + """ + Emit a record. + + Send the record to the Web server as an URL-encoded dictionary + """ + try: + import httplib, urllib + h = httplib.HTTP(self.host) + url = self.url + data = urllib.urlencode(self.mapLogRecord(record)) + if self.method == "GET": + if (string.find(url, '?') >= 0): + sep = '&' + else: + sep = '?' + url = url + "%c%s" % (sep, data) + h.putrequest(self.method, url) + if self.method == "POST": + h.putheader("Content-length", str(len(data))) + h.endheaders() + if self.method == "POST": + h.send(data) + h.getreply() #can't do anything with the result + except: + self.handleError(record) + +class BufferingHandler(logging.Handler): + """ + A handler class which buffers logging records in memory. Whenever each + record is added to the buffer, a check is made to see if the buffer should + be flushed. If it should, then flush() is expected to do what's needed. + """ + def __init__(self, capacity): + """ + Initialize the handler with the buffer size. + """ + logging.Handler.__init__(self) + self.capacity = capacity + self.buffer = [] + + def shouldFlush(self, record): + """ + Should the handler flush its buffer? + + Returns true if the buffer is up to capacity. This method can be + overridden to implement custom flushing strategies. + """ + return (len(self.buffer) >= self.capacity) + + def emit(self, record): + """ + Emit a record. + + Append the record. If shouldFlush() tells us to, call flush() to process + the buffer. + """ + self.buffer.append(record) + if self.shouldFlush(record): + self.flush() + + def flush(self): + """ + Override to implement custom flushing behaviour. + + This version just zaps the buffer to empty. + """ + self.buffer = [] + + def close(self): + """ + Close the handler. + + This version just flushes and chains to the parent class' close(). + """ + self.flush() + logging.Handler.close(self) + +class MemoryHandler(BufferingHandler): + """ + A handler class which buffers logging records in memory, periodically + flushing them to a target handler. Flushing occurs whenever the buffer + is full, or when an event of a certain severity or greater is seen. + """ + def __init__(self, capacity, flushLevel=logging.ERROR, target=None): + """ + Initialize the handler with the buffer size, the level at which + flushing should occur and an optional target. + + Note that without a target being set either here or via setTarget(), + a MemoryHandler is no use to anyone! + """ + BufferingHandler.__init__(self, capacity) + self.flushLevel = flushLevel + self.target = target + + def shouldFlush(self, record): + """ + Check for buffer full or a record at the flushLevel or higher. + """ + return (len(self.buffer) >= self.capacity) or \ + (record.levelno >= self.flushLevel) + + def setTarget(self, target): + """ + Set the target handler for this handler. + """ + self.target = target + + def flush(self): + """ + For a MemoryHandler, flushing means just sending the buffered + records to the target, if there is one. Override if you want + different behaviour. + """ + if self.target: + for record in self.buffer: + self.target.handle(record) + self.buffer = [] + + def close(self): + """ + Flush, set the target to None and lose the buffer. + """ + self.flush() + self.target = None + BufferingHandler.close(self) diff --git a/env/Lib/site-packages/magic_filter-1.0.12.dist-info/INSTALLER b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/magic_filter-1.0.12.dist-info/METADATA b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/METADATA new file mode 100644 index 0000000..235f015 --- /dev/null +++ b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/METADATA @@ -0,0 +1,37 @@ +Metadata-Version: 2.1 +Name: magic-filter +Version: 1.0.12 +Project-URL: Documentation, https://docs.aiogram.dev/en/dev-3.x/dispatcher/filters/magic_filters.html +Project-URL: Issues, https://github.com/aiogram/magic-filter/issues +Project-URL: Source, https://github.com/aiogram/magic-filter +Author-email: Alex Root Junior +License-Expression: MIT +License-File: LICENSE +Keywords: filter,magic,validation +Classifier: Development Status :: 3 - Alpha +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Topic :: Utilities +Classifier: Typing :: Typed +Requires-Python: >=3.7 +Provides-Extra: dev +Requires-Dist: black~=22.8.0; extra == 'dev' +Requires-Dist: flake8~=5.0.4; extra == 'dev' +Requires-Dist: isort~=5.11.5; extra == 'dev' +Requires-Dist: mypy~=1.4.1; extra == 'dev' +Requires-Dist: pre-commit~=2.20.0; extra == 'dev' +Requires-Dist: pytest-cov~=3.0.0; extra == 'dev' +Requires-Dist: pytest-html~=3.1.1; extra == 'dev' +Requires-Dist: pytest~=7.1.3; extra == 'dev' +Requires-Dist: types-setuptools~=65.3.0; extra == 'dev' +Description-Content-Type: text/markdown + +# magic-filter + +This package provides magic filter based on dynamic attribute getter diff --git a/env/Lib/site-packages/magic_filter-1.0.12.dist-info/RECORD b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/RECORD new file mode 100644 index 0000000..41b2227 --- /dev/null +++ b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/RECORD @@ -0,0 +1,40 @@ +magic_filter-1.0.12.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +magic_filter-1.0.12.dist-info/METADATA,sha256=lOYu2dS6vE2Ha5UrWEJVNmxokmWbtQHy7w3_v8NxZhk,1536 +magic_filter-1.0.12.dist-info/RECORD,, +magic_filter-1.0.12.dist-info/WHEEL,sha256=9QBuHhg6FNW7lppboF2vKVbCGTVzsFykgRQjjlajrhA,87 +magic_filter-1.0.12.dist-info/licenses/LICENSE,sha256=mnnw-u5pV8-s5DrMgusp5kyWuD8q_DxyBEyrGWhHhTo,1065 +magic_filter/__init__.py,sha256=9JzbtEEmmXCAvOsjWbTJJk5TeelJd6loA3HI6US7mZ0,278 +magic_filter/__pycache__/__init__.cpython-311.pyc,, +magic_filter/__pycache__/attrdict.cpython-311.pyc,, +magic_filter/__pycache__/exceptions.cpython-311.pyc,, +magic_filter/__pycache__/helper.cpython-311.pyc,, +magic_filter/__pycache__/magic.cpython-311.pyc,, +magic_filter/__pycache__/util.cpython-311.pyc,, +magic_filter/attrdict.py,sha256=TkQarjPn3cnzcXLAds5vw4T8CZtxe5gFebeMIpOkQxw,368 +magic_filter/exceptions.py,sha256=Dn5fIzyQv1Q-IkWaip5CIOAwB8Ye8TM1Xl-5eDEtbFA,361 +magic_filter/helper.py,sha256=EyoKzspmOKi740M3_N4SW-Fw8Ha3JWSqiFYdebySLoY,291 +magic_filter/magic.py,sha256=HzUY-y9-RA4J0-KDUkJMoegIY5OuwXIM90aRq2T-ffE,11550 +magic_filter/operations/__init__.py,sha256=4uGrtmRabLd6jdZrX9xNW8DTjmY4KyWUtKuZgnxOL4U,827 +magic_filter/operations/__pycache__/__init__.cpython-311.pyc,, +magic_filter/operations/__pycache__/base.cpython-311.pyc,, +magic_filter/operations/__pycache__/call.cpython-311.pyc,, +magic_filter/operations/__pycache__/cast.cpython-311.pyc,, +magic_filter/operations/__pycache__/combination.cpython-311.pyc,, +magic_filter/operations/__pycache__/comparator.cpython-311.pyc,, +magic_filter/operations/__pycache__/extract.cpython-311.pyc,, +magic_filter/operations/__pycache__/function.cpython-311.pyc,, +magic_filter/operations/__pycache__/getattr.cpython-311.pyc,, +magic_filter/operations/__pycache__/getitem.cpython-311.pyc,, +magic_filter/operations/__pycache__/selector.cpython-311.pyc,, +magic_filter/operations/base.py,sha256=4mOwMvBIcUrBw3ALcW5G6Xk1kYR4pM2-f8-Lr2KpFrQ,231 +magic_filter/operations/call.py,sha256=3VcEdjyTO_eNf3Z2aQcMVPZ3Z6JVMl1eeETe_bc4GHQ,527 +magic_filter/operations/cast.py,sha256=0J8-WJ233SxAfaFHl7ZyN4xamlJlU7jFWhLaXEQ_5F4,446 +magic_filter/operations/combination.py,sha256=y1ID3OaUNcArj_lYFm5cIo5knOSDxY8OMI1uBnR6Muk,1005 +magic_filter/operations/comparator.py,sha256=6w3EkrbRKR060p9Az7tvp652jJuR3c-66YT68bJuVtM,522 +magic_filter/operations/extract.py,sha256=7Z25YICzvteKMygwt7VHnLeluX2Tx3E8ZKgVUAVZ3kM,613 +magic_filter/operations/function.py,sha256=kzIh8SoeIbxN1nqiXJtHhzS8QjBlIcxfNGtKWmYK8is,940 +magic_filter/operations/getattr.py,sha256=6GvzUYm8ZQNcDL3h8m82oiUArBzdcXi1976QcbjFUi0,466 +magic_filter/operations/getitem.py,sha256=IrHfbDUm6igfvp-tuqB6oAnwJZAbj4_5sXFWaZhKxd4,736 +magic_filter/operations/selector.py,sha256=jhXmLg4vrfObetdDLm9laEJz-vsdw8p5_4aZAddzZfw,504 +magic_filter/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +magic_filter/util.py,sha256=iz_b9qrLIgrxjSL60xKhJHA69-Suoz5M9yDOSnFc9zk,660 diff --git a/env/Lib/site-packages/magic_filter-1.0.12.dist-info/WHEEL b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/WHEEL new file mode 100644 index 0000000..ba1a8af --- /dev/null +++ b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.18.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/env/Lib/site-packages/magic_filter-1.0.12.dist-info/licenses/LICENSE b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/licenses/LICENSE new file mode 100644 index 0000000..7b60093 --- /dev/null +++ b/env/Lib/site-packages/magic_filter-1.0.12.dist-info/licenses/LICENSE @@ -0,0 +1,18 @@ +Copyright (c) 2020-2022 Alex Root Junior + +Permission is hereby granted, free of charge, to any person obtaining a copy of this +software and associated documentation files (the "Software"), to deal in the Software +without restriction, including without limitation the rights to use, copy, modify, +merge, publish, distribute, sublicense, and/or sell copies of the Software, +and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies +or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR +PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE +OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/env/Lib/site-packages/magic_filter/__init__.py b/env/Lib/site-packages/magic_filter/__init__.py new file mode 100644 index 0000000..f6c0211 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/__init__.py @@ -0,0 +1,17 @@ +from . import operations +from .attrdict import AttrDict +from .magic import MagicFilter, MagicT, RegexpMode + +__all__ = ( + "__version__", + "operations", + "MagicFilter", + "MagicT", + "RegexpMode", + "F", + "AttrDict", +) + +__version__ = "1.0.12" + +F = MagicFilter() diff --git a/env/Lib/site-packages/magic_filter/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/magic_filter/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..d647262 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/__pycache__/attrdict.cpython-311.pyc b/env/Lib/site-packages/magic_filter/__pycache__/attrdict.cpython-311.pyc new file mode 100644 index 0000000..07bcb15 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/__pycache__/attrdict.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/__pycache__/exceptions.cpython-311.pyc b/env/Lib/site-packages/magic_filter/__pycache__/exceptions.cpython-311.pyc new file mode 100644 index 0000000..5bc9146 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/__pycache__/exceptions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/__pycache__/helper.cpython-311.pyc b/env/Lib/site-packages/magic_filter/__pycache__/helper.cpython-311.pyc new file mode 100644 index 0000000..cf45431 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/__pycache__/helper.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/__pycache__/magic.cpython-311.pyc b/env/Lib/site-packages/magic_filter/__pycache__/magic.cpython-311.pyc new file mode 100644 index 0000000..b0c11b3 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/__pycache__/magic.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/__pycache__/util.cpython-311.pyc b/env/Lib/site-packages/magic_filter/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000..807cb40 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/__pycache__/util.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/attrdict.py b/env/Lib/site-packages/magic_filter/attrdict.py new file mode 100644 index 0000000..1d90720 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/attrdict.py @@ -0,0 +1,14 @@ +from typing import Any, Dict, TypeVar + +KT = TypeVar("KT") +VT = TypeVar("VT") + + +class AttrDict(Dict[KT, VT]): + """ + A wrapper over dict which where element can be accessed as regular attributes + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super(AttrDict, self).__init__(*args, **kwargs) + self.__dict__ = self # type: ignore diff --git a/env/Lib/site-packages/magic_filter/exceptions.py b/env/Lib/site-packages/magic_filter/exceptions.py new file mode 100644 index 0000000..59e81ab --- /dev/null +++ b/env/Lib/site-packages/magic_filter/exceptions.py @@ -0,0 +1,23 @@ +class MagicFilterException(Exception): + pass + + +class SwitchMode(MagicFilterException): + pass + + +class SwitchModeToAll(SwitchMode): + def __init__(self, key: slice) -> None: + self.key = key + + +class SwitchModeToAny(SwitchMode): + pass + + +class RejectOperations(MagicFilterException): + pass + + +class ParamsConflict(MagicFilterException): + pass diff --git a/env/Lib/site-packages/magic_filter/helper.py b/env/Lib/site-packages/magic_filter/helper.py new file mode 100644 index 0000000..2685325 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/helper.py @@ -0,0 +1,10 @@ +from typing import Any + + +def resolve_if_needed(value: Any, initial_value: Any) -> Any: + # To avoid circular imports here is used local import + from magic_filter import MagicFilter + + if not isinstance(value, MagicFilter): + return value + return value.resolve(initial_value) diff --git a/env/Lib/site-packages/magic_filter/magic.py b/env/Lib/site-packages/magic_filter/magic.py new file mode 100644 index 0000000..77266e7 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/magic.py @@ -0,0 +1,290 @@ +import operator +import re +from functools import wraps +from typing import Any, Callable, Container, Optional, Pattern, Tuple, Type, TypeVar, Union +from warnings import warn + +from magic_filter.exceptions import ( + ParamsConflict, + RejectOperations, + SwitchModeToAll, + SwitchModeToAny, +) +from magic_filter.operations import ( + BaseOperation, + CallOperation, + CastOperation, + CombinationOperation, + ComparatorOperation, + ExtractOperation, + FunctionOperation, + GetAttributeOperation, + GetItemOperation, + ImportantCombinationOperation, + ImportantFunctionOperation, + RCombinationOperation, + SelectorOperation, +) +from magic_filter.util import and_op, contains_op, in_op, not_contains_op, not_in_op, or_op + +MagicT = TypeVar("MagicT", bound="MagicFilter") + + +class RegexpMode: + SEARCH = "search" + MATCH = "match" + FINDALL = "findall" + FINDITER = "finditer" + FULLMATCH = "fullmatch" + + +class MagicFilter: + __slots__ = ("_operations",) + + def __init__(self, operations: Tuple[BaseOperation, ...] = ()) -> None: + self._operations = operations + + # An instance of MagicFilter cannot be used as an iterable object because objects + # with a __getitem__ method can be endlessly iterated, which is not the desired behavior. + __iter__ = None + + @classmethod + def ilter(cls, magic: "MagicFilter") -> Callable[[Any], Any]: + @wraps(magic.resolve) + def wrapper(value: Any) -> Any: + return magic.resolve(value) + + return wrapper + + @classmethod + def _new(cls: Type[MagicT], operations: Tuple[BaseOperation, ...]) -> MagicT: + return cls(operations=operations) + + def _extend(self: MagicT, operation: BaseOperation) -> MagicT: + return self._new(self._operations + (operation,)) + + def _replace_last(self: MagicT, operation: BaseOperation) -> MagicT: + return self._new(self._operations[:-1] + (operation,)) + + def _exclude_last(self: MagicT) -> MagicT: + return self._new(self._operations[:-1]) + + def _resolve(self, value: Any, operations: Optional[Tuple[BaseOperation, ...]] = None) -> Any: + initial_value = value + if operations is None: + operations = self._operations + rejected = False + for index, operation in enumerate(operations): + if rejected and not operation.important: + continue + try: + value = operation.resolve(value=value, initial_value=initial_value) + except SwitchModeToAll: + return all(self._resolve(value=item, operations=operations[index + 1 :]) for item in value) + except SwitchModeToAny: + return any(self._resolve(value=item, operations=operations[index + 1 :]) for item in value) + except RejectOperations: + rejected = True + value = None + continue + rejected = False + return value + + def __bool__(self) -> bool: + return True + + def resolve(self: MagicT, value: Any) -> Any: + return self._resolve(value=value) + + def __getattr__(self: MagicT, item: Any) -> MagicT: + if item.startswith("_"): + raise AttributeError(f"{type(self).__name__!r} object has no attribute {item!r}") + return self._extend(GetAttributeOperation(name=item)) + + attr_ = __getattr__ + + def __getitem__(self: MagicT, item: Any) -> MagicT: + if isinstance(item, MagicFilter): + return self._extend(SelectorOperation(inner=item)) + return self._extend(GetItemOperation(key=item)) + + def __len__(self) -> int: + raise TypeError(f"Length can't be taken using len() function. Use {type(self).__name__}.len() instead.") + + def __eq__(self: MagicT, other: Any) -> MagicT: # type: ignore + return self._extend(ComparatorOperation(right=other, comparator=operator.eq)) + + def __ne__(self: MagicT, other: Any) -> MagicT: # type: ignore + return self._extend(ComparatorOperation(right=other, comparator=operator.ne)) + + def __lt__(self: MagicT, other: Any) -> MagicT: + return self._extend(ComparatorOperation(right=other, comparator=operator.lt)) + + def __gt__(self: MagicT, other: Any) -> MagicT: + return self._extend(ComparatorOperation(right=other, comparator=operator.gt)) + + def __le__(self: MagicT, other: Any) -> MagicT: + return self._extend(ComparatorOperation(right=other, comparator=operator.le)) + + def __ge__(self: MagicT, other: Any) -> MagicT: + return self._extend(ComparatorOperation(right=other, comparator=operator.ge)) + + def __invert__(self: MagicT) -> MagicT: + if ( + self._operations + and isinstance(self._operations[-1], ImportantFunctionOperation) + and self._operations[-1].function == operator.not_ + ): + return self._exclude_last() + return self._extend(ImportantFunctionOperation(function=operator.not_)) + + def __call__(self: MagicT, *args: Any, **kwargs: Any) -> MagicT: + return self._extend(CallOperation(args=args, kwargs=kwargs)) + + def __and__(self: MagicT, other: Any) -> MagicT: + if isinstance(other, MagicFilter): + return self._extend(CombinationOperation(right=other, combinator=and_op)) + return self._extend(CombinationOperation(right=other, combinator=operator.and_)) + + def __rand__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.and_)) + + def __or__(self: MagicT, other: Any) -> MagicT: + if isinstance(other, MagicFilter): + return self._extend(ImportantCombinationOperation(right=other, combinator=or_op)) + return self._extend(ImportantCombinationOperation(right=other, combinator=operator.or_)) + + def __ror__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.or_)) + + def __xor__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.xor)) + + def __rxor__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.xor)) + + def __rshift__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.rshift)) + + def __rrshift__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.rshift)) + + def __lshift__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.lshift)) + + def __rlshift__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.lshift)) + + def __add__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.add)) + + def __radd__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.add)) + + def __sub__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.sub)) + + def __rsub__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.sub)) + + def __mul__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.mul)) + + def __rmul__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.mul)) + + def __truediv__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.truediv)) + + def __rtruediv__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.truediv)) + + def __floordiv__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.floordiv)) + + def __rfloordiv__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.floordiv)) + + def __mod__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.mod)) + + def __rmod__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.mod)) + + def __matmul__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.matmul)) + + def __rmatmul__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.matmul)) + + def __pow__(self: MagicT, other: Any) -> MagicT: + return self._extend(CombinationOperation(right=other, combinator=operator.pow)) + + def __rpow__(self: MagicT, other: Any) -> MagicT: + return self._extend(RCombinationOperation(left=other, combinator=operator.pow)) + + def __pos__(self: MagicT) -> MagicT: + return self._extend(FunctionOperation(function=operator.pos)) + + def __neg__(self: MagicT) -> MagicT: + return self._extend(FunctionOperation(function=operator.neg)) + + def is_(self: MagicT, value: Any) -> MagicT: + return self._extend(CombinationOperation(right=value, combinator=operator.is_)) + + def is_not(self: MagicT, value: Any) -> MagicT: + return self._extend(CombinationOperation(right=value, combinator=operator.is_not)) + + def in_(self: MagicT, iterable: Union[Container[Any], MagicT]) -> MagicT: + return self._extend(FunctionOperation(in_op, iterable)) + + def not_in(self: MagicT, iterable: Union[Container[Any], MagicT]) -> MagicT: + return self._extend(FunctionOperation(not_in_op, iterable)) + + def contains(self: MagicT, value: Any) -> MagicT: + return self._extend(FunctionOperation(contains_op, value)) + + def not_contains(self: MagicT, value: Any) -> MagicT: + return self._extend(FunctionOperation(not_contains_op, value)) + + def len(self: MagicT) -> MagicT: + return self._extend(FunctionOperation(len)) + + def regexp( + self: MagicT, + pattern: Union[str, Pattern[str]], + *, + mode: Optional[str] = None, + search: Optional[bool] = None, + flags: Union[int, re.RegexFlag] = 0, + ) -> MagicT: + + if search is not None: + warn( + "Param 'search' is deprecated, use 'mode' instead.", + DeprecationWarning, + ) + + if mode is not None: + msg = "Can't pass both 'search' and 'mode' params." + raise ParamsConflict(msg) + + mode = RegexpMode.SEARCH if search else RegexpMode.MATCH + + if mode is None: + mode = RegexpMode.MATCH + + if isinstance(pattern, str): + pattern = re.compile(pattern, flags=flags) + + regexp_func = getattr(pattern, mode) + return self._extend(FunctionOperation(regexp_func)) + + def func(self: MagicT, func: Callable[[Any], Any], *args: Any, **kwargs: Any) -> MagicT: + return self._extend(FunctionOperation(func, *args, **kwargs)) + + def cast(self: MagicT, func: Callable[[Any], Any]) -> MagicT: + return self._extend(CastOperation(func)) + + def extract(self: MagicT, magic: "MagicT") -> MagicT: + return self._extend(ExtractOperation(magic)) diff --git a/env/Lib/site-packages/magic_filter/operations/__init__.py b/env/Lib/site-packages/magic_filter/operations/__init__.py new file mode 100644 index 0000000..8eacacc --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/__init__.py @@ -0,0 +1,26 @@ +from .base import BaseOperation +from .call import CallOperation +from .cast import CastOperation +from .combination import CombinationOperation, ImportantCombinationOperation, RCombinationOperation +from .comparator import ComparatorOperation +from .extract import ExtractOperation +from .function import FunctionOperation, ImportantFunctionOperation +from .getattr import GetAttributeOperation +from .getitem import GetItemOperation +from .selector import SelectorOperation + +__all__ = ( + "BaseOperation", + "CallOperation", + "CastOperation", + "CombinationOperation", + "ComparatorOperation", + "FunctionOperation", + "GetAttributeOperation", + "GetItemOperation", + "ImportantCombinationOperation", + "ImportantFunctionOperation", + "RCombinationOperation", + "SelectorOperation", + "ExtractOperation", +) diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..5e623cc Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/base.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/base.cpython-311.pyc new file mode 100644 index 0000000..b40ae5b Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/call.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/call.cpython-311.pyc new file mode 100644 index 0000000..fd935c0 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/call.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/cast.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/cast.cpython-311.pyc new file mode 100644 index 0000000..e22a91c Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/cast.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/combination.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/combination.cpython-311.pyc new file mode 100644 index 0000000..ee38fde Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/combination.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/comparator.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/comparator.cpython-311.pyc new file mode 100644 index 0000000..f54ab94 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/comparator.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/extract.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/extract.cpython-311.pyc new file mode 100644 index 0000000..b1c109e Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/extract.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/function.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/function.cpython-311.pyc new file mode 100644 index 0000000..36bf81d Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/function.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/getattr.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/getattr.cpython-311.pyc new file mode 100644 index 0000000..0374068 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/getattr.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/getitem.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/getitem.cpython-311.pyc new file mode 100644 index 0000000..5ef5cdf Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/getitem.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/__pycache__/selector.cpython-311.pyc b/env/Lib/site-packages/magic_filter/operations/__pycache__/selector.cpython-311.pyc new file mode 100644 index 0000000..289be25 Binary files /dev/null and b/env/Lib/site-packages/magic_filter/operations/__pycache__/selector.cpython-311.pyc differ diff --git a/env/Lib/site-packages/magic_filter/operations/base.py b/env/Lib/site-packages/magic_filter/operations/base.py new file mode 100644 index 0000000..2745990 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/base.py @@ -0,0 +1,10 @@ +from abc import ABC, abstractmethod +from typing import Any + + +class BaseOperation(ABC): + important: bool = False + + @abstractmethod + def resolve(self, value: Any, initial_value: Any) -> Any: # pragma: no cover + pass diff --git a/env/Lib/site-packages/magic_filter/operations/call.py b/env/Lib/site-packages/magic_filter/operations/call.py new file mode 100644 index 0000000..67c8d7a --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/call.py @@ -0,0 +1,17 @@ +from typing import Any, Dict, Tuple + +from ..exceptions import RejectOperations +from .base import BaseOperation + + +class CallOperation(BaseOperation): + __slots__ = ("args", "kwargs") + + def __init__(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]): + self.args = args + self.kwargs = kwargs + + def resolve(self, value: Any, initial_value: Any) -> Any: + if not callable(value): + raise RejectOperations(TypeError(f"{value} is not callable")) + return value(*self.args, **self.kwargs) diff --git a/env/Lib/site-packages/magic_filter/operations/cast.py b/env/Lib/site-packages/magic_filter/operations/cast.py new file mode 100644 index 0000000..73bc5bd --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/cast.py @@ -0,0 +1,17 @@ +from typing import Any, Callable + +from ..exceptions import RejectOperations +from .base import BaseOperation + + +class CastOperation(BaseOperation): + __slots__ = ("func",) + + def __init__(self, func: Callable[[Any], Any]) -> None: + self.func = func + + def resolve(self, value: Any, initial_value: Any) -> Any: + try: + return self.func(value) + except Exception as e: + raise RejectOperations(e) from e diff --git a/env/Lib/site-packages/magic_filter/operations/combination.py b/env/Lib/site-packages/magic_filter/operations/combination.py new file mode 100644 index 0000000..f2ecff3 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/combination.py @@ -0,0 +1,36 @@ +from typing import Any, Callable + +from ..helper import resolve_if_needed +from .base import BaseOperation + + +class CombinationOperation(BaseOperation): + __slots__ = ( + "right", + "combinator", + ) + + def __init__(self, right: Any, combinator: Callable[[Any, Any], bool]) -> None: + self.right = right + self.combinator = combinator + + def resolve(self, value: Any, initial_value: Any) -> Any: + return self.combinator(value, resolve_if_needed(self.right, initial_value=initial_value)) + + +class ImportantCombinationOperation(CombinationOperation): + important = True + + +class RCombinationOperation(BaseOperation): + __slots__ = ( + "left", + "combinator", + ) + + def __init__(self, left: Any, combinator: Callable[[Any, Any], bool]) -> None: + self.left = left + self.combinator = combinator + + def resolve(self, value: Any, initial_value: Any) -> Any: + return self.combinator(resolve_if_needed(self.left, initial_value), value) diff --git a/env/Lib/site-packages/magic_filter/operations/comparator.py b/env/Lib/site-packages/magic_filter/operations/comparator.py new file mode 100644 index 0000000..615da5a --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/comparator.py @@ -0,0 +1,18 @@ +from typing import Any, Callable + +from ..helper import resolve_if_needed +from .base import BaseOperation + + +class ComparatorOperation(BaseOperation): + __slots__ = ( + "right", + "comparator", + ) + + def __init__(self, right: Any, comparator: Callable[[Any, Any], bool]) -> None: + self.right = right + self.comparator = comparator + + def resolve(self, value: Any, initial_value: Any) -> Any: + return self.comparator(value, resolve_if_needed(self.right, initial_value=initial_value)) diff --git a/env/Lib/site-packages/magic_filter/operations/extract.py b/env/Lib/site-packages/magic_filter/operations/extract.py new file mode 100644 index 0000000..6fd1842 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/extract.py @@ -0,0 +1,23 @@ +from typing import TYPE_CHECKING, Any, Iterable + +from magic_filter.operations import BaseOperation + +if TYPE_CHECKING: + from magic_filter.magic import MagicFilter + + +class ExtractOperation(BaseOperation): + __slots__ = ("extractor",) + + def __init__(self, extractor: "MagicFilter") -> None: + self.extractor = extractor + + def resolve(self, value: Any, initial_value: Any) -> Any: + if not isinstance(value, Iterable): + return None + + result = [] + for item in value: + if self.extractor.resolve(item): + result.append(item) + return result diff --git a/env/Lib/site-packages/magic_filter/operations/function.py b/env/Lib/site-packages/magic_filter/operations/function.py new file mode 100644 index 0000000..409e94f --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/function.py @@ -0,0 +1,32 @@ +from typing import Any, Callable + +from ..exceptions import RejectOperations +from ..helper import resolve_if_needed +from .base import BaseOperation + + +class FunctionOperation(BaseOperation): + __slots__ = ( + "function", + "args", + "kwargs", + ) + + def __init__(self, function: Callable[..., Any], *args: Any, **kwargs: Any) -> None: + self.function = function + self.args = args + self.kwargs = kwargs + + def resolve(self, value: Any, initial_value: Any) -> Any: + try: + return self.function( + *(resolve_if_needed(arg, initial_value) for arg in self.args), + value, + **{key: resolve_if_needed(value, initial_value) for key, value in self.kwargs.items()}, + ) + except (TypeError, ValueError) as e: + raise RejectOperations(e) from e + + +class ImportantFunctionOperation(FunctionOperation): + important = True diff --git a/env/Lib/site-packages/magic_filter/operations/getattr.py b/env/Lib/site-packages/magic_filter/operations/getattr.py new file mode 100644 index 0000000..6e4b1d4 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/getattr.py @@ -0,0 +1,18 @@ +from abc import ABC +from typing import Any + +from ..exceptions import RejectOperations +from .base import BaseOperation + + +class GetAttributeOperation(BaseOperation, ABC): + __slots__ = ("name",) + + def __init__(self, name: str) -> None: + self.name = name + + def resolve(self, value: Any, initial_value: Any) -> Any: + try: + return getattr(value, self.name) + except AttributeError as e: + raise RejectOperations(e) from e diff --git a/env/Lib/site-packages/magic_filter/operations/getitem.py b/env/Lib/site-packages/magic_filter/operations/getitem.py new file mode 100644 index 0000000..5ba725d --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/getitem.py @@ -0,0 +1,25 @@ +from typing import Any, Iterable + +from magic_filter.exceptions import RejectOperations, SwitchModeToAll, SwitchModeToAny + +from .base import BaseOperation + +EMPTY_SLICE = slice(None, None, None) + + +class GetItemOperation(BaseOperation): + __slots__ = ("key",) + + def __init__(self, key: Any) -> None: + self.key = key + + def resolve(self, value: Any, initial_value: Any) -> Any: + if isinstance(value, Iterable): + if self.key is ...: + raise SwitchModeToAny() + if self.key == EMPTY_SLICE: + raise SwitchModeToAll(self.key) + try: + return value[self.key] + except (KeyError, IndexError, TypeError) as e: + raise RejectOperations(e) from e diff --git a/env/Lib/site-packages/magic_filter/operations/selector.py b/env/Lib/site-packages/magic_filter/operations/selector.py new file mode 100644 index 0000000..8073bde --- /dev/null +++ b/env/Lib/site-packages/magic_filter/operations/selector.py @@ -0,0 +1,19 @@ +from typing import TYPE_CHECKING, Any + +from magic_filter.exceptions import RejectOperations +from magic_filter.operations import BaseOperation + +if TYPE_CHECKING: + from magic_filter import MagicFilter + + +class SelectorOperation(BaseOperation): + __slots__ = ("inner",) + + def __init__(self, inner: "MagicFilter"): + self.inner = inner + + def resolve(self, value: Any, initial_value: Any) -> Any: + if self.inner.resolve(value): + return value + raise RejectOperations() diff --git a/env/Lib/site-packages/magic_filter/py.typed b/env/Lib/site-packages/magic_filter/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/magic_filter/util.py b/env/Lib/site-packages/magic_filter/util.py new file mode 100644 index 0000000..37293b0 --- /dev/null +++ b/env/Lib/site-packages/magic_filter/util.py @@ -0,0 +1,37 @@ +from typing import Any, Container + + +def in_op(a: Container[Any], b: Any) -> bool: + try: + return b in a + except TypeError: + return False + + +def not_in_op(a: Container[Any], b: Any) -> bool: + try: + return b not in a + except TypeError: + return False + + +def contains_op(a: Any, b: Container[Any]) -> bool: + try: + return a in b + except TypeError: + return False + + +def not_contains_op(a: Any, b: Container[Any]) -> bool: + try: + return a not in b + except TypeError: + return False + + +def and_op(a: Any, b: Any) -> Any: + return a and b + + +def or_op(a: Any, b: Any) -> Any: + return a or b diff --git a/env/Lib/site-packages/multidict-6.0.5.dist-info/INSTALLER b/env/Lib/site-packages/multidict-6.0.5.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/multidict-6.0.5.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/multidict-6.0.5.dist-info/LICENSE b/env/Lib/site-packages/multidict-6.0.5.dist-info/LICENSE new file mode 100644 index 0000000..8727172 --- /dev/null +++ b/env/Lib/site-packages/multidict-6.0.5.dist-info/LICENSE @@ -0,0 +1,13 @@ + Copyright 2016 Andrew Svetlov and aio-libs contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/env/Lib/site-packages/multidict-6.0.5.dist-info/METADATA b/env/Lib/site-packages/multidict-6.0.5.dist-info/METADATA new file mode 100644 index 0000000..9d9b4a7 --- /dev/null +++ b/env/Lib/site-packages/multidict-6.0.5.dist-info/METADATA @@ -0,0 +1,132 @@ +Metadata-Version: 2.1 +Name: multidict +Version: 6.0.5 +Summary: multidict implementation +Home-page: https://github.com/aio-libs/multidict +Author: Andrew Svetlov +Author-email: andrew.svetlov@gmail.com +License: Apache 2 +Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby +Project-URL: CI: GitHub, https://github.com/aio-libs/multidict/actions +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/multidict +Project-URL: Docs: RTD, https://multidict.aio-libs.org +Project-URL: GitHub: issues, https://github.com/aio-libs/multidict/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/multidict +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE + +========= +multidict +========= + +.. image:: https://github.com/aio-libs/multidict/workflows/CI/badge.svg + :target: https://github.com/aio-libs/multidict/actions?query=workflow%3ACI + :alt: GitHub status for master branch + +.. image:: https://codecov.io/gh/aio-libs/multidict/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/multidict + :alt: Coverage metrics + +.. image:: https://img.shields.io/pypi/v/multidict.svg + :target: https://pypi.org/project/multidict + :alt: PyPI + +.. image:: https://readthedocs.org/projects/multidict/badge/?version=latest + :target: http://multidict.aio-libs.org/en/latest/?badge=latest + :alt: Documentation + +.. image:: https://img.shields.io/pypi/pyversions/multidict.svg + :target: https://pypi.org/project/multidict + :alt: Python versions + +.. image:: https://badges.gitter.im/Join%20Chat.svg + :target: https://gitter.im/aio-libs/Lobby + :alt: Chat on Gitter + +Multidict is dict-like collection of *key-value pairs* where key +might occur more than once in the container. + +Introduction +------------ + +*HTTP Headers* and *URL query string* require specific data structure: +*multidict*. It behaves mostly like a regular ``dict`` but it may have +several *values* for the same *key* and *preserves insertion ordering*. + +The *key* is ``str`` (or ``istr`` for case-insensitive dictionaries). + +``multidict`` has four multidict classes: +``MultiDict``, ``MultiDictProxy``, ``CIMultiDict`` +and ``CIMultiDictProxy``. + +Immutable proxies (``MultiDictProxy`` and +``CIMultiDictProxy``) provide a dynamic view for the +proxied multidict, the view reflects underlying collection changes. They +implement the ``collections.abc.Mapping`` interface. + +Regular mutable (``MultiDict`` and ``CIMultiDict``) classes +implement ``collections.abc.MutableMapping`` and allows them to change +their own content. + + +*Case insensitive* (``CIMultiDict`` and +``CIMultiDictProxy``) assume the *keys* are case +insensitive, e.g.:: + + >>> dct = CIMultiDict(key='val') + >>> 'Key' in dct + True + >>> dct['Key'] + 'val' + +*Keys* should be ``str`` or ``istr`` instances. + +The library has optional C Extensions for speed. + + +License +------- + +Apache 2 + +Library Installation +-------------------- + +.. code-block:: bash + + $ pip install multidict + +The library is Python 3 only! + +PyPI contains binary wheels for Linux, Windows and MacOS. If you want to install +``multidict`` on another operating system (or *Alpine Linux* inside a Docker) the +tarball will be used to compile the library from source. It requires a C compiler and +Python headers to be installed. + +To skip the compilation, please use the `MULTIDICT_NO_EXTENSIONS` environment variable, +e.g.: + +.. code-block:: bash + + $ MULTIDICT_NO_EXTENSIONS=1 pip install multidict + +Please note, the pure Python (uncompiled) version is about 20-50 times slower depending on +the usage scenario!!! + + + +Changelog +--------- +See `RTD page `_. diff --git a/env/Lib/site-packages/multidict-6.0.5.dist-info/RECORD b/env/Lib/site-packages/multidict-6.0.5.dist-info/RECORD new file mode 100644 index 0000000..f65dc95 --- /dev/null +++ b/env/Lib/site-packages/multidict-6.0.5.dist-info/RECORD @@ -0,0 +1,19 @@ +multidict-6.0.5.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +multidict-6.0.5.dist-info/LICENSE,sha256=k9Ealo4vDzY3PECBH_bSDhc_WMPKtYhM1mF7v9eVSSo,611 +multidict-6.0.5.dist-info/METADATA,sha256=h3huVEq0b4Cpmc-wiUEVMOyBh-BCjaO-0i9gTBlqaK0,4346 +multidict-6.0.5.dist-info/RECORD,, +multidict-6.0.5.dist-info/WHEEL,sha256=ircjsfhzblqgSzO8ow7-0pXK-RVqDqNRGQ8F650AUNM,102 +multidict-6.0.5.dist-info/top_level.txt,sha256=-euDElkk5_qkmfIJ7WiqCab02ZlSFZWynejKg59qZQQ,10 +multidict/__init__.py,sha256=psbRrP64CD22Wjoc_OoqG9QlkRGcaZfOFCoPmoUiMig,928 +multidict/__init__.pyi,sha256=SbgC2ew1NvNXWlRKs9o0KhW4moozgMqgQ0OA4Re5JQQ,4840 +multidict/__pycache__/__init__.cpython-311.pyc,, +multidict/__pycache__/_abc.cpython-311.pyc,, +multidict/__pycache__/_compat.cpython-311.pyc,, +multidict/__pycache__/_multidict_base.cpython-311.pyc,, +multidict/__pycache__/_multidict_py.cpython-311.pyc,, +multidict/_abc.py,sha256=Zvnrn4SBkrv4QTD7-ZzqNcoxw0f8KStLMPzGvBuGT2w,1190 +multidict/_compat.py,sha256=tjUGdP9ooiH6c2KJrvUbPRwcvjWerKlKU6InIviwh7w,316 +multidict/_multidict.cp311-win_amd64.pyd,sha256=MlVd79sERxTbquwoGCD6egwiZUXUBWG5BSlNLgvboQI,46592 +multidict/_multidict_base.py,sha256=XugkE78fXBmtzDdg2Yi9TrEhDexmL-6qJbFIG0viLMg,3791 +multidict/_multidict_py.py,sha256=57h4sYrRIu7EjMX4YpHVIZVrV9-q1KCW3F6rao10D3U,15050 +multidict/py.typed,sha256=e9bmbH3UFxsabQrnNFPG9qxIXztwbcM6IKDYnvZwprY,15 diff --git a/env/Lib/site-packages/multidict-6.0.5.dist-info/WHEEL b/env/Lib/site-packages/multidict-6.0.5.dist-info/WHEEL new file mode 100644 index 0000000..d60b004 --- /dev/null +++ b/env/Lib/site-packages/multidict-6.0.5.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.42.0) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/env/Lib/site-packages/multidict-6.0.5.dist-info/top_level.txt b/env/Lib/site-packages/multidict-6.0.5.dist-info/top_level.txt new file mode 100644 index 0000000..afcecdf --- /dev/null +++ b/env/Lib/site-packages/multidict-6.0.5.dist-info/top_level.txt @@ -0,0 +1 @@ +multidict diff --git a/env/Lib/site-packages/multidict/__init__.py b/env/Lib/site-packages/multidict/__init__.py new file mode 100644 index 0000000..23142ee --- /dev/null +++ b/env/Lib/site-packages/multidict/__init__.py @@ -0,0 +1,48 @@ +"""Multidict implementation. + +HTTP Headers and URL query string require specific data structure: +multidict. It behaves mostly like a dict but it can have +several values for the same key. +""" + +from ._abc import MultiMapping, MutableMultiMapping +from ._compat import USE_EXTENSIONS + +__all__ = ( + "MultiMapping", + "MutableMultiMapping", + "MultiDictProxy", + "CIMultiDictProxy", + "MultiDict", + "CIMultiDict", + "upstr", + "istr", + "getversion", +) + +__version__ = "6.0.5" + + +try: + if not USE_EXTENSIONS: + raise ImportError + from ._multidict import ( + CIMultiDict, + CIMultiDictProxy, + MultiDict, + MultiDictProxy, + getversion, + istr, + ) +except ImportError: # pragma: no cover + from ._multidict_py import ( + CIMultiDict, + CIMultiDictProxy, + MultiDict, + MultiDictProxy, + getversion, + istr, + ) + + +upstr = istr diff --git a/env/Lib/site-packages/multidict/__init__.pyi b/env/Lib/site-packages/multidict/__init__.pyi new file mode 100644 index 0000000..0940340 --- /dev/null +++ b/env/Lib/site-packages/multidict/__init__.pyi @@ -0,0 +1,152 @@ +import abc +from typing import ( + Generic, + Iterable, + Iterator, + Mapping, + MutableMapping, + TypeVar, + overload, +) + +class istr(str): ... + +upstr = istr + +_S = str | istr + +_T = TypeVar("_T") + +_T_co = TypeVar("_T_co", covariant=True) + +_D = TypeVar("_D") + +class MultiMapping(Mapping[_S, _T_co]): + @overload + @abc.abstractmethod + def getall(self, key: _S) -> list[_T_co]: ... + @overload + @abc.abstractmethod + def getall(self, key: _S, default: _D) -> list[_T_co] | _D: ... + @overload + @abc.abstractmethod + def getone(self, key: _S) -> _T_co: ... + @overload + @abc.abstractmethod + def getone(self, key: _S, default: _D) -> _T_co | _D: ... + +_Arg = ( + Mapping[str, _T] + | Mapping[istr, _T] + | dict[str, _T] + | dict[istr, _T] + | MultiMapping[_T] + | Iterable[tuple[str, _T]] + | Iterable[tuple[istr, _T]] +) + +class MutableMultiMapping(MultiMapping[_T], MutableMapping[_S, _T], Generic[_T]): + @abc.abstractmethod + def add(self, key: _S, value: _T) -> None: ... + @abc.abstractmethod + def extend(self, arg: _Arg[_T] = ..., **kwargs: _T) -> None: ... + @overload + @abc.abstractmethod + def popone(self, key: _S) -> _T: ... + @overload + @abc.abstractmethod + def popone(self, key: _S, default: _D) -> _T | _D: ... + @overload + @abc.abstractmethod + def popall(self, key: _S) -> list[_T]: ... + @overload + @abc.abstractmethod + def popall(self, key: _S, default: _D) -> list[_T] | _D: ... + +class MultiDict(MutableMultiMapping[_T], Generic[_T]): + def __init__(self, arg: _Arg[_T] = ..., **kwargs: _T) -> None: ... + def copy(self) -> MultiDict[_T]: ... + def __getitem__(self, k: _S) -> _T: ... + def __setitem__(self, k: _S, v: _T) -> None: ... + def __delitem__(self, v: _S) -> None: ... + def __iter__(self) -> Iterator[_S]: ... + def __len__(self) -> int: ... + @overload + def getall(self, key: _S) -> list[_T]: ... + @overload + def getall(self, key: _S, default: _D) -> list[_T] | _D: ... + @overload + def getone(self, key: _S) -> _T: ... + @overload + def getone(self, key: _S, default: _D) -> _T | _D: ... + def add(self, key: _S, value: _T) -> None: ... + def extend(self, arg: _Arg[_T] = ..., **kwargs: _T) -> None: ... + @overload + def popone(self, key: _S) -> _T: ... + @overload + def popone(self, key: _S, default: _D) -> _T | _D: ... + @overload + def popall(self, key: _S) -> list[_T]: ... + @overload + def popall(self, key: _S, default: _D) -> list[_T] | _D: ... + +class CIMultiDict(MutableMultiMapping[_T], Generic[_T]): + def __init__(self, arg: _Arg[_T] = ..., **kwargs: _T) -> None: ... + def copy(self) -> CIMultiDict[_T]: ... + def __getitem__(self, k: _S) -> _T: ... + def __setitem__(self, k: _S, v: _T) -> None: ... + def __delitem__(self, v: _S) -> None: ... + def __iter__(self) -> Iterator[_S]: ... + def __len__(self) -> int: ... + @overload + def getall(self, key: _S) -> list[_T]: ... + @overload + def getall(self, key: _S, default: _D) -> list[_T] | _D: ... + @overload + def getone(self, key: _S) -> _T: ... + @overload + def getone(self, key: _S, default: _D) -> _T | _D: ... + def add(self, key: _S, value: _T) -> None: ... + def extend(self, arg: _Arg[_T] = ..., **kwargs: _T) -> None: ... + @overload + def popone(self, key: _S) -> _T: ... + @overload + def popone(self, key: _S, default: _D) -> _T | _D: ... + @overload + def popall(self, key: _S) -> list[_T]: ... + @overload + def popall(self, key: _S, default: _D) -> list[_T] | _D: ... + +class MultiDictProxy(MultiMapping[_T], Generic[_T]): + def __init__(self, arg: MultiMapping[_T] | MutableMultiMapping[_T]) -> None: ... + def copy(self) -> MultiDict[_T]: ... + def __getitem__(self, k: _S) -> _T: ... + def __iter__(self) -> Iterator[_S]: ... + def __len__(self) -> int: ... + @overload + def getall(self, key: _S) -> list[_T]: ... + @overload + def getall(self, key: _S, default: _D) -> list[_T] | _D: ... + @overload + def getone(self, key: _S) -> _T: ... + @overload + def getone(self, key: _S, default: _D) -> _T | _D: ... + +class CIMultiDictProxy(MultiMapping[_T], Generic[_T]): + def __init__(self, arg: MultiMapping[_T] | MutableMultiMapping[_T]) -> None: ... + def __getitem__(self, k: _S) -> _T: ... + def __iter__(self) -> Iterator[_S]: ... + def __len__(self) -> int: ... + @overload + def getall(self, key: _S) -> list[_T]: ... + @overload + def getall(self, key: _S, default: _D) -> list[_T] | _D: ... + @overload + def getone(self, key: _S) -> _T: ... + @overload + def getone(self, key: _S, default: _D) -> _T | _D: ... + def copy(self) -> CIMultiDict[_T]: ... + +def getversion( + md: MultiDict[_T] | CIMultiDict[_T] | MultiDictProxy[_T] | CIMultiDictProxy[_T], +) -> int: ... diff --git a/env/Lib/site-packages/multidict/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/multidict/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..e711fda Binary files /dev/null and b/env/Lib/site-packages/multidict/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/multidict/__pycache__/_abc.cpython-311.pyc b/env/Lib/site-packages/multidict/__pycache__/_abc.cpython-311.pyc new file mode 100644 index 0000000..5f2de2a Binary files /dev/null and b/env/Lib/site-packages/multidict/__pycache__/_abc.cpython-311.pyc differ diff --git a/env/Lib/site-packages/multidict/__pycache__/_compat.cpython-311.pyc b/env/Lib/site-packages/multidict/__pycache__/_compat.cpython-311.pyc new file mode 100644 index 0000000..d8cd8b5 Binary files /dev/null and b/env/Lib/site-packages/multidict/__pycache__/_compat.cpython-311.pyc differ diff --git a/env/Lib/site-packages/multidict/__pycache__/_multidict_base.cpython-311.pyc b/env/Lib/site-packages/multidict/__pycache__/_multidict_base.cpython-311.pyc new file mode 100644 index 0000000..0186758 Binary files /dev/null and b/env/Lib/site-packages/multidict/__pycache__/_multidict_base.cpython-311.pyc differ diff --git a/env/Lib/site-packages/multidict/__pycache__/_multidict_py.cpython-311.pyc b/env/Lib/site-packages/multidict/__pycache__/_multidict_py.cpython-311.pyc new file mode 100644 index 0000000..8c2a919 Binary files /dev/null and b/env/Lib/site-packages/multidict/__pycache__/_multidict_py.cpython-311.pyc differ diff --git a/env/Lib/site-packages/multidict/_abc.py b/env/Lib/site-packages/multidict/_abc.py new file mode 100644 index 0000000..0603cdd --- /dev/null +++ b/env/Lib/site-packages/multidict/_abc.py @@ -0,0 +1,48 @@ +import abc +import sys +import types +from collections.abc import Mapping, MutableMapping + + +class _TypingMeta(abc.ABCMeta): + # A fake metaclass to satisfy typing deps in runtime + # basically MultiMapping[str] and other generic-like type instantiations + # are emulated. + # Note: real type hints are provided by __init__.pyi stub file + if sys.version_info >= (3, 9): + + def __getitem__(self, key): + return types.GenericAlias(self, key) + + else: + + def __getitem__(self, key): + return self + + +class MultiMapping(Mapping, metaclass=_TypingMeta): + @abc.abstractmethod + def getall(self, key, default=None): + raise KeyError + + @abc.abstractmethod + def getone(self, key, default=None): + raise KeyError + + +class MutableMultiMapping(MultiMapping, MutableMapping): + @abc.abstractmethod + def add(self, key, value): + raise NotImplementedError + + @abc.abstractmethod + def extend(self, *args, **kwargs): + raise NotImplementedError + + @abc.abstractmethod + def popone(self, key, default=None): + raise KeyError + + @abc.abstractmethod + def popall(self, key, default=None): + raise KeyError diff --git a/env/Lib/site-packages/multidict/_compat.py b/env/Lib/site-packages/multidict/_compat.py new file mode 100644 index 0000000..d1ff392 --- /dev/null +++ b/env/Lib/site-packages/multidict/_compat.py @@ -0,0 +1,14 @@ +import os +import platform + +NO_EXTENSIONS = bool(os.environ.get("MULTIDICT_NO_EXTENSIONS")) + +PYPY = platform.python_implementation() == "PyPy" + +USE_EXTENSIONS = not NO_EXTENSIONS and not PYPY + +if USE_EXTENSIONS: + try: + from . import _multidict # noqa + except ImportError: + USE_EXTENSIONS = False diff --git a/env/Lib/site-packages/multidict/_multidict.cp311-win_amd64.pyd b/env/Lib/site-packages/multidict/_multidict.cp311-win_amd64.pyd new file mode 100644 index 0000000..e8c9ac6 Binary files /dev/null and b/env/Lib/site-packages/multidict/_multidict.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/multidict/_multidict_base.py b/env/Lib/site-packages/multidict/_multidict_base.py new file mode 100644 index 0000000..3944665 --- /dev/null +++ b/env/Lib/site-packages/multidict/_multidict_base.py @@ -0,0 +1,144 @@ +from collections.abc import ItemsView, Iterable, KeysView, Set, ValuesView + + +def _abc_itemsview_register(view_cls): + ItemsView.register(view_cls) + + +def _abc_keysview_register(view_cls): + KeysView.register(view_cls) + + +def _abc_valuesview_register(view_cls): + ValuesView.register(view_cls) + + +def _viewbaseset_richcmp(view, other, op): + if op == 0: # < + if not isinstance(other, Set): + return NotImplemented + return len(view) < len(other) and view <= other + elif op == 1: # <= + if not isinstance(other, Set): + return NotImplemented + if len(view) > len(other): + return False + for elem in view: + if elem not in other: + return False + return True + elif op == 2: # == + if not isinstance(other, Set): + return NotImplemented + return len(view) == len(other) and view <= other + elif op == 3: # != + return not view == other + elif op == 4: # > + if not isinstance(other, Set): + return NotImplemented + return len(view) > len(other) and view >= other + elif op == 5: # >= + if not isinstance(other, Set): + return NotImplemented + if len(view) < len(other): + return False + for elem in other: + if elem not in view: + return False + return True + + +def _viewbaseset_and(view, other): + if not isinstance(other, Iterable): + return NotImplemented + if isinstance(view, Set): + view = set(iter(view)) + if isinstance(other, Set): + other = set(iter(other)) + if not isinstance(other, Set): + other = set(iter(other)) + return view & other + + +def _viewbaseset_or(view, other): + if not isinstance(other, Iterable): + return NotImplemented + if isinstance(view, Set): + view = set(iter(view)) + if isinstance(other, Set): + other = set(iter(other)) + if not isinstance(other, Set): + other = set(iter(other)) + return view | other + + +def _viewbaseset_sub(view, other): + if not isinstance(other, Iterable): + return NotImplemented + if isinstance(view, Set): + view = set(iter(view)) + if isinstance(other, Set): + other = set(iter(other)) + if not isinstance(other, Set): + other = set(iter(other)) + return view - other + + +def _viewbaseset_xor(view, other): + if not isinstance(other, Iterable): + return NotImplemented + if isinstance(view, Set): + view = set(iter(view)) + if isinstance(other, Set): + other = set(iter(other)) + if not isinstance(other, Set): + other = set(iter(other)) + return view ^ other + + +def _itemsview_isdisjoint(view, other): + "Return True if two sets have a null intersection." + for v in other: + if v in view: + return False + return True + + +def _itemsview_repr(view): + lst = [] + for k, v in view: + lst.append("{!r}: {!r}".format(k, v)) + body = ", ".join(lst) + return "{}({})".format(view.__class__.__name__, body) + + +def _keysview_isdisjoint(view, other): + "Return True if two sets have a null intersection." + for k in other: + if k in view: + return False + return True + + +def _keysview_repr(view): + lst = [] + for k in view: + lst.append("{!r}".format(k)) + body = ", ".join(lst) + return "{}({})".format(view.__class__.__name__, body) + + +def _valuesview_repr(view): + lst = [] + for v in view: + lst.append("{!r}".format(v)) + body = ", ".join(lst) + return "{}({})".format(view.__class__.__name__, body) + + +def _mdrepr(md): + lst = [] + for k, v in md.items(): + lst.append("'{}': {!r}".format(k, v)) + body = ", ".join(lst) + return "<{}({})>".format(md.__class__.__name__, body) diff --git a/env/Lib/site-packages/multidict/_multidict_py.py b/env/Lib/site-packages/multidict/_multidict_py.py new file mode 100644 index 0000000..79c45aa --- /dev/null +++ b/env/Lib/site-packages/multidict/_multidict_py.py @@ -0,0 +1,527 @@ +import sys +import types +from array import array +from collections import abc + +from ._abc import MultiMapping, MutableMultiMapping + +_marker = object() + +if sys.version_info >= (3, 9): + GenericAlias = types.GenericAlias +else: + + def GenericAlias(cls): + return cls + + +class istr(str): + + """Case insensitive str.""" + + __is_istr__ = True + + +upstr = istr # for relaxing backward compatibility problems + + +def getversion(md): + if not isinstance(md, _Base): + raise TypeError("Parameter should be multidict or proxy") + return md._impl._version + + +_version = array("Q", [0]) + + +class _Impl: + __slots__ = ("_items", "_version") + + def __init__(self): + self._items = [] + self.incr_version() + + def incr_version(self): + global _version + v = _version + v[0] += 1 + self._version = v[0] + + if sys.implementation.name != "pypy": + + def __sizeof__(self): + return object.__sizeof__(self) + sys.getsizeof(self._items) + + +class _Base: + def _title(self, key): + return key + + def getall(self, key, default=_marker): + """Return a list of all values matching the key.""" + identity = self._title(key) + res = [v for i, k, v in self._impl._items if i == identity] + if res: + return res + if not res and default is not _marker: + return default + raise KeyError("Key not found: %r" % key) + + def getone(self, key, default=_marker): + """Get first value matching the key. + + Raises KeyError if the key is not found and no default is provided. + """ + identity = self._title(key) + for i, k, v in self._impl._items: + if i == identity: + return v + if default is not _marker: + return default + raise KeyError("Key not found: %r" % key) + + # Mapping interface # + + def __getitem__(self, key): + return self.getone(key) + + def get(self, key, default=None): + """Get first value matching the key. + + If the key is not found, returns the default (or None if no default is provided) + """ + return self.getone(key, default) + + def __iter__(self): + return iter(self.keys()) + + def __len__(self): + return len(self._impl._items) + + def keys(self): + """Return a new view of the dictionary's keys.""" + return _KeysView(self._impl) + + def items(self): + """Return a new view of the dictionary's items *(key, value) pairs).""" + return _ItemsView(self._impl) + + def values(self): + """Return a new view of the dictionary's values.""" + return _ValuesView(self._impl) + + def __eq__(self, other): + if not isinstance(other, abc.Mapping): + return NotImplemented + if isinstance(other, _Base): + lft = self._impl._items + rht = other._impl._items + if len(lft) != len(rht): + return False + for (i1, k2, v1), (i2, k2, v2) in zip(lft, rht): + if i1 != i2 or v1 != v2: + return False + return True + if len(self._impl._items) != len(other): + return False + for k, v in self.items(): + nv = other.get(k, _marker) + if v != nv: + return False + return True + + def __contains__(self, key): + identity = self._title(key) + for i, k, v in self._impl._items: + if i == identity: + return True + return False + + def __repr__(self): + body = ", ".join("'{}': {!r}".format(k, v) for k, v in self.items()) + return "<{}({})>".format(self.__class__.__name__, body) + + __class_getitem__ = classmethod(GenericAlias) + + +class MultiDictProxy(_Base, MultiMapping): + """Read-only proxy for MultiDict instance.""" + + def __init__(self, arg): + if not isinstance(arg, (MultiDict, MultiDictProxy)): + raise TypeError( + "ctor requires MultiDict or MultiDictProxy instance" + ", not {}".format(type(arg)) + ) + + self._impl = arg._impl + + def __reduce__(self): + raise TypeError("can't pickle {} objects".format(self.__class__.__name__)) + + def copy(self): + """Return a copy of itself.""" + return MultiDict(self.items()) + + +class CIMultiDictProxy(MultiDictProxy): + """Read-only proxy for CIMultiDict instance.""" + + def __init__(self, arg): + if not isinstance(arg, (CIMultiDict, CIMultiDictProxy)): + raise TypeError( + "ctor requires CIMultiDict or CIMultiDictProxy instance" + ", not {}".format(type(arg)) + ) + + self._impl = arg._impl + + def _title(self, key): + return key.title() + + def copy(self): + """Return a copy of itself.""" + return CIMultiDict(self.items()) + + +class MultiDict(_Base, MutableMultiMapping): + """Dictionary with the support for duplicate keys.""" + + def __init__(self, *args, **kwargs): + self._impl = _Impl() + + self._extend(args, kwargs, self.__class__.__name__, self._extend_items) + + if sys.implementation.name != "pypy": + + def __sizeof__(self): + return object.__sizeof__(self) + sys.getsizeof(self._impl) + + def __reduce__(self): + return (self.__class__, (list(self.items()),)) + + def _title(self, key): + return key + + def _key(self, key): + if isinstance(key, str): + return key + else: + raise TypeError( + "MultiDict keys should be either str " "or subclasses of str" + ) + + def add(self, key, value): + identity = self._title(key) + self._impl._items.append((identity, self._key(key), value)) + self._impl.incr_version() + + def copy(self): + """Return a copy of itself.""" + cls = self.__class__ + return cls(self.items()) + + __copy__ = copy + + def extend(self, *args, **kwargs): + """Extend current MultiDict with more values. + + This method must be used instead of update. + """ + self._extend(args, kwargs, "extend", self._extend_items) + + def _extend(self, args, kwargs, name, method): + if len(args) > 1: + raise TypeError( + "{} takes at most 1 positional argument" + " ({} given)".format(name, len(args)) + ) + if args: + arg = args[0] + if isinstance(args[0], (MultiDict, MultiDictProxy)) and not kwargs: + items = arg._impl._items + else: + if hasattr(arg, "items"): + arg = arg.items() + if kwargs: + arg = list(arg) + arg.extend(list(kwargs.items())) + items = [] + for item in arg: + if not len(item) == 2: + raise TypeError( + "{} takes either dict or list of (key, value) " + "tuples".format(name) + ) + items.append((self._title(item[0]), self._key(item[0]), item[1])) + + method(items) + else: + method( + [ + (self._title(key), self._key(key), value) + for key, value in kwargs.items() + ] + ) + + def _extend_items(self, items): + for identity, key, value in items: + self.add(key, value) + + def clear(self): + """Remove all items from MultiDict.""" + self._impl._items.clear() + self._impl.incr_version() + + # Mapping interface # + + def __setitem__(self, key, value): + self._replace(key, value) + + def __delitem__(self, key): + identity = self._title(key) + items = self._impl._items + found = False + for i in range(len(items) - 1, -1, -1): + if items[i][0] == identity: + del items[i] + found = True + if not found: + raise KeyError(key) + else: + self._impl.incr_version() + + def setdefault(self, key, default=None): + """Return value for key, set value to default if key is not present.""" + identity = self._title(key) + for i, k, v in self._impl._items: + if i == identity: + return v + self.add(key, default) + return default + + def popone(self, key, default=_marker): + """Remove specified key and return the corresponding value. + + If key is not found, d is returned if given, otherwise + KeyError is raised. + + """ + identity = self._title(key) + for i in range(len(self._impl._items)): + if self._impl._items[i][0] == identity: + value = self._impl._items[i][2] + del self._impl._items[i] + self._impl.incr_version() + return value + if default is _marker: + raise KeyError(key) + else: + return default + + pop = popone # type: ignore + + def popall(self, key, default=_marker): + """Remove all occurrences of key and return the list of corresponding + values. + + If key is not found, default is returned if given, otherwise + KeyError is raised. + + """ + found = False + identity = self._title(key) + ret = [] + for i in range(len(self._impl._items) - 1, -1, -1): + item = self._impl._items[i] + if item[0] == identity: + ret.append(item[2]) + del self._impl._items[i] + self._impl.incr_version() + found = True + if not found: + if default is _marker: + raise KeyError(key) + else: + return default + else: + ret.reverse() + return ret + + def popitem(self): + """Remove and return an arbitrary (key, value) pair.""" + if self._impl._items: + i = self._impl._items.pop(0) + self._impl.incr_version() + return i[1], i[2] + else: + raise KeyError("empty multidict") + + def update(self, *args, **kwargs): + """Update the dictionary from *other*, overwriting existing keys.""" + self._extend(args, kwargs, "update", self._update_items) + + def _update_items(self, items): + if not items: + return + used_keys = {} + for identity, key, value in items: + start = used_keys.get(identity, 0) + for i in range(start, len(self._impl._items)): + item = self._impl._items[i] + if item[0] == identity: + used_keys[identity] = i + 1 + self._impl._items[i] = (identity, key, value) + break + else: + self._impl._items.append((identity, key, value)) + used_keys[identity] = len(self._impl._items) + + # drop tails + i = 0 + while i < len(self._impl._items): + item = self._impl._items[i] + identity = item[0] + pos = used_keys.get(identity) + if pos is None: + i += 1 + continue + if i >= pos: + del self._impl._items[i] + else: + i += 1 + + self._impl.incr_version() + + def _replace(self, key, value): + key = self._key(key) + identity = self._title(key) + items = self._impl._items + + for i in range(len(items)): + item = items[i] + if item[0] == identity: + items[i] = (identity, key, value) + # i points to last found item + rgt = i + self._impl.incr_version() + break + else: + self._impl._items.append((identity, key, value)) + self._impl.incr_version() + return + + # remove all tail items + i = rgt + 1 + while i < len(items): + item = items[i] + if item[0] == identity: + del items[i] + else: + i += 1 + + +class CIMultiDict(MultiDict): + """Dictionary with the support for duplicate case-insensitive keys.""" + + def _title(self, key): + return key.title() + + +class _Iter: + __slots__ = ("_size", "_iter") + + def __init__(self, size, iterator): + self._size = size + self._iter = iterator + + def __iter__(self): + return self + + def __next__(self): + return next(self._iter) + + def __length_hint__(self): + return self._size + + +class _ViewBase: + def __init__(self, impl): + self._impl = impl + + def __len__(self): + return len(self._impl._items) + + +class _ItemsView(_ViewBase, abc.ItemsView): + def __contains__(self, item): + assert isinstance(item, tuple) or isinstance(item, list) + assert len(item) == 2 + for i, k, v in self._impl._items: + if item[0] == k and item[1] == v: + return True + return False + + def __iter__(self): + return _Iter(len(self), self._iter(self._impl._version)) + + def _iter(self, version): + for i, k, v in self._impl._items: + if version != self._impl._version: + raise RuntimeError("Dictionary changed during iteration") + yield k, v + + def __repr__(self): + lst = [] + for item in self._impl._items: + lst.append("{!r}: {!r}".format(item[1], item[2])) + body = ", ".join(lst) + return "{}({})".format(self.__class__.__name__, body) + + +class _ValuesView(_ViewBase, abc.ValuesView): + def __contains__(self, value): + for item in self._impl._items: + if item[2] == value: + return True + return False + + def __iter__(self): + return _Iter(len(self), self._iter(self._impl._version)) + + def _iter(self, version): + for item in self._impl._items: + if version != self._impl._version: + raise RuntimeError("Dictionary changed during iteration") + yield item[2] + + def __repr__(self): + lst = [] + for item in self._impl._items: + lst.append("{!r}".format(item[2])) + body = ", ".join(lst) + return "{}({})".format(self.__class__.__name__, body) + + +class _KeysView(_ViewBase, abc.KeysView): + def __contains__(self, key): + for item in self._impl._items: + if item[1] == key: + return True + return False + + def __iter__(self): + return _Iter(len(self), self._iter(self._impl._version)) + + def _iter(self, version): + for item in self._impl._items: + if version != self._impl._version: + raise RuntimeError("Dictionary changed during iteration") + yield item[1] + + def __repr__(self): + lst = [] + for item in self._impl._items: + lst.append("{!r}".format(item[1])) + body = ", ".join(lst) + return "{}({})".format(self.__class__.__name__, body) diff --git a/env/Lib/site-packages/multidict/py.typed b/env/Lib/site-packages/multidict/py.typed new file mode 100644 index 0000000..dfe8cc0 --- /dev/null +++ b/env/Lib/site-packages/multidict/py.typed @@ -0,0 +1 @@ +PEP-561 marker. \ No newline at end of file diff --git a/env/Lib/site-packages/psycopg2-2.9.9.dist-info/INSTALLER b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/psycopg2-2.9.9.dist-info/LICENSE b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/LICENSE new file mode 100644 index 0000000..9029e70 --- /dev/null +++ b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/LICENSE @@ -0,0 +1,49 @@ +psycopg2 and the LGPL +--------------------- + +psycopg2 is free software: you can redistribute it and/or modify it +under the terms of the GNU Lesser General Public License as published +by the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +psycopg2 is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +License for more details. + +In addition, as a special exception, the copyright holders give +permission to link this program with the OpenSSL library (or with +modified versions of OpenSSL that use the same license as OpenSSL), +and distribute linked combinations including the two. + +You must obey the GNU Lesser General Public License in all respects for +all of the code used other than OpenSSL. If you modify file(s) with this +exception, you may extend this exception to your version of the file(s), +but you are not obligated to do so. If you do not wish to do so, delete +this exception statement from your version. If you delete this exception +statement from all source files in the program, then also delete it here. + +You should have received a copy of the GNU Lesser General Public License +along with psycopg2 (see the doc/ directory.) +If not, see . + + +Alternative licenses +-------------------- + +The following BSD-like license applies (at your option) to the files following +the pattern ``psycopg/adapter*.{h,c}`` and ``psycopg/microprotocol*.{h,c}``: + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this + software in a product, an acknowledgment in the product documentation + would be appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not + be misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source distribution. diff --git a/env/Lib/site-packages/psycopg2-2.9.9.dist-info/METADATA b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/METADATA new file mode 100644 index 0000000..87dc149 --- /dev/null +++ b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/METADATA @@ -0,0 +1,110 @@ +Metadata-Version: 2.1 +Name: psycopg2 +Version: 2.9.9 +Summary: psycopg2 - Python-PostgreSQL Database Adapter +Home-page: https://psycopg.org/ +Author: Federico Di Gregorio +Author-email: fog@initd.org +Maintainer: Daniele Varrazzo +Maintainer-email: daniele.varrazzo@gmail.com +License: LGPL with exceptions +Project-URL: Homepage, https://psycopg.org/ +Project-URL: Documentation, https://www.psycopg.org/docs/ +Project-URL: Code, https://github.com/psycopg/psycopg2 +Project-URL: Issue Tracker, https://github.com/psycopg/psycopg2/issues +Project-URL: Download, https://pypi.org/project/psycopg2/ +Platform: any +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL) +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: C +Classifier: Programming Language :: SQL +Classifier: Topic :: Database +Classifier: Topic :: Database :: Front-Ends +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: Unix +Requires-Python: >=3.7 +License-File: LICENSE + +Psycopg is the most popular PostgreSQL database adapter for the Python +programming language. Its main features are the complete implementation of +the Python DB API 2.0 specification and the thread safety (several threads can +share the same connection). It was designed for heavily multi-threaded +applications that create and destroy lots of cursors and make a large number +of concurrent "INSERT"s or "UPDATE"s. + +Psycopg 2 is mostly implemented in C as a libpq wrapper, resulting in being +both efficient and secure. It features client-side and server-side cursors, +asynchronous communication and notifications, "COPY TO/COPY FROM" support. +Many Python types are supported out-of-the-box and adapted to matching +PostgreSQL data types; adaptation can be extended and customized thanks to a +flexible objects adaptation system. + +Psycopg 2 is both Unicode and Python 3 friendly. + + +Documentation +------------- + +Documentation is included in the ``doc`` directory and is `available online`__. + +.. __: https://www.psycopg.org/docs/ + +For any other resource (source code repository, bug tracker, mailing list) +please check the `project homepage`__. + +.. __: https://psycopg.org/ + + +Installation +------------ + +Building Psycopg requires a few prerequisites (a C compiler, some development +packages): please check the install_ and the faq_ documents in the ``doc`` dir +or online for the details. + +If prerequisites are met, you can install psycopg like any other Python +package, using ``pip`` to download it from PyPI_:: + + $ pip install psycopg2 + +or using ``setup.py`` if you have downloaded the source package locally:: + + $ python setup.py build + $ sudo python setup.py install + +You can also obtain a stand-alone package, not requiring a compiler or +external libraries, by installing the `psycopg2-binary`_ package from PyPI:: + + $ pip install psycopg2-binary + +The binary package is a practical choice for development and testing but in +production it is advised to use the package built from sources. + +.. _PyPI: https://pypi.org/project/psycopg2/ +.. _psycopg2-binary: https://pypi.org/project/psycopg2-binary/ +.. _install: https://www.psycopg.org/docs/install.html#install-from-source +.. _faq: https://www.psycopg.org/docs/faq.html#faq-compile + +:Linux/OSX: |gh-actions| +:Windows: |appveyor| + +.. |gh-actions| image:: https://github.com/psycopg/psycopg2/actions/workflows/tests.yml/badge.svg + :target: https://github.com/psycopg/psycopg2/actions/workflows/tests.yml + :alt: Linux and OSX build status + +.. |appveyor| image:: https://ci.appveyor.com/api/projects/status/github/psycopg/psycopg2?branch=master&svg=true + :target: https://ci.appveyor.com/project/psycopg/psycopg2/branch/master + :alt: Windows build status diff --git a/env/Lib/site-packages/psycopg2-2.9.9.dist-info/RECORD b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/RECORD new file mode 100644 index 0000000..ef64013 --- /dev/null +++ b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/RECORD @@ -0,0 +1,30 @@ +psycopg2-2.9.9.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +psycopg2-2.9.9.dist-info/LICENSE,sha256=lhS4XfyacsWyyjMUTB1-HtOxwpdFnZ-yimpXYsLo1xs,2238 +psycopg2-2.9.9.dist-info/METADATA,sha256=m-vTX7sYOv5wXKcTJhY3qIaz5SiHmyig-w7neDM_VL8,4548 +psycopg2-2.9.9.dist-info/RECORD,, +psycopg2-2.9.9.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +psycopg2-2.9.9.dist-info/WHEEL,sha256=badvNS-y9fEq0X-qzdZYvql_JFjI7Xfw-wR8FsjoK0I,102 +psycopg2-2.9.9.dist-info/top_level.txt,sha256=7dHGpLqQ3w-vGmGEVn-7uK90qU9fyrGdWWi7S-gTcnM,9 +psycopg2/__init__.py,sha256=9mo5Qd0uWHiEBx2CdogGos2kNqtlNNGzbtYlGC0hWS8,4768 +psycopg2/__pycache__/__init__.cpython-311.pyc,, +psycopg2/__pycache__/_ipaddress.cpython-311.pyc,, +psycopg2/__pycache__/_json.cpython-311.pyc,, +psycopg2/__pycache__/_range.cpython-311.pyc,, +psycopg2/__pycache__/errorcodes.cpython-311.pyc,, +psycopg2/__pycache__/errors.cpython-311.pyc,, +psycopg2/__pycache__/extensions.cpython-311.pyc,, +psycopg2/__pycache__/extras.cpython-311.pyc,, +psycopg2/__pycache__/pool.cpython-311.pyc,, +psycopg2/__pycache__/sql.cpython-311.pyc,, +psycopg2/__pycache__/tz.cpython-311.pyc,, +psycopg2/_ipaddress.py,sha256=jkuyhLgqUGRBcLNWDM8QJysV6q1Npc_RYH4_kE7JZPU,2922 +psycopg2/_json.py,sha256=XPn4PnzbTg1Dcqz7n1JMv5dKhB5VFV6834GEtxSawt0,7153 +psycopg2/_psycopg.cp311-win_amd64.pyd,sha256=fqbVB1hiveZXE5spFuUUyrHgsAfwhZNzqhLkREdGb7o,2416128 +psycopg2/_range.py,sha256=sXeenGraJEEw2I3mc8RlmNivy2jMg7zWoanDes2Ywp8,18494 +psycopg2/errorcodes.py,sha256=jb1SkuGq5zJT7F99GFAUi3VQH8GbsB7zRHiLsAWAU0Q,14362 +psycopg2/errors.py,sha256=aAS4dJyTg1bsDzJDCRQAMB_s7zv-Q4yB6Yvih26I-0M,1425 +psycopg2/extensions.py,sha256=CG0kG5vL8Ot503UGlDXXJJFdFWLg4HE2_c1-lLOLc8M,6797 +psycopg2/extras.py,sha256=oBfrdvtWn8ITxc3x-h2h6IwHUsWdVqCdf4Gphb0JqY8,44215 +psycopg2/pool.py,sha256=UGEt8IdP3xNc2PGYNlG4sQvg8nhf4aeCnz39hTR0H8I,6316 +psycopg2/sql.py,sha256=OcFEAmpe2aMfrx0MEk4Lx00XvXXJCmvllaOVbJY-yoE,14779 +psycopg2/tz.py,sha256=r95kK7eGSpOYr_luCyYsznHMzjl52sLjsnSPXkXLzRI,4870 diff --git a/env/Lib/site-packages/psycopg2-2.9.9.dist-info/REQUESTED b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/REQUESTED new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/psycopg2-2.9.9.dist-info/WHEEL b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/WHEEL new file mode 100644 index 0000000..6d16045 --- /dev/null +++ b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/env/Lib/site-packages/psycopg2-2.9.9.dist-info/top_level.txt b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/top_level.txt new file mode 100644 index 0000000..658130b --- /dev/null +++ b/env/Lib/site-packages/psycopg2-2.9.9.dist-info/top_level.txt @@ -0,0 +1 @@ +psycopg2 diff --git a/env/Lib/site-packages/psycopg2/__init__.py b/env/Lib/site-packages/psycopg2/__init__.py new file mode 100644 index 0000000..59a8938 --- /dev/null +++ b/env/Lib/site-packages/psycopg2/__init__.py @@ -0,0 +1,126 @@ +"""A Python driver for PostgreSQL + +psycopg is a PostgreSQL_ database adapter for the Python_ programming +language. This is version 2, a complete rewrite of the original code to +provide new-style classes for connection and cursor objects and other sweet +candies. Like the original, psycopg 2 was written with the aim of being very +small and fast, and stable as a rock. + +Homepage: https://psycopg.org/ + +.. _PostgreSQL: https://www.postgresql.org/ +.. _Python: https://www.python.org/ + +:Groups: + * `Connections creation`: connect + * `Value objects constructors`: Binary, Date, DateFromTicks, Time, + TimeFromTicks, Timestamp, TimestampFromTicks +""" +# psycopg/__init__.py - initialization of the psycopg module +# +# Copyright (C) 2003-2019 Federico Di Gregorio +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +# Import modules needed by _psycopg to allow tools like py2exe to do +# their work without bothering about the module dependencies. + +# Note: the first internal import should be _psycopg, otherwise the real cause +# of a failed loading of the C module may get hidden, see +# https://archives.postgresql.org/psycopg/2011-02/msg00044.php + +# Import the DBAPI-2.0 stuff into top-level module. + +from psycopg2._psycopg import ( # noqa + BINARY, NUMBER, STRING, DATETIME, ROWID, + + Binary, Date, Time, Timestamp, + DateFromTicks, TimeFromTicks, TimestampFromTicks, + + Error, Warning, DataError, DatabaseError, ProgrammingError, IntegrityError, + InterfaceError, InternalError, NotSupportedError, OperationalError, + + _connect, apilevel, threadsafety, paramstyle, + __version__, __libpq_version__, +) + + +# Register default adapters. + +from psycopg2 import extensions as _ext +_ext.register_adapter(tuple, _ext.SQL_IN) +_ext.register_adapter(type(None), _ext.NoneAdapter) + +# Register the Decimal adapter here instead of in the C layer. +# This way a new class is registered for each sub-interpreter. +# See ticket #52 +from decimal import Decimal # noqa +from psycopg2._psycopg import Decimal as Adapter # noqa +_ext.register_adapter(Decimal, Adapter) +del Decimal, Adapter + + +def connect(dsn=None, connection_factory=None, cursor_factory=None, **kwargs): + """ + Create a new database connection. + + The connection parameters can be specified as a string: + + conn = psycopg2.connect("dbname=test user=postgres password=secret") + + or using a set of keyword arguments: + + conn = psycopg2.connect(database="test", user="postgres", password="secret") + + Or as a mix of both. The basic connection parameters are: + + - *dbname*: the database name + - *database*: the database name (only as keyword argument) + - *user*: user name used to authenticate + - *password*: password used to authenticate + - *host*: database host address (defaults to UNIX socket if not provided) + - *port*: connection port number (defaults to 5432 if not provided) + + Using the *connection_factory* parameter a different class or connections + factory can be specified. It should be a callable object taking a dsn + argument. + + Using the *cursor_factory* parameter, a new default cursor factory will be + used by cursor(). + + Using *async*=True an asynchronous connection will be created. *async_* is + a valid alias (for Python versions where ``async`` is a keyword). + + Any other keyword parameter will be passed to the underlying client + library: the list of supported parameters depends on the library version. + + """ + kwasync = {} + if 'async' in kwargs: + kwasync['async'] = kwargs.pop('async') + if 'async_' in kwargs: + kwasync['async_'] = kwargs.pop('async_') + + dsn = _ext.make_dsn(dsn, **kwargs) + conn = _connect(dsn, connection_factory=connection_factory, **kwasync) + if cursor_factory is not None: + conn.cursor_factory = cursor_factory + + return conn diff --git a/env/Lib/site-packages/psycopg2/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..a5cab97 Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/_ipaddress.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/_ipaddress.cpython-311.pyc new file mode 100644 index 0000000..1db574d Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/_ipaddress.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/_json.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/_json.cpython-311.pyc new file mode 100644 index 0000000..5f4fda6 Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/_json.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/_range.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/_range.cpython-311.pyc new file mode 100644 index 0000000..73b0d73 Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/_range.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/errorcodes.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/errorcodes.cpython-311.pyc new file mode 100644 index 0000000..c5acf7b Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/errorcodes.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/errors.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000..ac7aa3f Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/errors.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/extensions.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/extensions.cpython-311.pyc new file mode 100644 index 0000000..651a590 Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/extensions.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/extras.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/extras.cpython-311.pyc new file mode 100644 index 0000000..d6c6e98 Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/extras.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/pool.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/pool.cpython-311.pyc new file mode 100644 index 0000000..90f3c2b Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/pool.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/sql.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/sql.cpython-311.pyc new file mode 100644 index 0000000..01809b9 Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/sql.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/__pycache__/tz.cpython-311.pyc b/env/Lib/site-packages/psycopg2/__pycache__/tz.cpython-311.pyc new file mode 100644 index 0000000..a9c6e5b Binary files /dev/null and b/env/Lib/site-packages/psycopg2/__pycache__/tz.cpython-311.pyc differ diff --git a/env/Lib/site-packages/psycopg2/_ipaddress.py b/env/Lib/site-packages/psycopg2/_ipaddress.py new file mode 100644 index 0000000..d38566c --- /dev/null +++ b/env/Lib/site-packages/psycopg2/_ipaddress.py @@ -0,0 +1,90 @@ +"""Implementation of the ipaddres-based network types adaptation +""" + +# psycopg/_ipaddress.py - Ipaddres-based network types adaptation +# +# Copyright (C) 2016-2019 Daniele Varrazzo +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +from psycopg2.extensions import ( + new_type, new_array_type, register_type, register_adapter, QuotedString) + +# The module is imported on register_ipaddress +ipaddress = None + +# The typecasters are created only once +_casters = None + + +def register_ipaddress(conn_or_curs=None): + """ + Register conversion support between `ipaddress` objects and `network types`__. + + :param conn_or_curs: the scope where to register the type casters. + If `!None` register them globally. + + After the function is called, PostgreSQL :sql:`inet` values will be + converted into `~ipaddress.IPv4Interface` or `~ipaddress.IPv6Interface` + objects, :sql:`cidr` values into into `~ipaddress.IPv4Network` or + `~ipaddress.IPv6Network`. + + .. __: https://www.postgresql.org/docs/current/static/datatype-net-types.html + """ + global ipaddress + import ipaddress + + global _casters + if _casters is None: + _casters = _make_casters() + + for c in _casters: + register_type(c, conn_or_curs) + + for t in [ipaddress.IPv4Interface, ipaddress.IPv6Interface, + ipaddress.IPv4Network, ipaddress.IPv6Network]: + register_adapter(t, adapt_ipaddress) + + +def _make_casters(): + inet = new_type((869,), 'INET', cast_interface) + ainet = new_array_type((1041,), 'INET[]', inet) + + cidr = new_type((650,), 'CIDR', cast_network) + acidr = new_array_type((651,), 'CIDR[]', cidr) + + return [inet, ainet, cidr, acidr] + + +def cast_interface(s, cur=None): + if s is None: + return None + # Py2 version force the use of unicode. meh. + return ipaddress.ip_interface(str(s)) + + +def cast_network(s, cur=None): + if s is None: + return None + return ipaddress.ip_network(str(s)) + + +def adapt_ipaddress(obj): + return QuotedString(str(obj)) diff --git a/env/Lib/site-packages/psycopg2/_json.py b/env/Lib/site-packages/psycopg2/_json.py new file mode 100644 index 0000000..9502422 --- /dev/null +++ b/env/Lib/site-packages/psycopg2/_json.py @@ -0,0 +1,199 @@ +"""Implementation of the JSON adaptation objects + +This module exists to avoid a circular import problem: pyscopg2.extras depends +on psycopg2.extension, so I can't create the default JSON typecasters in +extensions importing register_json from extras. +""" + +# psycopg/_json.py - Implementation of the JSON adaptation objects +# +# Copyright (C) 2012-2019 Daniele Varrazzo +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +import json + +from psycopg2._psycopg import ISQLQuote, QuotedString +from psycopg2._psycopg import new_type, new_array_type, register_type + + +# oids from PostgreSQL 9.2 +JSON_OID = 114 +JSONARRAY_OID = 199 + +# oids from PostgreSQL 9.4 +JSONB_OID = 3802 +JSONBARRAY_OID = 3807 + + +class Json: + """ + An `~psycopg2.extensions.ISQLQuote` wrapper to adapt a Python object to + :sql:`json` data type. + + `!Json` can be used to wrap any object supported by the provided *dumps* + function. If none is provided, the standard :py:func:`json.dumps()` is + used. + + """ + def __init__(self, adapted, dumps=None): + self.adapted = adapted + self._conn = None + self._dumps = dumps or json.dumps + + def __conform__(self, proto): + if proto is ISQLQuote: + return self + + def dumps(self, obj): + """Serialize *obj* in JSON format. + + The default is to call `!json.dumps()` or the *dumps* function + provided in the constructor. You can override this method to create a + customized JSON wrapper. + """ + return self._dumps(obj) + + def prepare(self, conn): + self._conn = conn + + def getquoted(self): + s = self.dumps(self.adapted) + qs = QuotedString(s) + if self._conn is not None: + qs.prepare(self._conn) + return qs.getquoted() + + def __str__(self): + # getquoted is binary + return self.getquoted().decode('ascii', 'replace') + + +def register_json(conn_or_curs=None, globally=False, loads=None, + oid=None, array_oid=None, name='json'): + """Create and register typecasters converting :sql:`json` type to Python objects. + + :param conn_or_curs: a connection or cursor used to find the :sql:`json` + and :sql:`json[]` oids; the typecasters are registered in a scope + limited to this object, unless *globally* is set to `!True`. It can be + `!None` if the oids are provided + :param globally: if `!False` register the typecasters only on + *conn_or_curs*, otherwise register them globally + :param loads: the function used to parse the data into a Python object. If + `!None` use `!json.loads()`, where `!json` is the module chosen + according to the Python version (see above) + :param oid: the OID of the :sql:`json` type if known; If not, it will be + queried on *conn_or_curs* + :param array_oid: the OID of the :sql:`json[]` array type if known; + if not, it will be queried on *conn_or_curs* + :param name: the name of the data type to look for in *conn_or_curs* + + The connection or cursor passed to the function will be used to query the + database and look for the OID of the :sql:`json` type (or an alternative + type if *name* if provided). No query is performed if *oid* and *array_oid* + are provided. Raise `~psycopg2.ProgrammingError` if the type is not found. + + """ + if oid is None: + oid, array_oid = _get_json_oids(conn_or_curs, name) + + JSON, JSONARRAY = _create_json_typecasters( + oid, array_oid, loads=loads, name=name.upper()) + + register_type(JSON, not globally and conn_or_curs or None) + + if JSONARRAY is not None: + register_type(JSONARRAY, not globally and conn_or_curs or None) + + return JSON, JSONARRAY + + +def register_default_json(conn_or_curs=None, globally=False, loads=None): + """ + Create and register :sql:`json` typecasters for PostgreSQL 9.2 and following. + + Since PostgreSQL 9.2 :sql:`json` is a builtin type, hence its oid is known + and fixed. This function allows specifying a customized *loads* function + for the default :sql:`json` type without querying the database. + All the parameters have the same meaning of `register_json()`. + """ + return register_json(conn_or_curs=conn_or_curs, globally=globally, + loads=loads, oid=JSON_OID, array_oid=JSONARRAY_OID) + + +def register_default_jsonb(conn_or_curs=None, globally=False, loads=None): + """ + Create and register :sql:`jsonb` typecasters for PostgreSQL 9.4 and following. + + As in `register_default_json()`, the function allows to register a + customized *loads* function for the :sql:`jsonb` type at its known oid for + PostgreSQL 9.4 and following versions. All the parameters have the same + meaning of `register_json()`. + """ + return register_json(conn_or_curs=conn_or_curs, globally=globally, + loads=loads, oid=JSONB_OID, array_oid=JSONBARRAY_OID, name='jsonb') + + +def _create_json_typecasters(oid, array_oid, loads=None, name='JSON'): + """Create typecasters for json data type.""" + if loads is None: + loads = json.loads + + def typecast_json(s, cur): + if s is None: + return None + return loads(s) + + JSON = new_type((oid, ), name, typecast_json) + if array_oid is not None: + JSONARRAY = new_array_type((array_oid, ), f"{name}ARRAY", JSON) + else: + JSONARRAY = None + + return JSON, JSONARRAY + + +def _get_json_oids(conn_or_curs, name='json'): + # lazy imports + from psycopg2.extensions import STATUS_IN_TRANSACTION + from psycopg2.extras import _solve_conn_curs + + conn, curs = _solve_conn_curs(conn_or_curs) + + # Store the transaction status of the connection to revert it after use + conn_status = conn.status + + # column typarray not available before PG 8.3 + typarray = conn.info.server_version >= 80300 and "typarray" or "NULL" + + # get the oid for the hstore + curs.execute( + "SELECT t.oid, %s FROM pg_type t WHERE t.typname = %%s;" + % typarray, (name,)) + r = curs.fetchone() + + # revert the status of the connection as before the command + if conn_status != STATUS_IN_TRANSACTION and not conn.autocommit: + conn.rollback() + + if not r: + raise conn.ProgrammingError(f"{name} data type not found") + + return r diff --git a/env/Lib/site-packages/psycopg2/_psycopg.cp311-win_amd64.pyd b/env/Lib/site-packages/psycopg2/_psycopg.cp311-win_amd64.pyd new file mode 100644 index 0000000..c21a35a Binary files /dev/null and b/env/Lib/site-packages/psycopg2/_psycopg.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/psycopg2/_range.py b/env/Lib/site-packages/psycopg2/_range.py new file mode 100644 index 0000000..64bae07 --- /dev/null +++ b/env/Lib/site-packages/psycopg2/_range.py @@ -0,0 +1,554 @@ +"""Implementation of the Range type and adaptation + +""" + +# psycopg/_range.py - Implementation of the Range type and adaptation +# +# Copyright (C) 2012-2019 Daniele Varrazzo +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +import re + +from psycopg2._psycopg import ProgrammingError, InterfaceError +from psycopg2.extensions import ISQLQuote, adapt, register_adapter +from psycopg2.extensions import new_type, new_array_type, register_type + + +class Range: + """Python representation for a PostgreSQL |range|_ type. + + :param lower: lower bound for the range. `!None` means unbound + :param upper: upper bound for the range. `!None` means unbound + :param bounds: one of the literal strings ``()``, ``[)``, ``(]``, ``[]``, + representing whether the lower or upper bounds are included + :param empty: if `!True`, the range is empty + + """ + __slots__ = ('_lower', '_upper', '_bounds') + + def __init__(self, lower=None, upper=None, bounds='[)', empty=False): + if not empty: + if bounds not in ('[)', '(]', '()', '[]'): + raise ValueError(f"bound flags not valid: {bounds!r}") + + self._lower = lower + self._upper = upper + self._bounds = bounds + else: + self._lower = self._upper = self._bounds = None + + def __repr__(self): + if self._bounds is None: + return f"{self.__class__.__name__}(empty=True)" + else: + return "{}({!r}, {!r}, {!r})".format(self.__class__.__name__, + self._lower, self._upper, self._bounds) + + def __str__(self): + if self._bounds is None: + return 'empty' + + items = [ + self._bounds[0], + str(self._lower), + ', ', + str(self._upper), + self._bounds[1] + ] + return ''.join(items) + + @property + def lower(self): + """The lower bound of the range. `!None` if empty or unbound.""" + return self._lower + + @property + def upper(self): + """The upper bound of the range. `!None` if empty or unbound.""" + return self._upper + + @property + def isempty(self): + """`!True` if the range is empty.""" + return self._bounds is None + + @property + def lower_inf(self): + """`!True` if the range doesn't have a lower bound.""" + if self._bounds is None: + return False + return self._lower is None + + @property + def upper_inf(self): + """`!True` if the range doesn't have an upper bound.""" + if self._bounds is None: + return False + return self._upper is None + + @property + def lower_inc(self): + """`!True` if the lower bound is included in the range.""" + if self._bounds is None or self._lower is None: + return False + return self._bounds[0] == '[' + + @property + def upper_inc(self): + """`!True` if the upper bound is included in the range.""" + if self._bounds is None or self._upper is None: + return False + return self._bounds[1] == ']' + + def __contains__(self, x): + if self._bounds is None: + return False + + if self._lower is not None: + if self._bounds[0] == '[': + if x < self._lower: + return False + else: + if x <= self._lower: + return False + + if self._upper is not None: + if self._bounds[1] == ']': + if x > self._upper: + return False + else: + if x >= self._upper: + return False + + return True + + def __bool__(self): + return self._bounds is not None + + def __eq__(self, other): + if not isinstance(other, Range): + return False + return (self._lower == other._lower + and self._upper == other._upper + and self._bounds == other._bounds) + + def __ne__(self, other): + return not self.__eq__(other) + + def __hash__(self): + return hash((self._lower, self._upper, self._bounds)) + + # as the postgres docs describe for the server-side stuff, + # ordering is rather arbitrary, but will remain stable + # and consistent. + + def __lt__(self, other): + if not isinstance(other, Range): + return NotImplemented + for attr in ('_lower', '_upper', '_bounds'): + self_value = getattr(self, attr) + other_value = getattr(other, attr) + if self_value == other_value: + pass + elif self_value is None: + return True + elif other_value is None: + return False + else: + return self_value < other_value + return False + + def __le__(self, other): + if self == other: + return True + else: + return self.__lt__(other) + + def __gt__(self, other): + if isinstance(other, Range): + return other.__lt__(self) + else: + return NotImplemented + + def __ge__(self, other): + if self == other: + return True + else: + return self.__gt__(other) + + def __getstate__(self): + return {slot: getattr(self, slot) + for slot in self.__slots__ if hasattr(self, slot)} + + def __setstate__(self, state): + for slot, value in state.items(): + setattr(self, slot, value) + + +def register_range(pgrange, pyrange, conn_or_curs, globally=False): + """Create and register an adapter and the typecasters to convert between + a PostgreSQL |range|_ type and a PostgreSQL `Range` subclass. + + :param pgrange: the name of the PostgreSQL |range| type. Can be + schema-qualified + :param pyrange: a `Range` strict subclass, or just a name to give to a new + class + :param conn_or_curs: a connection or cursor used to find the oid of the + range and its subtype; the typecaster is registered in a scope limited + to this object, unless *globally* is set to `!True` + :param globally: if `!False` (default) register the typecaster only on + *conn_or_curs*, otherwise register it globally + :return: `RangeCaster` instance responsible for the conversion + + If a string is passed to *pyrange*, a new `Range` subclass is created + with such name and will be available as the `~RangeCaster.range` attribute + of the returned `RangeCaster` object. + + The function queries the database on *conn_or_curs* to inspect the + *pgrange* type and raises `~psycopg2.ProgrammingError` if the type is not + found. If querying the database is not advisable, use directly the + `RangeCaster` class and register the adapter and typecasters using the + provided functions. + + """ + caster = RangeCaster._from_db(pgrange, pyrange, conn_or_curs) + caster._register(not globally and conn_or_curs or None) + return caster + + +class RangeAdapter: + """`ISQLQuote` adapter for `Range` subclasses. + + This is an abstract class: concrete classes must set a `name` class + attribute or override `getquoted()`. + """ + name = None + + def __init__(self, adapted): + self.adapted = adapted + + def __conform__(self, proto): + if self._proto is ISQLQuote: + return self + + def prepare(self, conn): + self._conn = conn + + def getquoted(self): + if self.name is None: + raise NotImplementedError( + 'RangeAdapter must be subclassed overriding its name ' + 'or the getquoted() method') + + r = self.adapted + if r.isempty: + return b"'empty'::" + self.name.encode('utf8') + + if r.lower is not None: + a = adapt(r.lower) + if hasattr(a, 'prepare'): + a.prepare(self._conn) + lower = a.getquoted() + else: + lower = b'NULL' + + if r.upper is not None: + a = adapt(r.upper) + if hasattr(a, 'prepare'): + a.prepare(self._conn) + upper = a.getquoted() + else: + upper = b'NULL' + + return self.name.encode('utf8') + b'(' + lower + b', ' + upper \ + + b", '" + r._bounds.encode('utf8') + b"')" + + +class RangeCaster: + """Helper class to convert between `Range` and PostgreSQL range types. + + Objects of this class are usually created by `register_range()`. Manual + creation could be useful if querying the database is not advisable: in + this case the oids must be provided. + """ + def __init__(self, pgrange, pyrange, oid, subtype_oid, array_oid=None): + self.subtype_oid = subtype_oid + self._create_ranges(pgrange, pyrange) + + name = self.adapter.name or self.adapter.__class__.__name__ + + self.typecaster = new_type((oid,), name, self.parse) + + if array_oid is not None: + self.array_typecaster = new_array_type( + (array_oid,), name + "ARRAY", self.typecaster) + else: + self.array_typecaster = None + + def _create_ranges(self, pgrange, pyrange): + """Create Range and RangeAdapter classes if needed.""" + # if got a string create a new RangeAdapter concrete type (with a name) + # else take it as an adapter. Passing an adapter should be considered + # an implementation detail and is not documented. It is currently used + # for the numeric ranges. + self.adapter = None + if isinstance(pgrange, str): + self.adapter = type(pgrange, (RangeAdapter,), {}) + self.adapter.name = pgrange + else: + try: + if issubclass(pgrange, RangeAdapter) \ + and pgrange is not RangeAdapter: + self.adapter = pgrange + except TypeError: + pass + + if self.adapter is None: + raise TypeError( + 'pgrange must be a string or a RangeAdapter strict subclass') + + self.range = None + try: + if isinstance(pyrange, str): + self.range = type(pyrange, (Range,), {}) + if issubclass(pyrange, Range) and pyrange is not Range: + self.range = pyrange + except TypeError: + pass + + if self.range is None: + raise TypeError( + 'pyrange must be a type or a Range strict subclass') + + @classmethod + def _from_db(self, name, pyrange, conn_or_curs): + """Return a `RangeCaster` instance for the type *pgrange*. + + Raise `ProgrammingError` if the type is not found. + """ + from psycopg2.extensions import STATUS_IN_TRANSACTION + from psycopg2.extras import _solve_conn_curs + conn, curs = _solve_conn_curs(conn_or_curs) + + if conn.info.server_version < 90200: + raise ProgrammingError("range types not available in version %s" + % conn.info.server_version) + + # Store the transaction status of the connection to revert it after use + conn_status = conn.status + + # Use the correct schema + if '.' in name: + schema, tname = name.split('.', 1) + else: + tname = name + schema = 'public' + + # get the type oid and attributes + curs.execute("""\ +select rngtypid, rngsubtype, typarray +from pg_range r +join pg_type t on t.oid = rngtypid +join pg_namespace ns on ns.oid = typnamespace +where typname = %s and ns.nspname = %s; +""", (tname, schema)) + rec = curs.fetchone() + + if not rec: + # The above algorithm doesn't work for customized seach_path + # (#1487) The implementation below works better, but, to guarantee + # backwards compatibility, use it only if the original one failed. + try: + savepoint = False + # Because we executed statements earlier, we are either INTRANS + # or we are IDLE only if the transaction is autocommit, in + # which case we don't need the savepoint anyway. + if conn.status == STATUS_IN_TRANSACTION: + curs.execute("SAVEPOINT register_type") + savepoint = True + + curs.execute("""\ +SELECT rngtypid, rngsubtype, typarray, typname, nspname +from pg_range r +join pg_type t on t.oid = rngtypid +join pg_namespace ns on ns.oid = typnamespace +WHERE t.oid = %s::regtype +""", (name, )) + except ProgrammingError: + pass + else: + rec = curs.fetchone() + if rec: + tname, schema = rec[3:] + finally: + if savepoint: + curs.execute("ROLLBACK TO SAVEPOINT register_type") + + # revert the status of the connection as before the command + if conn_status != STATUS_IN_TRANSACTION and not conn.autocommit: + conn.rollback() + + if not rec: + raise ProgrammingError( + f"PostgreSQL range '{name}' not found") + + type, subtype, array = rec[:3] + + return RangeCaster(name, pyrange, + oid=type, subtype_oid=subtype, array_oid=array) + + _re_range = re.compile(r""" + ( \(|\[ ) # lower bound flag + (?: # lower bound: + " ( (?: [^"] | "")* ) " # - a quoted string + | ( [^",]+ ) # - or an unquoted string + )? # - or empty (not catched) + , + (?: # upper bound: + " ( (?: [^"] | "")* ) " # - a quoted string + | ( [^"\)\]]+ ) # - or an unquoted string + )? # - or empty (not catched) + ( \)|\] ) # upper bound flag + """, re.VERBOSE) + + _re_undouble = re.compile(r'(["\\])\1') + + def parse(self, s, cur=None): + if s is None: + return None + + if s == 'empty': + return self.range(empty=True) + + m = self._re_range.match(s) + if m is None: + raise InterfaceError(f"failed to parse range: '{s}'") + + lower = m.group(3) + if lower is None: + lower = m.group(2) + if lower is not None: + lower = self._re_undouble.sub(r"\1", lower) + + upper = m.group(5) + if upper is None: + upper = m.group(4) + if upper is not None: + upper = self._re_undouble.sub(r"\1", upper) + + if cur is not None: + lower = cur.cast(self.subtype_oid, lower) + upper = cur.cast(self.subtype_oid, upper) + + bounds = m.group(1) + m.group(6) + + return self.range(lower, upper, bounds) + + def _register(self, scope=None): + register_type(self.typecaster, scope) + if self.array_typecaster is not None: + register_type(self.array_typecaster, scope) + + register_adapter(self.range, self.adapter) + + +class NumericRange(Range): + """A `Range` suitable to pass Python numeric types to a PostgreSQL range. + + PostgreSQL types :sql:`int4range`, :sql:`int8range`, :sql:`numrange` are + casted into `!NumericRange` instances. + """ + pass + + +class DateRange(Range): + """Represents :sql:`daterange` values.""" + pass + + +class DateTimeRange(Range): + """Represents :sql:`tsrange` values.""" + pass + + +class DateTimeTZRange(Range): + """Represents :sql:`tstzrange` values.""" + pass + + +# Special adaptation for NumericRange. Allows to pass number range regardless +# of whether they are ints, floats and what size of ints are, which are +# pointless in Python world. On the way back, no numeric range is casted to +# NumericRange, but only to their subclasses + +class NumberRangeAdapter(RangeAdapter): + """Adapt a range if the subtype doesn't need quotes.""" + def getquoted(self): + r = self.adapted + if r.isempty: + return b"'empty'" + + if not r.lower_inf: + # not exactly: we are relying that none of these object is really + # quoted (they are numbers). Also, I'm lazy and not preparing the + # adapter because I assume encoding doesn't matter for these + # objects. + lower = adapt(r.lower).getquoted().decode('ascii') + else: + lower = '' + + if not r.upper_inf: + upper = adapt(r.upper).getquoted().decode('ascii') + else: + upper = '' + + return (f"'{r._bounds[0]}{lower},{upper}{r._bounds[1]}'").encode('ascii') + + +# TODO: probably won't work with infs, nans and other tricky cases. +register_adapter(NumericRange, NumberRangeAdapter) + +# Register globally typecasters and adapters for builtin range types. + +# note: the adapter is registered more than once, but this is harmless. +int4range_caster = RangeCaster(NumberRangeAdapter, NumericRange, + oid=3904, subtype_oid=23, array_oid=3905) +int4range_caster._register() + +int8range_caster = RangeCaster(NumberRangeAdapter, NumericRange, + oid=3926, subtype_oid=20, array_oid=3927) +int8range_caster._register() + +numrange_caster = RangeCaster(NumberRangeAdapter, NumericRange, + oid=3906, subtype_oid=1700, array_oid=3907) +numrange_caster._register() + +daterange_caster = RangeCaster('daterange', DateRange, + oid=3912, subtype_oid=1082, array_oid=3913) +daterange_caster._register() + +tsrange_caster = RangeCaster('tsrange', DateTimeRange, + oid=3908, subtype_oid=1114, array_oid=3909) +tsrange_caster._register() + +tstzrange_caster = RangeCaster('tstzrange', DateTimeTZRange, + oid=3910, subtype_oid=1184, array_oid=3911) +tstzrange_caster._register() diff --git a/env/Lib/site-packages/psycopg2/errorcodes.py b/env/Lib/site-packages/psycopg2/errorcodes.py new file mode 100644 index 0000000..aa646c4 --- /dev/null +++ b/env/Lib/site-packages/psycopg2/errorcodes.py @@ -0,0 +1,449 @@ +"""Error codes for PostgreSQL + +This module contains symbolic names for all PostgreSQL error codes. +""" +# psycopg2/errorcodes.py - PostgreSQL error codes +# +# Copyright (C) 2006-2019 Johan Dahlin +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. +# +# Based on: +# +# https://www.postgresql.org/docs/current/static/errcodes-appendix.html +# + + +def lookup(code, _cache={}): + """Lookup an error code or class code and return its symbolic name. + + Raise `KeyError` if the code is not found. + """ + if _cache: + return _cache[code] + + # Generate the lookup map at first usage. + tmp = {} + for k, v in globals().items(): + if isinstance(v, str) and len(v) in (2, 5): + # Strip trailing underscore used to disambiguate duplicate values + tmp[v] = k.rstrip("_") + + assert tmp + + # Atomic update, to avoid race condition on import (bug #382) + _cache.update(tmp) + + return _cache[code] + + +# autogenerated data: do not edit below this point. + +# Error classes +CLASS_SUCCESSFUL_COMPLETION = '00' +CLASS_WARNING = '01' +CLASS_NO_DATA = '02' +CLASS_SQL_STATEMENT_NOT_YET_COMPLETE = '03' +CLASS_CONNECTION_EXCEPTION = '08' +CLASS_TRIGGERED_ACTION_EXCEPTION = '09' +CLASS_FEATURE_NOT_SUPPORTED = '0A' +CLASS_INVALID_TRANSACTION_INITIATION = '0B' +CLASS_LOCATOR_EXCEPTION = '0F' +CLASS_INVALID_GRANTOR = '0L' +CLASS_INVALID_ROLE_SPECIFICATION = '0P' +CLASS_DIAGNOSTICS_EXCEPTION = '0Z' +CLASS_CASE_NOT_FOUND = '20' +CLASS_CARDINALITY_VIOLATION = '21' +CLASS_DATA_EXCEPTION = '22' +CLASS_INTEGRITY_CONSTRAINT_VIOLATION = '23' +CLASS_INVALID_CURSOR_STATE = '24' +CLASS_INVALID_TRANSACTION_STATE = '25' +CLASS_INVALID_SQL_STATEMENT_NAME = '26' +CLASS_TRIGGERED_DATA_CHANGE_VIOLATION = '27' +CLASS_INVALID_AUTHORIZATION_SPECIFICATION = '28' +CLASS_DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST = '2B' +CLASS_INVALID_TRANSACTION_TERMINATION = '2D' +CLASS_SQL_ROUTINE_EXCEPTION = '2F' +CLASS_INVALID_CURSOR_NAME = '34' +CLASS_EXTERNAL_ROUTINE_EXCEPTION = '38' +CLASS_EXTERNAL_ROUTINE_INVOCATION_EXCEPTION = '39' +CLASS_SAVEPOINT_EXCEPTION = '3B' +CLASS_INVALID_CATALOG_NAME = '3D' +CLASS_INVALID_SCHEMA_NAME = '3F' +CLASS_TRANSACTION_ROLLBACK = '40' +CLASS_SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION = '42' +CLASS_WITH_CHECK_OPTION_VIOLATION = '44' +CLASS_INSUFFICIENT_RESOURCES = '53' +CLASS_PROGRAM_LIMIT_EXCEEDED = '54' +CLASS_OBJECT_NOT_IN_PREREQUISITE_STATE = '55' +CLASS_OPERATOR_INTERVENTION = '57' +CLASS_SYSTEM_ERROR = '58' +CLASS_SNAPSHOT_FAILURE = '72' +CLASS_CONFIGURATION_FILE_ERROR = 'F0' +CLASS_FOREIGN_DATA_WRAPPER_ERROR = 'HV' +CLASS_PL_PGSQL_ERROR = 'P0' +CLASS_INTERNAL_ERROR = 'XX' + +# Class 00 - Successful Completion +SUCCESSFUL_COMPLETION = '00000' + +# Class 01 - Warning +WARNING = '01000' +NULL_VALUE_ELIMINATED_IN_SET_FUNCTION = '01003' +STRING_DATA_RIGHT_TRUNCATION_ = '01004' +PRIVILEGE_NOT_REVOKED = '01006' +PRIVILEGE_NOT_GRANTED = '01007' +IMPLICIT_ZERO_BIT_PADDING = '01008' +DYNAMIC_RESULT_SETS_RETURNED = '0100C' +DEPRECATED_FEATURE = '01P01' + +# Class 02 - No Data (this is also a warning class per the SQL standard) +NO_DATA = '02000' +NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED = '02001' + +# Class 03 - SQL Statement Not Yet Complete +SQL_STATEMENT_NOT_YET_COMPLETE = '03000' + +# Class 08 - Connection Exception +CONNECTION_EXCEPTION = '08000' +SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION = '08001' +CONNECTION_DOES_NOT_EXIST = '08003' +SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION = '08004' +CONNECTION_FAILURE = '08006' +TRANSACTION_RESOLUTION_UNKNOWN = '08007' +PROTOCOL_VIOLATION = '08P01' + +# Class 09 - Triggered Action Exception +TRIGGERED_ACTION_EXCEPTION = '09000' + +# Class 0A - Feature Not Supported +FEATURE_NOT_SUPPORTED = '0A000' + +# Class 0B - Invalid Transaction Initiation +INVALID_TRANSACTION_INITIATION = '0B000' + +# Class 0F - Locator Exception +LOCATOR_EXCEPTION = '0F000' +INVALID_LOCATOR_SPECIFICATION = '0F001' + +# Class 0L - Invalid Grantor +INVALID_GRANTOR = '0L000' +INVALID_GRANT_OPERATION = '0LP01' + +# Class 0P - Invalid Role Specification +INVALID_ROLE_SPECIFICATION = '0P000' + +# Class 0Z - Diagnostics Exception +DIAGNOSTICS_EXCEPTION = '0Z000' +STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER = '0Z002' + +# Class 20 - Case Not Found +CASE_NOT_FOUND = '20000' + +# Class 21 - Cardinality Violation +CARDINALITY_VIOLATION = '21000' + +# Class 22 - Data Exception +DATA_EXCEPTION = '22000' +STRING_DATA_RIGHT_TRUNCATION = '22001' +NULL_VALUE_NO_INDICATOR_PARAMETER = '22002' +NUMERIC_VALUE_OUT_OF_RANGE = '22003' +NULL_VALUE_NOT_ALLOWED_ = '22004' +ERROR_IN_ASSIGNMENT = '22005' +INVALID_DATETIME_FORMAT = '22007' +DATETIME_FIELD_OVERFLOW = '22008' +INVALID_TIME_ZONE_DISPLACEMENT_VALUE = '22009' +ESCAPE_CHARACTER_CONFLICT = '2200B' +INVALID_USE_OF_ESCAPE_CHARACTER = '2200C' +INVALID_ESCAPE_OCTET = '2200D' +ZERO_LENGTH_CHARACTER_STRING = '2200F' +MOST_SPECIFIC_TYPE_MISMATCH = '2200G' +SEQUENCE_GENERATOR_LIMIT_EXCEEDED = '2200H' +NOT_AN_XML_DOCUMENT = '2200L' +INVALID_XML_DOCUMENT = '2200M' +INVALID_XML_CONTENT = '2200N' +INVALID_XML_COMMENT = '2200S' +INVALID_XML_PROCESSING_INSTRUCTION = '2200T' +INVALID_INDICATOR_PARAMETER_VALUE = '22010' +SUBSTRING_ERROR = '22011' +DIVISION_BY_ZERO = '22012' +INVALID_PRECEDING_OR_FOLLOWING_SIZE = '22013' +INVALID_ARGUMENT_FOR_NTILE_FUNCTION = '22014' +INTERVAL_FIELD_OVERFLOW = '22015' +INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION = '22016' +INVALID_CHARACTER_VALUE_FOR_CAST = '22018' +INVALID_ESCAPE_CHARACTER = '22019' +INVALID_REGULAR_EXPRESSION = '2201B' +INVALID_ARGUMENT_FOR_LOGARITHM = '2201E' +INVALID_ARGUMENT_FOR_POWER_FUNCTION = '2201F' +INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION = '2201G' +INVALID_ROW_COUNT_IN_LIMIT_CLAUSE = '2201W' +INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE = '2201X' +INVALID_LIMIT_VALUE = '22020' +CHARACTER_NOT_IN_REPERTOIRE = '22021' +INDICATOR_OVERFLOW = '22022' +INVALID_PARAMETER_VALUE = '22023' +UNTERMINATED_C_STRING = '22024' +INVALID_ESCAPE_SEQUENCE = '22025' +STRING_DATA_LENGTH_MISMATCH = '22026' +TRIM_ERROR = '22027' +ARRAY_SUBSCRIPT_ERROR = '2202E' +INVALID_TABLESAMPLE_REPEAT = '2202G' +INVALID_TABLESAMPLE_ARGUMENT = '2202H' +DUPLICATE_JSON_OBJECT_KEY_VALUE = '22030' +INVALID_ARGUMENT_FOR_SQL_JSON_DATETIME_FUNCTION = '22031' +INVALID_JSON_TEXT = '22032' +INVALID_SQL_JSON_SUBSCRIPT = '22033' +MORE_THAN_ONE_SQL_JSON_ITEM = '22034' +NO_SQL_JSON_ITEM = '22035' +NON_NUMERIC_SQL_JSON_ITEM = '22036' +NON_UNIQUE_KEYS_IN_A_JSON_OBJECT = '22037' +SINGLETON_SQL_JSON_ITEM_REQUIRED = '22038' +SQL_JSON_ARRAY_NOT_FOUND = '22039' +SQL_JSON_MEMBER_NOT_FOUND = '2203A' +SQL_JSON_NUMBER_NOT_FOUND = '2203B' +SQL_JSON_OBJECT_NOT_FOUND = '2203C' +TOO_MANY_JSON_ARRAY_ELEMENTS = '2203D' +TOO_MANY_JSON_OBJECT_MEMBERS = '2203E' +SQL_JSON_SCALAR_REQUIRED = '2203F' +SQL_JSON_ITEM_CANNOT_BE_CAST_TO_TARGET_TYPE = '2203G' +FLOATING_POINT_EXCEPTION = '22P01' +INVALID_TEXT_REPRESENTATION = '22P02' +INVALID_BINARY_REPRESENTATION = '22P03' +BAD_COPY_FILE_FORMAT = '22P04' +UNTRANSLATABLE_CHARACTER = '22P05' +NONSTANDARD_USE_OF_ESCAPE_CHARACTER = '22P06' + +# Class 23 - Integrity Constraint Violation +INTEGRITY_CONSTRAINT_VIOLATION = '23000' +RESTRICT_VIOLATION = '23001' +NOT_NULL_VIOLATION = '23502' +FOREIGN_KEY_VIOLATION = '23503' +UNIQUE_VIOLATION = '23505' +CHECK_VIOLATION = '23514' +EXCLUSION_VIOLATION = '23P01' + +# Class 24 - Invalid Cursor State +INVALID_CURSOR_STATE = '24000' + +# Class 25 - Invalid Transaction State +INVALID_TRANSACTION_STATE = '25000' +ACTIVE_SQL_TRANSACTION = '25001' +BRANCH_TRANSACTION_ALREADY_ACTIVE = '25002' +INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION = '25003' +INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION = '25004' +NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION = '25005' +READ_ONLY_SQL_TRANSACTION = '25006' +SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED = '25007' +HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL = '25008' +NO_ACTIVE_SQL_TRANSACTION = '25P01' +IN_FAILED_SQL_TRANSACTION = '25P02' +IDLE_IN_TRANSACTION_SESSION_TIMEOUT = '25P03' + +# Class 26 - Invalid SQL Statement Name +INVALID_SQL_STATEMENT_NAME = '26000' + +# Class 27 - Triggered Data Change Violation +TRIGGERED_DATA_CHANGE_VIOLATION = '27000' + +# Class 28 - Invalid Authorization Specification +INVALID_AUTHORIZATION_SPECIFICATION = '28000' +INVALID_PASSWORD = '28P01' + +# Class 2B - Dependent Privilege Descriptors Still Exist +DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST = '2B000' +DEPENDENT_OBJECTS_STILL_EXIST = '2BP01' + +# Class 2D - Invalid Transaction Termination +INVALID_TRANSACTION_TERMINATION = '2D000' + +# Class 2F - SQL Routine Exception +SQL_ROUTINE_EXCEPTION = '2F000' +MODIFYING_SQL_DATA_NOT_PERMITTED_ = '2F002' +PROHIBITED_SQL_STATEMENT_ATTEMPTED_ = '2F003' +READING_SQL_DATA_NOT_PERMITTED_ = '2F004' +FUNCTION_EXECUTED_NO_RETURN_STATEMENT = '2F005' + +# Class 34 - Invalid Cursor Name +INVALID_CURSOR_NAME = '34000' + +# Class 38 - External Routine Exception +EXTERNAL_ROUTINE_EXCEPTION = '38000' +CONTAINING_SQL_NOT_PERMITTED = '38001' +MODIFYING_SQL_DATA_NOT_PERMITTED = '38002' +PROHIBITED_SQL_STATEMENT_ATTEMPTED = '38003' +READING_SQL_DATA_NOT_PERMITTED = '38004' + +# Class 39 - External Routine Invocation Exception +EXTERNAL_ROUTINE_INVOCATION_EXCEPTION = '39000' +INVALID_SQLSTATE_RETURNED = '39001' +NULL_VALUE_NOT_ALLOWED = '39004' +TRIGGER_PROTOCOL_VIOLATED = '39P01' +SRF_PROTOCOL_VIOLATED = '39P02' +EVENT_TRIGGER_PROTOCOL_VIOLATED = '39P03' + +# Class 3B - Savepoint Exception +SAVEPOINT_EXCEPTION = '3B000' +INVALID_SAVEPOINT_SPECIFICATION = '3B001' + +# Class 3D - Invalid Catalog Name +INVALID_CATALOG_NAME = '3D000' + +# Class 3F - Invalid Schema Name +INVALID_SCHEMA_NAME = '3F000' + +# Class 40 - Transaction Rollback +TRANSACTION_ROLLBACK = '40000' +SERIALIZATION_FAILURE = '40001' +TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION = '40002' +STATEMENT_COMPLETION_UNKNOWN = '40003' +DEADLOCK_DETECTED = '40P01' + +# Class 42 - Syntax Error or Access Rule Violation +SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION = '42000' +INSUFFICIENT_PRIVILEGE = '42501' +SYNTAX_ERROR = '42601' +INVALID_NAME = '42602' +INVALID_COLUMN_DEFINITION = '42611' +NAME_TOO_LONG = '42622' +DUPLICATE_COLUMN = '42701' +AMBIGUOUS_COLUMN = '42702' +UNDEFINED_COLUMN = '42703' +UNDEFINED_OBJECT = '42704' +DUPLICATE_OBJECT = '42710' +DUPLICATE_ALIAS = '42712' +DUPLICATE_FUNCTION = '42723' +AMBIGUOUS_FUNCTION = '42725' +GROUPING_ERROR = '42803' +DATATYPE_MISMATCH = '42804' +WRONG_OBJECT_TYPE = '42809' +INVALID_FOREIGN_KEY = '42830' +CANNOT_COERCE = '42846' +UNDEFINED_FUNCTION = '42883' +GENERATED_ALWAYS = '428C9' +RESERVED_NAME = '42939' +UNDEFINED_TABLE = '42P01' +UNDEFINED_PARAMETER = '42P02' +DUPLICATE_CURSOR = '42P03' +DUPLICATE_DATABASE = '42P04' +DUPLICATE_PREPARED_STATEMENT = '42P05' +DUPLICATE_SCHEMA = '42P06' +DUPLICATE_TABLE = '42P07' +AMBIGUOUS_PARAMETER = '42P08' +AMBIGUOUS_ALIAS = '42P09' +INVALID_COLUMN_REFERENCE = '42P10' +INVALID_CURSOR_DEFINITION = '42P11' +INVALID_DATABASE_DEFINITION = '42P12' +INVALID_FUNCTION_DEFINITION = '42P13' +INVALID_PREPARED_STATEMENT_DEFINITION = '42P14' +INVALID_SCHEMA_DEFINITION = '42P15' +INVALID_TABLE_DEFINITION = '42P16' +INVALID_OBJECT_DEFINITION = '42P17' +INDETERMINATE_DATATYPE = '42P18' +INVALID_RECURSION = '42P19' +WINDOWING_ERROR = '42P20' +COLLATION_MISMATCH = '42P21' +INDETERMINATE_COLLATION = '42P22' + +# Class 44 - WITH CHECK OPTION Violation +WITH_CHECK_OPTION_VIOLATION = '44000' + +# Class 53 - Insufficient Resources +INSUFFICIENT_RESOURCES = '53000' +DISK_FULL = '53100' +OUT_OF_MEMORY = '53200' +TOO_MANY_CONNECTIONS = '53300' +CONFIGURATION_LIMIT_EXCEEDED = '53400' + +# Class 54 - Program Limit Exceeded +PROGRAM_LIMIT_EXCEEDED = '54000' +STATEMENT_TOO_COMPLEX = '54001' +TOO_MANY_COLUMNS = '54011' +TOO_MANY_ARGUMENTS = '54023' + +# Class 55 - Object Not In Prerequisite State +OBJECT_NOT_IN_PREREQUISITE_STATE = '55000' +OBJECT_IN_USE = '55006' +CANT_CHANGE_RUNTIME_PARAM = '55P02' +LOCK_NOT_AVAILABLE = '55P03' +UNSAFE_NEW_ENUM_VALUE_USAGE = '55P04' + +# Class 57 - Operator Intervention +OPERATOR_INTERVENTION = '57000' +QUERY_CANCELED = '57014' +ADMIN_SHUTDOWN = '57P01' +CRASH_SHUTDOWN = '57P02' +CANNOT_CONNECT_NOW = '57P03' +DATABASE_DROPPED = '57P04' +IDLE_SESSION_TIMEOUT = '57P05' + +# Class 58 - System Error (errors external to PostgreSQL itself) +SYSTEM_ERROR = '58000' +IO_ERROR = '58030' +UNDEFINED_FILE = '58P01' +DUPLICATE_FILE = '58P02' + +# Class 72 - Snapshot Failure +SNAPSHOT_TOO_OLD = '72000' + +# Class F0 - Configuration File Error +CONFIG_FILE_ERROR = 'F0000' +LOCK_FILE_EXISTS = 'F0001' + +# Class HV - Foreign Data Wrapper Error (SQL/MED) +FDW_ERROR = 'HV000' +FDW_OUT_OF_MEMORY = 'HV001' +FDW_DYNAMIC_PARAMETER_VALUE_NEEDED = 'HV002' +FDW_INVALID_DATA_TYPE = 'HV004' +FDW_COLUMN_NAME_NOT_FOUND = 'HV005' +FDW_INVALID_DATA_TYPE_DESCRIPTORS = 'HV006' +FDW_INVALID_COLUMN_NAME = 'HV007' +FDW_INVALID_COLUMN_NUMBER = 'HV008' +FDW_INVALID_USE_OF_NULL_POINTER = 'HV009' +FDW_INVALID_STRING_FORMAT = 'HV00A' +FDW_INVALID_HANDLE = 'HV00B' +FDW_INVALID_OPTION_INDEX = 'HV00C' +FDW_INVALID_OPTION_NAME = 'HV00D' +FDW_OPTION_NAME_NOT_FOUND = 'HV00J' +FDW_REPLY_HANDLE = 'HV00K' +FDW_UNABLE_TO_CREATE_EXECUTION = 'HV00L' +FDW_UNABLE_TO_CREATE_REPLY = 'HV00M' +FDW_UNABLE_TO_ESTABLISH_CONNECTION = 'HV00N' +FDW_NO_SCHEMAS = 'HV00P' +FDW_SCHEMA_NOT_FOUND = 'HV00Q' +FDW_TABLE_NOT_FOUND = 'HV00R' +FDW_FUNCTION_SEQUENCE_ERROR = 'HV010' +FDW_TOO_MANY_HANDLES = 'HV014' +FDW_INCONSISTENT_DESCRIPTOR_INFORMATION = 'HV021' +FDW_INVALID_ATTRIBUTE_VALUE = 'HV024' +FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH = 'HV090' +FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER = 'HV091' + +# Class P0 - PL/pgSQL Error +PLPGSQL_ERROR = 'P0000' +RAISE_EXCEPTION = 'P0001' +NO_DATA_FOUND = 'P0002' +TOO_MANY_ROWS = 'P0003' +ASSERT_FAILURE = 'P0004' + +# Class XX - Internal Error +INTERNAL_ERROR = 'XX000' +DATA_CORRUPTED = 'XX001' +INDEX_CORRUPTED = 'XX002' diff --git a/env/Lib/site-packages/psycopg2/errors.py b/env/Lib/site-packages/psycopg2/errors.py new file mode 100644 index 0000000..e4e47f5 --- /dev/null +++ b/env/Lib/site-packages/psycopg2/errors.py @@ -0,0 +1,38 @@ +"""Error classes for PostgreSQL error codes +""" + +# psycopg/errors.py - SQLSTATE and DB-API exceptions +# +# Copyright (C) 2018-2019 Daniele Varrazzo +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +# +# NOTE: the exceptions are injected into this module by the C extention. +# + + +def lookup(code): + """Lookup an error code and return its exception class. + + Raise `!KeyError` if the code is not found. + """ + from psycopg2._psycopg import sqlstate_errors # avoid circular import + return sqlstate_errors[code] diff --git a/env/Lib/site-packages/psycopg2/extensions.py b/env/Lib/site-packages/psycopg2/extensions.py new file mode 100644 index 0000000..b938d0c --- /dev/null +++ b/env/Lib/site-packages/psycopg2/extensions.py @@ -0,0 +1,213 @@ +"""psycopg extensions to the DBAPI-2.0 + +This module holds all the extensions to the DBAPI-2.0 provided by psycopg. + +- `connection` -- the new-type inheritable connection class +- `cursor` -- the new-type inheritable cursor class +- `lobject` -- the new-type inheritable large object class +- `adapt()` -- exposes the PEP-246_ compatible adapting mechanism used + by psycopg to adapt Python types to PostgreSQL ones + +.. _PEP-246: https://www.python.org/dev/peps/pep-0246/ +""" +# psycopg/extensions.py - DBAPI-2.0 extensions specific to psycopg +# +# Copyright (C) 2003-2019 Federico Di Gregorio +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +import re as _re + +from psycopg2._psycopg import ( # noqa + BINARYARRAY, BOOLEAN, BOOLEANARRAY, BYTES, BYTESARRAY, DATE, DATEARRAY, + DATETIMEARRAY, DECIMAL, DECIMALARRAY, FLOAT, FLOATARRAY, INTEGER, + INTEGERARRAY, INTERVAL, INTERVALARRAY, LONGINTEGER, LONGINTEGERARRAY, + ROWIDARRAY, STRINGARRAY, TIME, TIMEARRAY, UNICODE, UNICODEARRAY, + AsIs, Binary, Boolean, Float, Int, QuotedString, ) + +from psycopg2._psycopg import ( # noqa + PYDATE, PYDATETIME, PYDATETIMETZ, PYINTERVAL, PYTIME, PYDATEARRAY, + PYDATETIMEARRAY, PYDATETIMETZARRAY, PYINTERVALARRAY, PYTIMEARRAY, + DateFromPy, TimeFromPy, TimestampFromPy, IntervalFromPy, ) + +from psycopg2._psycopg import ( # noqa + adapt, adapters, encodings, connection, cursor, + lobject, Xid, libpq_version, parse_dsn, quote_ident, + string_types, binary_types, new_type, new_array_type, register_type, + ISQLQuote, Notify, Diagnostics, Column, ConnectionInfo, + QueryCanceledError, TransactionRollbackError, + set_wait_callback, get_wait_callback, encrypt_password, ) + + +"""Isolation level values.""" +ISOLATION_LEVEL_AUTOCOMMIT = 0 +ISOLATION_LEVEL_READ_UNCOMMITTED = 4 +ISOLATION_LEVEL_READ_COMMITTED = 1 +ISOLATION_LEVEL_REPEATABLE_READ = 2 +ISOLATION_LEVEL_SERIALIZABLE = 3 +ISOLATION_LEVEL_DEFAULT = None + + +"""psycopg connection status values.""" +STATUS_SETUP = 0 +STATUS_READY = 1 +STATUS_BEGIN = 2 +STATUS_SYNC = 3 # currently unused +STATUS_ASYNC = 4 # currently unused +STATUS_PREPARED = 5 + +# This is a useful mnemonic to check if the connection is in a transaction +STATUS_IN_TRANSACTION = STATUS_BEGIN + + +"""psycopg asynchronous connection polling values""" +POLL_OK = 0 +POLL_READ = 1 +POLL_WRITE = 2 +POLL_ERROR = 3 + + +"""Backend transaction status values.""" +TRANSACTION_STATUS_IDLE = 0 +TRANSACTION_STATUS_ACTIVE = 1 +TRANSACTION_STATUS_INTRANS = 2 +TRANSACTION_STATUS_INERROR = 3 +TRANSACTION_STATUS_UNKNOWN = 4 + + +def register_adapter(typ, callable): + """Register 'callable' as an ISQLQuote adapter for type 'typ'.""" + adapters[(typ, ISQLQuote)] = callable + + +# The SQL_IN class is the official adapter for tuples starting from 2.0.6. +class SQL_IN: + """Adapt any iterable to an SQL quotable object.""" + def __init__(self, seq): + self._seq = seq + self._conn = None + + def prepare(self, conn): + self._conn = conn + + def getquoted(self): + # this is the important line: note how every object in the + # list is adapted and then how getquoted() is called on it + pobjs = [adapt(o) for o in self._seq] + if self._conn is not None: + for obj in pobjs: + if hasattr(obj, 'prepare'): + obj.prepare(self._conn) + qobjs = [o.getquoted() for o in pobjs] + return b'(' + b', '.join(qobjs) + b')' + + def __str__(self): + return str(self.getquoted()) + + +class NoneAdapter: + """Adapt None to NULL. + + This adapter is not used normally as a fast path in mogrify uses NULL, + but it makes easier to adapt composite types. + """ + def __init__(self, obj): + pass + + def getquoted(self, _null=b"NULL"): + return _null + + +def make_dsn(dsn=None, **kwargs): + """Convert a set of keywords into a connection strings.""" + if dsn is None and not kwargs: + return '' + + # If no kwarg is specified don't mung the dsn, but verify it + if not kwargs: + parse_dsn(dsn) + return dsn + + # Override the dsn with the parameters + if 'database' in kwargs: + if 'dbname' in kwargs: + raise TypeError( + "you can't specify both 'database' and 'dbname' arguments") + kwargs['dbname'] = kwargs.pop('database') + + # Drop the None arguments + kwargs = {k: v for (k, v) in kwargs.items() if v is not None} + + if dsn is not None: + tmp = parse_dsn(dsn) + tmp.update(kwargs) + kwargs = tmp + + dsn = " ".join(["{}={}".format(k, _param_escape(str(v))) + for (k, v) in kwargs.items()]) + + # verify that the returned dsn is valid + parse_dsn(dsn) + + return dsn + + +def _param_escape(s, + re_escape=_re.compile(r"([\\'])"), + re_space=_re.compile(r'\s')): + """ + Apply the escaping rule required by PQconnectdb + """ + if not s: + return "''" + + s = re_escape.sub(r'\\\1', s) + if re_space.search(s): + s = "'" + s + "'" + + return s + + +# Create default json typecasters for PostgreSQL 9.2 oids +from psycopg2._json import register_default_json, register_default_jsonb # noqa + +try: + JSON, JSONARRAY = register_default_json() + JSONB, JSONBARRAY = register_default_jsonb() +except ImportError: + pass + +del register_default_json, register_default_jsonb + + +# Create default Range typecasters +from psycopg2. _range import Range # noqa +del Range + + +# Add the "cleaned" version of the encodings to the key. +# When the encoding is set its name is cleaned up from - and _ and turned +# uppercase, so an encoding not respecting these rules wouldn't be found in the +# encodings keys and would raise an exception with the unicode typecaster +for k, v in list(encodings.items()): + k = k.replace('_', '').replace('-', '').upper() + encodings[k] = v + +del k, v diff --git a/env/Lib/site-packages/psycopg2/extras.py b/env/Lib/site-packages/psycopg2/extras.py new file mode 100644 index 0000000..36e8ef9 --- /dev/null +++ b/env/Lib/site-packages/psycopg2/extras.py @@ -0,0 +1,1340 @@ +"""Miscellaneous goodies for psycopg2 + +This module is a generic place used to hold little helper functions +and classes until a better place in the distribution is found. +""" +# psycopg/extras.py - miscellaneous extra goodies for psycopg +# +# Copyright (C) 2003-2019 Federico Di Gregorio +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +import os as _os +import time as _time +import re as _re +from collections import namedtuple, OrderedDict + +import logging as _logging + +import psycopg2 +from psycopg2 import extensions as _ext +from .extensions import cursor as _cursor +from .extensions import connection as _connection +from .extensions import adapt as _A, quote_ident +from functools import lru_cache + +from psycopg2._psycopg import ( # noqa + REPLICATION_PHYSICAL, REPLICATION_LOGICAL, + ReplicationConnection as _replicationConnection, + ReplicationCursor as _replicationCursor, + ReplicationMessage) + + +# expose the json adaptation stuff into the module +from psycopg2._json import ( # noqa + json, Json, register_json, register_default_json, register_default_jsonb) + + +# Expose range-related objects +from psycopg2._range import ( # noqa + Range, NumericRange, DateRange, DateTimeRange, DateTimeTZRange, + register_range, RangeAdapter, RangeCaster) + + +# Expose ipaddress-related objects +from psycopg2._ipaddress import register_ipaddress # noqa + + +class DictCursorBase(_cursor): + """Base class for all dict-like cursors.""" + + def __init__(self, *args, **kwargs): + if 'row_factory' in kwargs: + row_factory = kwargs['row_factory'] + del kwargs['row_factory'] + else: + raise NotImplementedError( + "DictCursorBase can't be instantiated without a row factory.") + super().__init__(*args, **kwargs) + self._query_executed = False + self._prefetch = False + self.row_factory = row_factory + + def fetchone(self): + if self._prefetch: + res = super().fetchone() + if self._query_executed: + self._build_index() + if not self._prefetch: + res = super().fetchone() + return res + + def fetchmany(self, size=None): + if self._prefetch: + res = super().fetchmany(size) + if self._query_executed: + self._build_index() + if not self._prefetch: + res = super().fetchmany(size) + return res + + def fetchall(self): + if self._prefetch: + res = super().fetchall() + if self._query_executed: + self._build_index() + if not self._prefetch: + res = super().fetchall() + return res + + def __iter__(self): + try: + if self._prefetch: + res = super().__iter__() + first = next(res) + if self._query_executed: + self._build_index() + if not self._prefetch: + res = super().__iter__() + first = next(res) + + yield first + while True: + yield next(res) + except StopIteration: + return + + +class DictConnection(_connection): + """A connection that uses `DictCursor` automatically.""" + def cursor(self, *args, **kwargs): + kwargs.setdefault('cursor_factory', self.cursor_factory or DictCursor) + return super().cursor(*args, **kwargs) + + +class DictCursor(DictCursorBase): + """A cursor that keeps a list of column name -> index mappings__. + + .. __: https://docs.python.org/glossary.html#term-mapping + """ + + def __init__(self, *args, **kwargs): + kwargs['row_factory'] = DictRow + super().__init__(*args, **kwargs) + self._prefetch = True + + def execute(self, query, vars=None): + self.index = OrderedDict() + self._query_executed = True + return super().execute(query, vars) + + def callproc(self, procname, vars=None): + self.index = OrderedDict() + self._query_executed = True + return super().callproc(procname, vars) + + def _build_index(self): + if self._query_executed and self.description: + for i in range(len(self.description)): + self.index[self.description[i][0]] = i + self._query_executed = False + + +class DictRow(list): + """A row object that allow by-column-name access to data.""" + + __slots__ = ('_index',) + + def __init__(self, cursor): + self._index = cursor.index + self[:] = [None] * len(cursor.description) + + def __getitem__(self, x): + if not isinstance(x, (int, slice)): + x = self._index[x] + return super().__getitem__(x) + + def __setitem__(self, x, v): + if not isinstance(x, (int, slice)): + x = self._index[x] + super().__setitem__(x, v) + + def items(self): + g = super().__getitem__ + return ((n, g(self._index[n])) for n in self._index) + + def keys(self): + return iter(self._index) + + def values(self): + g = super().__getitem__ + return (g(self._index[n]) for n in self._index) + + def get(self, x, default=None): + try: + return self[x] + except Exception: + return default + + def copy(self): + return OrderedDict(self.items()) + + def __contains__(self, x): + return x in self._index + + def __reduce__(self): + # this is apparently useless, but it fixes #1073 + return super().__reduce__() + + def __getstate__(self): + return self[:], self._index.copy() + + def __setstate__(self, data): + self[:] = data[0] + self._index = data[1] + + +class RealDictConnection(_connection): + """A connection that uses `RealDictCursor` automatically.""" + def cursor(self, *args, **kwargs): + kwargs.setdefault('cursor_factory', self.cursor_factory or RealDictCursor) + return super().cursor(*args, **kwargs) + + +class RealDictCursor(DictCursorBase): + """A cursor that uses a real dict as the base type for rows. + + Note that this cursor is extremely specialized and does not allow + the normal access (using integer indices) to fetched data. If you need + to access database rows both as a dictionary and a list, then use + the generic `DictCursor` instead of `!RealDictCursor`. + """ + def __init__(self, *args, **kwargs): + kwargs['row_factory'] = RealDictRow + super().__init__(*args, **kwargs) + + def execute(self, query, vars=None): + self.column_mapping = [] + self._query_executed = True + return super().execute(query, vars) + + def callproc(self, procname, vars=None): + self.column_mapping = [] + self._query_executed = True + return super().callproc(procname, vars) + + def _build_index(self): + if self._query_executed and self.description: + self.column_mapping = [d[0] for d in self.description] + self._query_executed = False + + +class RealDictRow(OrderedDict): + """A `!dict` subclass representing a data record.""" + + def __init__(self, *args, **kwargs): + if args and isinstance(args[0], _cursor): + cursor = args[0] + args = args[1:] + else: + cursor = None + + super().__init__(*args, **kwargs) + + if cursor is not None: + # Required for named cursors + if cursor.description and not cursor.column_mapping: + cursor._build_index() + + # Store the cols mapping in the dict itself until the row is fully + # populated, so we don't need to add attributes to the class + # (hence keeping its maintenance, special pickle support, etc.) + self[RealDictRow] = cursor.column_mapping + + def __setitem__(self, key, value): + if RealDictRow in self: + # We are in the row building phase + mapping = self[RealDictRow] + super().__setitem__(mapping[key], value) + if key == len(mapping) - 1: + # Row building finished + del self[RealDictRow] + return + + super().__setitem__(key, value) + + +class NamedTupleConnection(_connection): + """A connection that uses `NamedTupleCursor` automatically.""" + def cursor(self, *args, **kwargs): + kwargs.setdefault('cursor_factory', self.cursor_factory or NamedTupleCursor) + return super().cursor(*args, **kwargs) + + +class NamedTupleCursor(_cursor): + """A cursor that generates results as `~collections.namedtuple`. + + `!fetch*()` methods will return named tuples instead of regular tuples, so + their elements can be accessed both as regular numeric items as well as + attributes. + + >>> nt_cur = conn.cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) + >>> rec = nt_cur.fetchone() + >>> rec + Record(id=1, num=100, data="abc'def") + >>> rec[1] + 100 + >>> rec.data + "abc'def" + """ + Record = None + MAX_CACHE = 1024 + + def execute(self, query, vars=None): + self.Record = None + return super().execute(query, vars) + + def executemany(self, query, vars): + self.Record = None + return super().executemany(query, vars) + + def callproc(self, procname, vars=None): + self.Record = None + return super().callproc(procname, vars) + + def fetchone(self): + t = super().fetchone() + if t is not None: + nt = self.Record + if nt is None: + nt = self.Record = self._make_nt() + return nt._make(t) + + def fetchmany(self, size=None): + ts = super().fetchmany(size) + nt = self.Record + if nt is None: + nt = self.Record = self._make_nt() + return list(map(nt._make, ts)) + + def fetchall(self): + ts = super().fetchall() + nt = self.Record + if nt is None: + nt = self.Record = self._make_nt() + return list(map(nt._make, ts)) + + def __iter__(self): + try: + it = super().__iter__() + t = next(it) + + nt = self.Record + if nt is None: + nt = self.Record = self._make_nt() + + yield nt._make(t) + + while True: + yield nt._make(next(it)) + except StopIteration: + return + + def _make_nt(self): + key = tuple(d[0] for d in self.description) if self.description else () + return self._cached_make_nt(key) + + @classmethod + def _do_make_nt(cls, key): + fields = [] + for s in key: + s = _re_clean.sub('_', s) + # Python identifier cannot start with numbers, namedtuple fields + # cannot start with underscore. So... + if s[0] == '_' or '0' <= s[0] <= '9': + s = 'f' + s + fields.append(s) + + nt = namedtuple("Record", fields) + return nt + + +@lru_cache(512) +def _cached_make_nt(cls, key): + return cls._do_make_nt(key) + + +# Exposed for testability, and if someone wants to monkeypatch to tweak +# the cache size. +NamedTupleCursor._cached_make_nt = classmethod(_cached_make_nt) + + +class LoggingConnection(_connection): + """A connection that logs all queries to a file or logger__ object. + + .. __: https://docs.python.org/library/logging.html + """ + + def initialize(self, logobj): + """Initialize the connection to log to `!logobj`. + + The `!logobj` parameter can be an open file object or a Logger/LoggerAdapter + instance from the standard logging module. + """ + self._logobj = logobj + if _logging and isinstance( + logobj, (_logging.Logger, _logging.LoggerAdapter)): + self.log = self._logtologger + else: + self.log = self._logtofile + + def filter(self, msg, curs): + """Filter the query before logging it. + + This is the method to overwrite to filter unwanted queries out of the + log or to add some extra data to the output. The default implementation + just does nothing. + """ + return msg + + def _logtofile(self, msg, curs): + msg = self.filter(msg, curs) + if msg: + if isinstance(msg, bytes): + msg = msg.decode(_ext.encodings[self.encoding], 'replace') + self._logobj.write(msg + _os.linesep) + + def _logtologger(self, msg, curs): + msg = self.filter(msg, curs) + if msg: + self._logobj.debug(msg) + + def _check(self): + if not hasattr(self, '_logobj'): + raise self.ProgrammingError( + "LoggingConnection object has not been initialize()d") + + def cursor(self, *args, **kwargs): + self._check() + kwargs.setdefault('cursor_factory', self.cursor_factory or LoggingCursor) + return super().cursor(*args, **kwargs) + + +class LoggingCursor(_cursor): + """A cursor that logs queries using its connection logging facilities.""" + + def execute(self, query, vars=None): + try: + return super().execute(query, vars) + finally: + self.connection.log(self.query, self) + + def callproc(self, procname, vars=None): + try: + return super().callproc(procname, vars) + finally: + self.connection.log(self.query, self) + + +class MinTimeLoggingConnection(LoggingConnection): + """A connection that logs queries based on execution time. + + This is just an example of how to sub-class `LoggingConnection` to + provide some extra filtering for the logged queries. Both the + `initialize()` and `filter()` methods are overwritten to make sure + that only queries executing for more than ``mintime`` ms are logged. + + Note that this connection uses the specialized cursor + `MinTimeLoggingCursor`. + """ + def initialize(self, logobj, mintime=0): + LoggingConnection.initialize(self, logobj) + self._mintime = mintime + + def filter(self, msg, curs): + t = (_time.time() - curs.timestamp) * 1000 + if t > self._mintime: + if isinstance(msg, bytes): + msg = msg.decode(_ext.encodings[self.encoding], 'replace') + return f"{msg}{_os.linesep} (execution time: {t} ms)" + + def cursor(self, *args, **kwargs): + kwargs.setdefault('cursor_factory', + self.cursor_factory or MinTimeLoggingCursor) + return LoggingConnection.cursor(self, *args, **kwargs) + + +class MinTimeLoggingCursor(LoggingCursor): + """The cursor sub-class companion to `MinTimeLoggingConnection`.""" + + def execute(self, query, vars=None): + self.timestamp = _time.time() + return LoggingCursor.execute(self, query, vars) + + def callproc(self, procname, vars=None): + self.timestamp = _time.time() + return LoggingCursor.callproc(self, procname, vars) + + +class LogicalReplicationConnection(_replicationConnection): + + def __init__(self, *args, **kwargs): + kwargs['replication_type'] = REPLICATION_LOGICAL + super().__init__(*args, **kwargs) + + +class PhysicalReplicationConnection(_replicationConnection): + + def __init__(self, *args, **kwargs): + kwargs['replication_type'] = REPLICATION_PHYSICAL + super().__init__(*args, **kwargs) + + +class StopReplication(Exception): + """ + Exception used to break out of the endless loop in + `~ReplicationCursor.consume_stream()`. + + Subclass of `~exceptions.Exception`. Intentionally *not* inherited from + `~psycopg2.Error` as occurrence of this exception does not indicate an + error. + """ + pass + + +class ReplicationCursor(_replicationCursor): + """A cursor used for communication on replication connections.""" + + def create_replication_slot(self, slot_name, slot_type=None, output_plugin=None): + """Create streaming replication slot.""" + + command = f"CREATE_REPLICATION_SLOT {quote_ident(slot_name, self)} " + + if slot_type is None: + slot_type = self.connection.replication_type + + if slot_type == REPLICATION_LOGICAL: + if output_plugin is None: + raise psycopg2.ProgrammingError( + "output plugin name is required to create " + "logical replication slot") + + command += f"LOGICAL {quote_ident(output_plugin, self)}" + + elif slot_type == REPLICATION_PHYSICAL: + if output_plugin is not None: + raise psycopg2.ProgrammingError( + "cannot specify output plugin name when creating " + "physical replication slot") + + command += "PHYSICAL" + + else: + raise psycopg2.ProgrammingError( + f"unrecognized replication type: {repr(slot_type)}") + + self.execute(command) + + def drop_replication_slot(self, slot_name): + """Drop streaming replication slot.""" + + command = f"DROP_REPLICATION_SLOT {quote_ident(slot_name, self)}" + self.execute(command) + + def start_replication( + self, slot_name=None, slot_type=None, start_lsn=0, + timeline=0, options=None, decode=False, status_interval=10): + """Start replication stream.""" + + command = "START_REPLICATION " + + if slot_type is None: + slot_type = self.connection.replication_type + + if slot_type == REPLICATION_LOGICAL: + if slot_name: + command += f"SLOT {quote_ident(slot_name, self)} " + else: + raise psycopg2.ProgrammingError( + "slot name is required for logical replication") + + command += "LOGICAL " + + elif slot_type == REPLICATION_PHYSICAL: + if slot_name: + command += f"SLOT {quote_ident(slot_name, self)} " + # don't add "PHYSICAL", before 9.4 it was just START_REPLICATION XXX/XXX + + else: + raise psycopg2.ProgrammingError( + f"unrecognized replication type: {repr(slot_type)}") + + if type(start_lsn) is str: + lsn = start_lsn.split('/') + lsn = f"{int(lsn[0], 16):X}/{int(lsn[1], 16):08X}" + else: + lsn = f"{start_lsn >> 32 & 4294967295:X}/{start_lsn & 4294967295:08X}" + + command += lsn + + if timeline != 0: + if slot_type == REPLICATION_LOGICAL: + raise psycopg2.ProgrammingError( + "cannot specify timeline for logical replication") + + command += f" TIMELINE {timeline}" + + if options: + if slot_type == REPLICATION_PHYSICAL: + raise psycopg2.ProgrammingError( + "cannot specify output plugin options for physical replication") + + command += " (" + for k, v in options.items(): + if not command.endswith('('): + command += ", " + command += f"{quote_ident(k, self)} {_A(str(v))}" + command += ")" + + self.start_replication_expert( + command, decode=decode, status_interval=status_interval) + + # allows replication cursors to be used in select.select() directly + def fileno(self): + return self.connection.fileno() + + +# a dbtype and adapter for Python UUID type + +class UUID_adapter: + """Adapt Python's uuid.UUID__ type to PostgreSQL's uuid__. + + .. __: https://docs.python.org/library/uuid.html + .. __: https://www.postgresql.org/docs/current/static/datatype-uuid.html + """ + + def __init__(self, uuid): + self._uuid = uuid + + def __conform__(self, proto): + if proto is _ext.ISQLQuote: + return self + + def getquoted(self): + return (f"'{self._uuid}'::uuid").encode('utf8') + + def __str__(self): + return f"'{self._uuid}'::uuid" + + +def register_uuid(oids=None, conn_or_curs=None): + """Create the UUID type and an uuid.UUID adapter. + + :param oids: oid for the PostgreSQL :sql:`uuid` type, or 2-items sequence + with oids of the type and the array. If not specified, use PostgreSQL + standard oids. + :param conn_or_curs: where to register the typecaster. If not specified, + register it globally. + """ + + import uuid + + if not oids: + oid1 = 2950 + oid2 = 2951 + elif isinstance(oids, (list, tuple)): + oid1, oid2 = oids + else: + oid1 = oids + oid2 = 2951 + + _ext.UUID = _ext.new_type((oid1, ), "UUID", + lambda data, cursor: data and uuid.UUID(data) or None) + _ext.UUIDARRAY = _ext.new_array_type((oid2,), "UUID[]", _ext.UUID) + + _ext.register_type(_ext.UUID, conn_or_curs) + _ext.register_type(_ext.UUIDARRAY, conn_or_curs) + _ext.register_adapter(uuid.UUID, UUID_adapter) + + return _ext.UUID + + +# a type, dbtype and adapter for PostgreSQL inet type + +class Inet: + """Wrap a string to allow for correct SQL-quoting of inet values. + + Note that this adapter does NOT check the passed value to make + sure it really is an inet-compatible address but DOES call adapt() + on it to make sure it is impossible to execute an SQL-injection + by passing an evil value to the initializer. + """ + def __init__(self, addr): + self.addr = addr + + def __repr__(self): + return f"{self.__class__.__name__}({self.addr!r})" + + def prepare(self, conn): + self._conn = conn + + def getquoted(self): + obj = _A(self.addr) + if hasattr(obj, 'prepare'): + obj.prepare(self._conn) + return obj.getquoted() + b"::inet" + + def __conform__(self, proto): + if proto is _ext.ISQLQuote: + return self + + def __str__(self): + return str(self.addr) + + +def register_inet(oid=None, conn_or_curs=None): + """Create the INET type and an Inet adapter. + + :param oid: oid for the PostgreSQL :sql:`inet` type, or 2-items sequence + with oids of the type and the array. If not specified, use PostgreSQL + standard oids. + :param conn_or_curs: where to register the typecaster. If not specified, + register it globally. + """ + import warnings + warnings.warn( + "the inet adapter is deprecated, it's not very useful", + DeprecationWarning) + + if not oid: + oid1 = 869 + oid2 = 1041 + elif isinstance(oid, (list, tuple)): + oid1, oid2 = oid + else: + oid1 = oid + oid2 = 1041 + + _ext.INET = _ext.new_type((oid1, ), "INET", + lambda data, cursor: data and Inet(data) or None) + _ext.INETARRAY = _ext.new_array_type((oid2, ), "INETARRAY", _ext.INET) + + _ext.register_type(_ext.INET, conn_or_curs) + _ext.register_type(_ext.INETARRAY, conn_or_curs) + + return _ext.INET + + +def wait_select(conn): + """Wait until a connection or cursor has data available. + + The function is an example of a wait callback to be registered with + `~psycopg2.extensions.set_wait_callback()`. This function uses + :py:func:`~select.select()` to wait for data to become available, and + therefore is able to handle/receive SIGINT/KeyboardInterrupt. + """ + import select + from psycopg2.extensions import POLL_OK, POLL_READ, POLL_WRITE + + while True: + try: + state = conn.poll() + if state == POLL_OK: + break + elif state == POLL_READ: + select.select([conn.fileno()], [], []) + elif state == POLL_WRITE: + select.select([], [conn.fileno()], []) + else: + raise conn.OperationalError(f"bad state from poll: {state}") + except KeyboardInterrupt: + conn.cancel() + # the loop will be broken by a server error + continue + + +def _solve_conn_curs(conn_or_curs): + """Return the connection and a DBAPI cursor from a connection or cursor.""" + if conn_or_curs is None: + raise psycopg2.ProgrammingError("no connection or cursor provided") + + if hasattr(conn_or_curs, 'execute'): + conn = conn_or_curs.connection + curs = conn.cursor(cursor_factory=_cursor) + else: + conn = conn_or_curs + curs = conn.cursor(cursor_factory=_cursor) + + return conn, curs + + +class HstoreAdapter: + """Adapt a Python dict to the hstore syntax.""" + def __init__(self, wrapped): + self.wrapped = wrapped + + def prepare(self, conn): + self.conn = conn + + # use an old-style getquoted implementation if required + if conn.info.server_version < 90000: + self.getquoted = self._getquoted_8 + + def _getquoted_8(self): + """Use the operators available in PG pre-9.0.""" + if not self.wrapped: + return b"''::hstore" + + adapt = _ext.adapt + rv = [] + for k, v in self.wrapped.items(): + k = adapt(k) + k.prepare(self.conn) + k = k.getquoted() + + if v is not None: + v = adapt(v) + v.prepare(self.conn) + v = v.getquoted() + else: + v = b'NULL' + + # XXX this b'ing is painfully inefficient! + rv.append(b"(" + k + b" => " + v + b")") + + return b"(" + b'||'.join(rv) + b")" + + def _getquoted_9(self): + """Use the hstore(text[], text[]) function.""" + if not self.wrapped: + return b"''::hstore" + + k = _ext.adapt(list(self.wrapped.keys())) + k.prepare(self.conn) + v = _ext.adapt(list(self.wrapped.values())) + v.prepare(self.conn) + return b"hstore(" + k.getquoted() + b", " + v.getquoted() + b")" + + getquoted = _getquoted_9 + + _re_hstore = _re.compile(r""" + # hstore key: + # a string of normal or escaped chars + "((?: [^"\\] | \\. )*)" + \s*=>\s* # hstore value + (?: + NULL # the value can be null - not catched + # or a quoted string like the key + | "((?: [^"\\] | \\. )*)" + ) + (?:\s*,\s*|$) # pairs separated by comma or end of string. + """, _re.VERBOSE) + + @classmethod + def parse(self, s, cur, _bsdec=_re.compile(r"\\(.)")): + """Parse an hstore representation in a Python string. + + The hstore is represented as something like:: + + "a"=>"1", "b"=>"2" + + with backslash-escaped strings. + """ + if s is None: + return None + + rv = {} + start = 0 + for m in self._re_hstore.finditer(s): + if m is None or m.start() != start: + raise psycopg2.InterfaceError( + f"error parsing hstore pair at char {start}") + k = _bsdec.sub(r'\1', m.group(1)) + v = m.group(2) + if v is not None: + v = _bsdec.sub(r'\1', v) + + rv[k] = v + start = m.end() + + if start < len(s): + raise psycopg2.InterfaceError( + f"error parsing hstore: unparsed data after char {start}") + + return rv + + @classmethod + def parse_unicode(self, s, cur): + """Parse an hstore returning unicode keys and values.""" + if s is None: + return None + + s = s.decode(_ext.encodings[cur.connection.encoding]) + return self.parse(s, cur) + + @classmethod + def get_oids(self, conn_or_curs): + """Return the lists of OID of the hstore and hstore[] types. + """ + conn, curs = _solve_conn_curs(conn_or_curs) + + # Store the transaction status of the connection to revert it after use + conn_status = conn.status + + # column typarray not available before PG 8.3 + typarray = conn.info.server_version >= 80300 and "typarray" or "NULL" + + rv0, rv1 = [], [] + + # get the oid for the hstore + curs.execute(f"""SELECT t.oid, {typarray} +FROM pg_type t JOIN pg_namespace ns + ON typnamespace = ns.oid +WHERE typname = 'hstore'; +""") + for oids in curs: + rv0.append(oids[0]) + rv1.append(oids[1]) + + # revert the status of the connection as before the command + if (conn_status != _ext.STATUS_IN_TRANSACTION + and not conn.autocommit): + conn.rollback() + + return tuple(rv0), tuple(rv1) + + +def register_hstore(conn_or_curs, globally=False, unicode=False, + oid=None, array_oid=None): + r"""Register adapter and typecaster for `!dict`\-\ |hstore| conversions. + + :param conn_or_curs: a connection or cursor: the typecaster will be + registered only on this object unless *globally* is set to `!True` + :param globally: register the adapter globally, not only on *conn_or_curs* + :param unicode: if `!True`, keys and values returned from the database + will be `!unicode` instead of `!str`. The option is not available on + Python 3 + :param oid: the OID of the |hstore| type if known. If not, it will be + queried on *conn_or_curs*. + :param array_oid: the OID of the |hstore| array type if known. If not, it + will be queried on *conn_or_curs*. + + The connection or cursor passed to the function will be used to query the + database and look for the OID of the |hstore| type (which may be different + across databases). If querying is not desirable (e.g. with + :ref:`asynchronous connections `) you may specify it in the + *oid* parameter, which can be found using a query such as :sql:`SELECT + 'hstore'::regtype::oid`. Analogously you can obtain a value for *array_oid* + using a query such as :sql:`SELECT 'hstore[]'::regtype::oid`. + + Note that, when passing a dictionary from Python to the database, both + strings and unicode keys and values are supported. Dictionaries returned + from the database have keys/values according to the *unicode* parameter. + + The |hstore| contrib module must be already installed in the database + (executing the ``hstore.sql`` script in your ``contrib`` directory). + Raise `~psycopg2.ProgrammingError` if the type is not found. + """ + if oid is None: + oid = HstoreAdapter.get_oids(conn_or_curs) + if oid is None or not oid[0]: + raise psycopg2.ProgrammingError( + "hstore type not found in the database. " + "please install it from your 'contrib/hstore.sql' file") + else: + array_oid = oid[1] + oid = oid[0] + + if isinstance(oid, int): + oid = (oid,) + + if array_oid is not None: + if isinstance(array_oid, int): + array_oid = (array_oid,) + else: + array_oid = tuple([x for x in array_oid if x]) + + # create and register the typecaster + HSTORE = _ext.new_type(oid, "HSTORE", HstoreAdapter.parse) + _ext.register_type(HSTORE, not globally and conn_or_curs or None) + _ext.register_adapter(dict, HstoreAdapter) + + if array_oid: + HSTOREARRAY = _ext.new_array_type(array_oid, "HSTOREARRAY", HSTORE) + _ext.register_type(HSTOREARRAY, not globally and conn_or_curs or None) + + +class CompositeCaster: + """Helps conversion of a PostgreSQL composite type into a Python object. + + The class is usually created by the `register_composite()` function. + You may want to create and register manually instances of the class if + querying the database at registration time is not desirable (such as when + using an :ref:`asynchronous connections `). + + """ + def __init__(self, name, oid, attrs, array_oid=None, schema=None): + self.name = name + self.schema = schema + self.oid = oid + self.array_oid = array_oid + + self.attnames = [a[0] for a in attrs] + self.atttypes = [a[1] for a in attrs] + self._create_type(name, self.attnames) + self.typecaster = _ext.new_type((oid,), name, self.parse) + if array_oid: + self.array_typecaster = _ext.new_array_type( + (array_oid,), f"{name}ARRAY", self.typecaster) + else: + self.array_typecaster = None + + def parse(self, s, curs): + if s is None: + return None + + tokens = self.tokenize(s) + if len(tokens) != len(self.atttypes): + raise psycopg2.DataError( + "expecting %d components for the type %s, %d found instead" % + (len(self.atttypes), self.name, len(tokens))) + + values = [curs.cast(oid, token) + for oid, token in zip(self.atttypes, tokens)] + + return self.make(values) + + def make(self, values): + """Return a new Python object representing the data being casted. + + *values* is the list of attributes, already casted into their Python + representation. + + You can subclass this method to :ref:`customize the composite cast + `. + """ + + return self._ctor(values) + + _re_tokenize = _re.compile(r""" + \(? ([,)]) # an empty token, representing NULL +| \(? " ((?: [^"] | "")*) " [,)] # or a quoted string +| \(? ([^",)]+) [,)] # or an unquoted string + """, _re.VERBOSE) + + _re_undouble = _re.compile(r'(["\\])\1') + + @classmethod + def tokenize(self, s): + rv = [] + for m in self._re_tokenize.finditer(s): + if m is None: + raise psycopg2.InterfaceError(f"can't parse type: {s!r}") + if m.group(1) is not None: + rv.append(None) + elif m.group(2) is not None: + rv.append(self._re_undouble.sub(r"\1", m.group(2))) + else: + rv.append(m.group(3)) + + return rv + + def _create_type(self, name, attnames): + name = _re_clean.sub('_', name) + self.type = namedtuple(name, attnames) + self._ctor = self.type._make + + @classmethod + def _from_db(self, name, conn_or_curs): + """Return a `CompositeCaster` instance for the type *name*. + + Raise `ProgrammingError` if the type is not found. + """ + conn, curs = _solve_conn_curs(conn_or_curs) + + # Store the transaction status of the connection to revert it after use + conn_status = conn.status + + # Use the correct schema + if '.' in name: + schema, tname = name.split('.', 1) + else: + tname = name + schema = 'public' + + # column typarray not available before PG 8.3 + typarray = conn.info.server_version >= 80300 and "typarray" or "NULL" + + # get the type oid and attributes + curs.execute("""\ +SELECT t.oid, %s, attname, atttypid +FROM pg_type t +JOIN pg_namespace ns ON typnamespace = ns.oid +JOIN pg_attribute a ON attrelid = typrelid +WHERE typname = %%s AND nspname = %%s + AND attnum > 0 AND NOT attisdropped +ORDER BY attnum; +""" % typarray, (tname, schema)) + + recs = curs.fetchall() + + if not recs: + # The above algorithm doesn't work for customized seach_path + # (#1487) The implementation below works better, but, to guarantee + # backwards compatibility, use it only if the original one failed. + try: + savepoint = False + # Because we executed statements earlier, we are either INTRANS + # or we are IDLE only if the transaction is autocommit, in + # which case we don't need the savepoint anyway. + if conn.status == _ext.STATUS_IN_TRANSACTION: + curs.execute("SAVEPOINT register_type") + savepoint = True + + curs.execute("""\ +SELECT t.oid, %s, attname, atttypid, typname, nspname +FROM pg_type t +JOIN pg_namespace ns ON typnamespace = ns.oid +JOIN pg_attribute a ON attrelid = typrelid +WHERE t.oid = %%s::regtype + AND attnum > 0 AND NOT attisdropped +ORDER BY attnum; +""" % typarray, (name, )) + except psycopg2.ProgrammingError: + pass + else: + recs = curs.fetchall() + if recs: + tname = recs[0][4] + schema = recs[0][5] + finally: + if savepoint: + curs.execute("ROLLBACK TO SAVEPOINT register_type") + + # revert the status of the connection as before the command + if conn_status != _ext.STATUS_IN_TRANSACTION and not conn.autocommit: + conn.rollback() + + if not recs: + raise psycopg2.ProgrammingError( + f"PostgreSQL type '{name}' not found") + + type_oid = recs[0][0] + array_oid = recs[0][1] + type_attrs = [(r[2], r[3]) for r in recs] + + return self(tname, type_oid, type_attrs, + array_oid=array_oid, schema=schema) + + +def register_composite(name, conn_or_curs, globally=False, factory=None): + """Register a typecaster to convert a composite type into a tuple. + + :param name: the name of a PostgreSQL composite type, e.g. created using + the |CREATE TYPE|_ command + :param conn_or_curs: a connection or cursor used to find the type oid and + components; the typecaster is registered in a scope limited to this + object, unless *globally* is set to `!True` + :param globally: if `!False` (default) register the typecaster only on + *conn_or_curs*, otherwise register it globally + :param factory: if specified it should be a `CompositeCaster` subclass: use + it to :ref:`customize how to cast composite types ` + :return: the registered `CompositeCaster` or *factory* instance + responsible for the conversion + """ + if factory is None: + factory = CompositeCaster + + caster = factory._from_db(name, conn_or_curs) + _ext.register_type(caster.typecaster, not globally and conn_or_curs or None) + + if caster.array_typecaster is not None: + _ext.register_type( + caster.array_typecaster, not globally and conn_or_curs or None) + + return caster + + +def _paginate(seq, page_size): + """Consume an iterable and return it in chunks. + + Every chunk is at most `page_size`. Never return an empty chunk. + """ + page = [] + it = iter(seq) + while True: + try: + for i in range(page_size): + page.append(next(it)) + yield page + page = [] + except StopIteration: + if page: + yield page + return + + +def execute_batch(cur, sql, argslist, page_size=100): + r"""Execute groups of statements in fewer server roundtrips. + + Execute *sql* several times, against all parameters set (sequences or + mappings) found in *argslist*. + + The function is semantically similar to + + .. parsed-literal:: + + *cur*\.\ `~cursor.executemany`\ (\ *sql*\ , *argslist*\ ) + + but has a different implementation: Psycopg will join the statements into + fewer multi-statement commands, each one containing at most *page_size* + statements, resulting in a reduced number of server roundtrips. + + After the execution of the function the `cursor.rowcount` property will + **not** contain a total result. + + """ + for page in _paginate(argslist, page_size=page_size): + sqls = [cur.mogrify(sql, args) for args in page] + cur.execute(b";".join(sqls)) + + +def execute_values(cur, sql, argslist, template=None, page_size=100, fetch=False): + '''Execute a statement using :sql:`VALUES` with a sequence of parameters. + + :param cur: the cursor to use to execute the query. + + :param sql: the query to execute. It must contain a single ``%s`` + placeholder, which will be replaced by a `VALUES list`__. + Example: ``"INSERT INTO mytable (id, f1, f2) VALUES %s"``. + + :param argslist: sequence of sequences or dictionaries with the arguments + to send to the query. The type and content must be consistent with + *template*. + + :param template: the snippet to merge to every item in *argslist* to + compose the query. + + - If the *argslist* items are sequences it should contain positional + placeholders (e.g. ``"(%s, %s, %s)"``, or ``"(%s, %s, 42)``" if there + are constants value...). + + - If the *argslist* items are mappings it should contain named + placeholders (e.g. ``"(%(id)s, %(f1)s, 42)"``). + + If not specified, assume the arguments are sequence and use a simple + positional template (i.e. ``(%s, %s, ...)``), with the number of + placeholders sniffed by the first element in *argslist*. + + :param page_size: maximum number of *argslist* items to include in every + statement. If there are more items the function will execute more than + one statement. + + :param fetch: if `!True` return the query results into a list (like in a + `~cursor.fetchall()`). Useful for queries with :sql:`RETURNING` + clause. + + .. __: https://www.postgresql.org/docs/current/static/queries-values.html + + After the execution of the function the `cursor.rowcount` property will + **not** contain a total result. + + While :sql:`INSERT` is an obvious candidate for this function it is + possible to use it with other statements, for example:: + + >>> cur.execute( + ... "create table test (id int primary key, v1 int, v2 int)") + + >>> execute_values(cur, + ... "INSERT INTO test (id, v1, v2) VALUES %s", + ... [(1, 2, 3), (4, 5, 6), (7, 8, 9)]) + + >>> execute_values(cur, + ... """UPDATE test SET v1 = data.v1 FROM (VALUES %s) AS data (id, v1) + ... WHERE test.id = data.id""", + ... [(1, 20), (4, 50)]) + + >>> cur.execute("select * from test order by id") + >>> cur.fetchall() + [(1, 20, 3), (4, 50, 6), (7, 8, 9)]) + + ''' + from psycopg2.sql import Composable + if isinstance(sql, Composable): + sql = sql.as_string(cur) + + # we can't just use sql % vals because vals is bytes: if sql is bytes + # there will be some decoding error because of stupid codec used, and Py3 + # doesn't implement % on bytes. + if not isinstance(sql, bytes): + sql = sql.encode(_ext.encodings[cur.connection.encoding]) + pre, post = _split_sql(sql) + + result = [] if fetch else None + for page in _paginate(argslist, page_size=page_size): + if template is None: + template = b'(' + b','.join([b'%s'] * len(page[0])) + b')' + parts = pre[:] + for args in page: + parts.append(cur.mogrify(template, args)) + parts.append(b',') + parts[-1:] = post + cur.execute(b''.join(parts)) + if fetch: + result.extend(cur.fetchall()) + + return result + + +def _split_sql(sql): + """Split *sql* on a single ``%s`` placeholder. + + Split on the %s, perform %% replacement and return pre, post lists of + snippets. + """ + curr = pre = [] + post = [] + tokens = _re.split(br'(%.)', sql) + for token in tokens: + if len(token) != 2 or token[:1] != b'%': + curr.append(token) + continue + + if token[1:] == b's': + if curr is pre: + curr = post + else: + raise ValueError( + "the query contains more than one '%s' placeholder") + elif token[1:] == b'%': + curr.append(b'%') + else: + raise ValueError("unsupported format character: '%s'" + % token[1:].decode('ascii', 'replace')) + + if curr is pre: + raise ValueError("the query doesn't contain any '%s' placeholder") + + return pre, post + + +# ascii except alnum and underscore +_re_clean = _re.compile( + '[' + _re.escape(' !"#$%&\'()*+,-./:;<=>?@[\\]^`{|}~') + ']') diff --git a/env/Lib/site-packages/psycopg2/pool.py b/env/Lib/site-packages/psycopg2/pool.py new file mode 100644 index 0000000..9d67d68 --- /dev/null +++ b/env/Lib/site-packages/psycopg2/pool.py @@ -0,0 +1,187 @@ +"""Connection pooling for psycopg2 + +This module implements thread-safe (and not) connection pools. +""" +# psycopg/pool.py - pooling code for psycopg +# +# Copyright (C) 2003-2019 Federico Di Gregorio +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +import psycopg2 +from psycopg2 import extensions as _ext + + +class PoolError(psycopg2.Error): + pass + + +class AbstractConnectionPool: + """Generic key-based pooling code.""" + + def __init__(self, minconn, maxconn, *args, **kwargs): + """Initialize the connection pool. + + New 'minconn' connections are created immediately calling 'connfunc' + with given parameters. The connection pool will support a maximum of + about 'maxconn' connections. + """ + self.minconn = int(minconn) + self.maxconn = int(maxconn) + self.closed = False + + self._args = args + self._kwargs = kwargs + + self._pool = [] + self._used = {} + self._rused = {} # id(conn) -> key map + self._keys = 0 + + for i in range(self.minconn): + self._connect() + + def _connect(self, key=None): + """Create a new connection and assign it to 'key' if not None.""" + conn = psycopg2.connect(*self._args, **self._kwargs) + if key is not None: + self._used[key] = conn + self._rused[id(conn)] = key + else: + self._pool.append(conn) + return conn + + def _getkey(self): + """Return a new unique key.""" + self._keys += 1 + return self._keys + + def _getconn(self, key=None): + """Get a free connection and assign it to 'key' if not None.""" + if self.closed: + raise PoolError("connection pool is closed") + if key is None: + key = self._getkey() + + if key in self._used: + return self._used[key] + + if self._pool: + self._used[key] = conn = self._pool.pop() + self._rused[id(conn)] = key + return conn + else: + if len(self._used) == self.maxconn: + raise PoolError("connection pool exhausted") + return self._connect(key) + + def _putconn(self, conn, key=None, close=False): + """Put away a connection.""" + if self.closed: + raise PoolError("connection pool is closed") + + if key is None: + key = self._rused.get(id(conn)) + if key is None: + raise PoolError("trying to put unkeyed connection") + + if len(self._pool) < self.minconn and not close: + # Return the connection into a consistent state before putting + # it back into the pool + if not conn.closed: + status = conn.info.transaction_status + if status == _ext.TRANSACTION_STATUS_UNKNOWN: + # server connection lost + conn.close() + elif status != _ext.TRANSACTION_STATUS_IDLE: + # connection in error or in transaction + conn.rollback() + self._pool.append(conn) + else: + # regular idle connection + self._pool.append(conn) + # If the connection is closed, we just discard it. + else: + conn.close() + + # here we check for the presence of key because it can happen that a + # thread tries to put back a connection after a call to close + if not self.closed or key in self._used: + del self._used[key] + del self._rused[id(conn)] + + def _closeall(self): + """Close all connections. + + Note that this can lead to some code fail badly when trying to use + an already closed connection. If you call .closeall() make sure + your code can deal with it. + """ + if self.closed: + raise PoolError("connection pool is closed") + for conn in self._pool + list(self._used.values()): + try: + conn.close() + except Exception: + pass + self.closed = True + + +class SimpleConnectionPool(AbstractConnectionPool): + """A connection pool that can't be shared across different threads.""" + + getconn = AbstractConnectionPool._getconn + putconn = AbstractConnectionPool._putconn + closeall = AbstractConnectionPool._closeall + + +class ThreadedConnectionPool(AbstractConnectionPool): + """A connection pool that works with the threading module.""" + + def __init__(self, minconn, maxconn, *args, **kwargs): + """Initialize the threading lock.""" + import threading + AbstractConnectionPool.__init__( + self, minconn, maxconn, *args, **kwargs) + self._lock = threading.Lock() + + def getconn(self, key=None): + """Get a free connection and assign it to 'key' if not None.""" + self._lock.acquire() + try: + return self._getconn(key) + finally: + self._lock.release() + + def putconn(self, conn=None, key=None, close=False): + """Put away an unused connection.""" + self._lock.acquire() + try: + self._putconn(conn, key, close) + finally: + self._lock.release() + + def closeall(self): + """Close all connections (even the one currently in use.)""" + self._lock.acquire() + try: + self._closeall() + finally: + self._lock.release() diff --git a/env/Lib/site-packages/psycopg2/sql.py b/env/Lib/site-packages/psycopg2/sql.py new file mode 100644 index 0000000..69b352b --- /dev/null +++ b/env/Lib/site-packages/psycopg2/sql.py @@ -0,0 +1,455 @@ +"""SQL composition utility module +""" + +# psycopg/sql.py - SQL composition utility module +# +# Copyright (C) 2016-2019 Daniele Varrazzo +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +import string + +from psycopg2 import extensions as ext + + +_formatter = string.Formatter() + + +class Composable: + """ + Abstract base class for objects that can be used to compose an SQL string. + + `!Composable` objects can be passed directly to `~cursor.execute()`, + `~cursor.executemany()`, `~cursor.copy_expert()` in place of the query + string. + + `!Composable` objects can be joined using the ``+`` operator: the result + will be a `Composed` instance containing the objects joined. The operator + ``*`` is also supported with an integer argument: the result is a + `!Composed` instance containing the left argument repeated as many times as + requested. + """ + def __init__(self, wrapped): + self._wrapped = wrapped + + def __repr__(self): + return f"{self.__class__.__name__}({self._wrapped!r})" + + def as_string(self, context): + """ + Return the string value of the object. + + :param context: the context to evaluate the string into. + :type context: `connection` or `cursor` + + The method is automatically invoked by `~cursor.execute()`, + `~cursor.executemany()`, `~cursor.copy_expert()` if a `!Composable` is + passed instead of the query string. + """ + raise NotImplementedError + + def __add__(self, other): + if isinstance(other, Composed): + return Composed([self]) + other + if isinstance(other, Composable): + return Composed([self]) + Composed([other]) + else: + return NotImplemented + + def __mul__(self, n): + return Composed([self] * n) + + def __eq__(self, other): + return type(self) is type(other) and self._wrapped == other._wrapped + + def __ne__(self, other): + return not self.__eq__(other) + + +class Composed(Composable): + """ + A `Composable` object made of a sequence of `!Composable`. + + The object is usually created using `!Composable` operators and methods. + However it is possible to create a `!Composed` directly specifying a + sequence of `!Composable` as arguments. + + Example:: + + >>> comp = sql.Composed( + ... [sql.SQL("insert into "), sql.Identifier("table")]) + >>> print(comp.as_string(conn)) + insert into "table" + + `!Composed` objects are iterable (so they can be used in `SQL.join` for + instance). + """ + def __init__(self, seq): + wrapped = [] + for i in seq: + if not isinstance(i, Composable): + raise TypeError( + f"Composed elements must be Composable, got {i!r} instead") + wrapped.append(i) + + super().__init__(wrapped) + + @property + def seq(self): + """The list of the content of the `!Composed`.""" + return list(self._wrapped) + + def as_string(self, context): + rv = [] + for i in self._wrapped: + rv.append(i.as_string(context)) + return ''.join(rv) + + def __iter__(self): + return iter(self._wrapped) + + def __add__(self, other): + if isinstance(other, Composed): + return Composed(self._wrapped + other._wrapped) + if isinstance(other, Composable): + return Composed(self._wrapped + [other]) + else: + return NotImplemented + + def join(self, joiner): + """ + Return a new `!Composed` interposing the *joiner* with the `!Composed` items. + + The *joiner* must be a `SQL` or a string which will be interpreted as + an `SQL`. + + Example:: + + >>> fields = sql.Identifier('foo') + sql.Identifier('bar') # a Composed + >>> print(fields.join(', ').as_string(conn)) + "foo", "bar" + + """ + if isinstance(joiner, str): + joiner = SQL(joiner) + elif not isinstance(joiner, SQL): + raise TypeError( + "Composed.join() argument must be a string or an SQL") + + return joiner.join(self) + + +class SQL(Composable): + """ + A `Composable` representing a snippet of SQL statement. + + `!SQL` exposes `join()` and `format()` methods useful to create a template + where to merge variable parts of a query (for instance field or table + names). + + The *string* doesn't undergo any form of escaping, so it is not suitable to + represent variable identifiers or values: you should only use it to pass + constant strings representing templates or snippets of SQL statements; use + other objects such as `Identifier` or `Literal` to represent variable + parts. + + Example:: + + >>> query = sql.SQL("select {0} from {1}").format( + ... sql.SQL(', ').join([sql.Identifier('foo'), sql.Identifier('bar')]), + ... sql.Identifier('table')) + >>> print(query.as_string(conn)) + select "foo", "bar" from "table" + """ + def __init__(self, string): + if not isinstance(string, str): + raise TypeError("SQL values must be strings") + super().__init__(string) + + @property + def string(self): + """The string wrapped by the `!SQL` object.""" + return self._wrapped + + def as_string(self, context): + return self._wrapped + + def format(self, *args, **kwargs): + """ + Merge `Composable` objects into a template. + + :param `Composable` args: parameters to replace to numbered + (``{0}``, ``{1}``) or auto-numbered (``{}``) placeholders + :param `Composable` kwargs: parameters to replace to named (``{name}``) + placeholders + :return: the union of the `!SQL` string with placeholders replaced + :rtype: `Composed` + + The method is similar to the Python `str.format()` method: the string + template supports auto-numbered (``{}``), numbered (``{0}``, + ``{1}``...), and named placeholders (``{name}``), with positional + arguments replacing the numbered placeholders and keywords replacing + the named ones. However placeholder modifiers (``{0!r}``, ``{0:<10}``) + are not supported. Only `!Composable` objects can be passed to the + template. + + Example:: + + >>> print(sql.SQL("select * from {} where {} = %s") + ... .format(sql.Identifier('people'), sql.Identifier('id')) + ... .as_string(conn)) + select * from "people" where "id" = %s + + >>> print(sql.SQL("select * from {tbl} where {pkey} = %s") + ... .format(tbl=sql.Identifier('people'), pkey=sql.Identifier('id')) + ... .as_string(conn)) + select * from "people" where "id" = %s + + """ + rv = [] + autonum = 0 + for pre, name, spec, conv in _formatter.parse(self._wrapped): + if spec: + raise ValueError("no format specification supported by SQL") + if conv: + raise ValueError("no format conversion supported by SQL") + if pre: + rv.append(SQL(pre)) + + if name is None: + continue + + if name.isdigit(): + if autonum: + raise ValueError( + "cannot switch from automatic field numbering to manual") + rv.append(args[int(name)]) + autonum = None + + elif not name: + if autonum is None: + raise ValueError( + "cannot switch from manual field numbering to automatic") + rv.append(args[autonum]) + autonum += 1 + + else: + rv.append(kwargs[name]) + + return Composed(rv) + + def join(self, seq): + """ + Join a sequence of `Composable`. + + :param seq: the elements to join. + :type seq: iterable of `!Composable` + + Use the `!SQL` object's *string* to separate the elements in *seq*. + Note that `Composed` objects are iterable too, so they can be used as + argument for this method. + + Example:: + + >>> snip = sql.SQL(', ').join( + ... sql.Identifier(n) for n in ['foo', 'bar', 'baz']) + >>> print(snip.as_string(conn)) + "foo", "bar", "baz" + """ + rv = [] + it = iter(seq) + try: + rv.append(next(it)) + except StopIteration: + pass + else: + for i in it: + rv.append(self) + rv.append(i) + + return Composed(rv) + + +class Identifier(Composable): + """ + A `Composable` representing an SQL identifier or a dot-separated sequence. + + Identifiers usually represent names of database objects, such as tables or + fields. PostgreSQL identifiers follow `different rules`__ than SQL string + literals for escaping (e.g. they use double quotes instead of single). + + .. __: https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html# \ + SQL-SYNTAX-IDENTIFIERS + + Example:: + + >>> t1 = sql.Identifier("foo") + >>> t2 = sql.Identifier("ba'r") + >>> t3 = sql.Identifier('ba"z') + >>> print(sql.SQL(', ').join([t1, t2, t3]).as_string(conn)) + "foo", "ba'r", "ba""z" + + Multiple strings can be passed to the object to represent a qualified name, + i.e. a dot-separated sequence of identifiers. + + Example:: + + >>> query = sql.SQL("select {} from {}").format( + ... sql.Identifier("table", "field"), + ... sql.Identifier("schema", "table")) + >>> print(query.as_string(conn)) + select "table"."field" from "schema"."table" + + """ + def __init__(self, *strings): + if not strings: + raise TypeError("Identifier cannot be empty") + + for s in strings: + if not isinstance(s, str): + raise TypeError("SQL identifier parts must be strings") + + super().__init__(strings) + + @property + def strings(self): + """A tuple with the strings wrapped by the `Identifier`.""" + return self._wrapped + + @property + def string(self): + """The string wrapped by the `Identifier`. + """ + if len(self._wrapped) == 1: + return self._wrapped[0] + else: + raise AttributeError( + "the Identifier wraps more than one than one string") + + def __repr__(self): + return f"{self.__class__.__name__}({', '.join(map(repr, self._wrapped))})" + + def as_string(self, context): + return '.'.join(ext.quote_ident(s, context) for s in self._wrapped) + + +class Literal(Composable): + """ + A `Composable` representing an SQL value to include in a query. + + Usually you will want to include placeholders in the query and pass values + as `~cursor.execute()` arguments. If however you really really need to + include a literal value in the query you can use this object. + + The string returned by `!as_string()` follows the normal :ref:`adaptation + rules ` for Python objects. + + Example:: + + >>> s1 = sql.Literal("foo") + >>> s2 = sql.Literal("ba'r") + >>> s3 = sql.Literal(42) + >>> print(sql.SQL(', ').join([s1, s2, s3]).as_string(conn)) + 'foo', 'ba''r', 42 + + """ + @property + def wrapped(self): + """The object wrapped by the `!Literal`.""" + return self._wrapped + + def as_string(self, context): + # is it a connection or cursor? + if isinstance(context, ext.connection): + conn = context + elif isinstance(context, ext.cursor): + conn = context.connection + else: + raise TypeError("context must be a connection or a cursor") + + a = ext.adapt(self._wrapped) + if hasattr(a, 'prepare'): + a.prepare(conn) + + rv = a.getquoted() + if isinstance(rv, bytes): + rv = rv.decode(ext.encodings[conn.encoding]) + + return rv + + +class Placeholder(Composable): + """A `Composable` representing a placeholder for query parameters. + + If the name is specified, generate a named placeholder (e.g. ``%(name)s``), + otherwise generate a positional placeholder (e.g. ``%s``). + + The object is useful to generate SQL queries with a variable number of + arguments. + + Examples:: + + >>> names = ['foo', 'bar', 'baz'] + + >>> q1 = sql.SQL("insert into table ({}) values ({})").format( + ... sql.SQL(', ').join(map(sql.Identifier, names)), + ... sql.SQL(', ').join(sql.Placeholder() * len(names))) + >>> print(q1.as_string(conn)) + insert into table ("foo", "bar", "baz") values (%s, %s, %s) + + >>> q2 = sql.SQL("insert into table ({}) values ({})").format( + ... sql.SQL(', ').join(map(sql.Identifier, names)), + ... sql.SQL(', ').join(map(sql.Placeholder, names))) + >>> print(q2.as_string(conn)) + insert into table ("foo", "bar", "baz") values (%(foo)s, %(bar)s, %(baz)s) + + """ + + def __init__(self, name=None): + if isinstance(name, str): + if ')' in name: + raise ValueError(f"invalid name: {name!r}") + + elif name is not None: + raise TypeError(f"expected string or None as name, got {name!r}") + + super().__init__(name) + + @property + def name(self): + """The name of the `!Placeholder`.""" + return self._wrapped + + def __repr__(self): + if self._wrapped is None: + return f"{self.__class__.__name__}()" + else: + return f"{self.__class__.__name__}({self._wrapped!r})" + + def as_string(self, context): + if self._wrapped is not None: + return f"%({self._wrapped})s" + else: + return "%s" + + +# Literals +NULL = SQL("NULL") +DEFAULT = SQL("DEFAULT") diff --git a/env/Lib/site-packages/psycopg2/tz.py b/env/Lib/site-packages/psycopg2/tz.py new file mode 100644 index 0000000..d88ca37 --- /dev/null +++ b/env/Lib/site-packages/psycopg2/tz.py @@ -0,0 +1,158 @@ +"""tzinfo implementations for psycopg2 + +This module holds two different tzinfo implementations that can be used as +the 'tzinfo' argument to datetime constructors, directly passed to psycopg +functions or used to set the .tzinfo_factory attribute in cursors. +""" +# psycopg/tz.py - tzinfo implementation +# +# Copyright (C) 2003-2019 Federico Di Gregorio +# Copyright (C) 2020-2021 The Psycopg Team +# +# psycopg2 is free software: you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published +# by the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# In addition, as a special exception, the copyright holders give +# permission to link this program with the OpenSSL library (or with +# modified versions of OpenSSL that use the same license as OpenSSL), +# and distribute linked combinations including the two. +# +# You must obey the GNU Lesser General Public License in all respects for +# all of the code used other than OpenSSL. +# +# psycopg2 is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +# License for more details. + +import datetime +import time + +ZERO = datetime.timedelta(0) + + +class FixedOffsetTimezone(datetime.tzinfo): + """Fixed offset in minutes east from UTC. + + This is exactly the implementation__ found in Python 2.3.x documentation, + with a small change to the `!__init__()` method to allow for pickling + and a default name in the form ``sHH:MM`` (``s`` is the sign.). + + The implementation also caches instances. During creation, if a + FixedOffsetTimezone instance has previously been created with the same + offset and name that instance will be returned. This saves memory and + improves comparability. + + .. versionchanged:: 2.9 + + The constructor can take either a timedelta or a number of minutes of + offset. Previously only minutes were supported. + + .. __: https://docs.python.org/library/datetime.html + """ + _name = None + _offset = ZERO + + _cache = {} + + def __init__(self, offset=None, name=None): + if offset is not None: + if not isinstance(offset, datetime.timedelta): + offset = datetime.timedelta(minutes=offset) + self._offset = offset + if name is not None: + self._name = name + + def __new__(cls, offset=None, name=None): + """Return a suitable instance created earlier if it exists + """ + key = (offset, name) + try: + return cls._cache[key] + except KeyError: + tz = super().__new__(cls, offset, name) + cls._cache[key] = tz + return tz + + def __repr__(self): + return "psycopg2.tz.FixedOffsetTimezone(offset=%r, name=%r)" \ + % (self._offset, self._name) + + def __eq__(self, other): + if isinstance(other, FixedOffsetTimezone): + return self._offset == other._offset + else: + return NotImplemented + + def __ne__(self, other): + if isinstance(other, FixedOffsetTimezone): + return self._offset != other._offset + else: + return NotImplemented + + def __getinitargs__(self): + return self._offset, self._name + + def utcoffset(self, dt): + return self._offset + + def tzname(self, dt): + if self._name is not None: + return self._name + + minutes, seconds = divmod(self._offset.total_seconds(), 60) + hours, minutes = divmod(minutes, 60) + rv = "%+03d" % hours + if minutes or seconds: + rv += ":%02d" % minutes + if seconds: + rv += ":%02d" % seconds + + return rv + + def dst(self, dt): + return ZERO + + +STDOFFSET = datetime.timedelta(seconds=-time.timezone) +if time.daylight: + DSTOFFSET = datetime.timedelta(seconds=-time.altzone) +else: + DSTOFFSET = STDOFFSET +DSTDIFF = DSTOFFSET - STDOFFSET + + +class LocalTimezone(datetime.tzinfo): + """Platform idea of local timezone. + + This is the exact implementation from the Python 2.3 documentation. + """ + def utcoffset(self, dt): + if self._isdst(dt): + return DSTOFFSET + else: + return STDOFFSET + + def dst(self, dt): + if self._isdst(dt): + return DSTDIFF + else: + return ZERO + + def tzname(self, dt): + return time.tzname[self._isdst(dt)] + + def _isdst(self, dt): + tt = (dt.year, dt.month, dt.day, + dt.hour, dt.minute, dt.second, + dt.weekday(), 0, -1) + stamp = time.mktime(tt) + tt = time.localtime(stamp) + return tt.tm_isdst > 0 + + +LOCAL = LocalTimezone() + +# TODO: pre-generate some interesting time zones? diff --git a/env/Lib/site-packages/pydantic-2.8.2.dist-info/INSTALLER b/env/Lib/site-packages/pydantic-2.8.2.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/pydantic-2.8.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/pydantic-2.8.2.dist-info/METADATA b/env/Lib/site-packages/pydantic-2.8.2.dist-info/METADATA new file mode 100644 index 0000000..dc57ef4 --- /dev/null +++ b/env/Lib/site-packages/pydantic-2.8.2.dist-info/METADATA @@ -0,0 +1,1271 @@ +Metadata-Version: 2.3 +Name: pydantic +Version: 2.8.2 +Summary: Data validation using Python type hints +Project-URL: Homepage, https://github.com/pydantic/pydantic +Project-URL: Documentation, https://docs.pydantic.dev +Project-URL: Funding, https://github.com/sponsors/samuelcolvin +Project-URL: Source, https://github.com/pydantic/pydantic +Project-URL: Changelog, https://docs.pydantic.dev/latest/changelog/ +Author-email: Samuel Colvin , Eric Jolibois , Hasan Ramezani , Adrian Garcia Badaracco <1755071+adriangb@users.noreply.github.com>, Terrence Dorsey , David Montague , Serge Matveenko , Marcelo Trylesinski , Sydney Runkle , David Hewitt , Alex Hall +License-Expression: MIT +License-File: LICENSE +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Environment :: MacOS X +Classifier: Framework :: Hypothesis +Classifier: Framework :: Pydantic +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: Intended Audience :: System Administrators +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: Unix +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Internet +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.8 +Requires-Dist: annotated-types>=0.4.0 +Requires-Dist: pydantic-core==2.20.1 +Requires-Dist: typing-extensions>=4.12.2; python_version >= '3.13' +Requires-Dist: typing-extensions>=4.6.1; python_version < '3.13' +Provides-Extra: email +Requires-Dist: email-validator>=2.0.0; extra == 'email' +Description-Content-Type: text/markdown + +# Pydantic +[![CI](https://img.shields.io/github/actions/workflow/status/pydantic/pydantic/ci.yml?branch=main&logo=github&label=CI)](https://github.com/pydantic/pydantic/actions?query=event%3Apush+branch%3Amain+workflow%3ACI) +[![Coverage](https://coverage-badge.samuelcolvin.workers.dev/pydantic/pydantic.svg)](https://coverage-badge.samuelcolvin.workers.dev/redirect/pydantic/pydantic) +[![pypi](https://img.shields.io/pypi/v/pydantic.svg)](https://pypi.python.org/pypi/pydantic) +[![CondaForge](https://img.shields.io/conda/v/conda-forge/pydantic.svg)](https://anaconda.org/conda-forge/pydantic) +[![downloads](https://static.pepy.tech/badge/pydantic/month)](https://pepy.tech/project/pydantic) +[![versions](https://img.shields.io/pypi/pyversions/pydantic.svg)](https://github.com/pydantic/pydantic) +[![license](https://img.shields.io/github/license/pydantic/pydantic.svg)](https://github.com/pydantic/pydantic/blob/main/LICENSE) +[![Pydantic v2](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/pydantic/pydantic/main/docs/badge/v2.json)](https://docs.pydantic.dev/latest/contributing/#badges) + +Data validation using Python type hints. + +Fast and extensible, Pydantic plays nicely with your linters/IDE/brain. +Define how data should be in pure, canonical Python 3.8+; validate it with Pydantic. + +## Pydantic Company :rocket: + +We've started a company based on the principles that I believe have led to Pydantic's success. +Learn more from the [Company Announcement](https://blog.pydantic.dev/blog/2023/02/16/company-announcement--pydantic/). + +## Pydantic V1.10 vs. V2 + +Pydantic V2 is a ground-up rewrite that offers many new features, performance improvements, and some breaking changes compared to Pydantic V1. + +If you're using Pydantic V1 you may want to look at the +[pydantic V1.10 Documentation](https://docs.pydantic.dev/) or, +[`1.10.X-fixes` git branch](https://github.com/pydantic/pydantic/tree/1.10.X-fixes). Pydantic V2 also ships with the latest version of Pydantic V1 built in so that you can incrementally upgrade your code base and projects: `from pydantic import v1 as pydantic_v1`. + +## Help + +See [documentation](https://docs.pydantic.dev/) for more details. + +## Installation + +Install using `pip install -U pydantic` or `conda install pydantic -c conda-forge`. +For more installation options to make Pydantic even faster, +see the [Install](https://docs.pydantic.dev/install/) section in the documentation. + +## A Simple Example + +```py +from datetime import datetime +from typing import List, Optional +from pydantic import BaseModel + +class User(BaseModel): + id: int + name: str = 'John Doe' + signup_ts: Optional[datetime] = None + friends: List[int] = [] + +external_data = {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']} +user = User(**external_data) +print(user) +#> User id=123 name='John Doe' signup_ts=datetime.datetime(2017, 6, 1, 12, 22) friends=[1, 2, 3] +print(user.id) +#> 123 +``` + +## Contributing + +For guidance on setting up a development environment and how to make a +contribution to Pydantic, see +[Contributing to Pydantic](https://docs.pydantic.dev/contributing/). + +## Reporting a Security Vulnerability + +See our [security policy](https://github.com/pydantic/pydantic/security/policy). + +## Changelog + +## v2.8.2 (2024-07-03) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.8.2) + +### What's Changed + +#### Fixes + +* Fix issue with assertion caused by pluggable schema validator by [@dmontagu](https://github.com/dmontagu) in [#9838](https://github.com/pydantic/pydantic/pull/9838) + +## v2.8.1 (2024-07-03) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.8.1) + +### What's Changed + +#### Packaging +* Bump `ruff` to `v0.5.0` and `pyright` to `v1.1.369` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9801](https://github.com/pydantic/pydantic/pull/9801) +* Bump `pydantic-core` to `v2.20.1`, `pydantic-extra-types` to `v2.9.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9832](https://github.com/pydantic/pydantic/pull/9832) + +#### Fixes +* Fix breaking change in `to_snake` from v2.7 -> v2.8 by [@sydney-runkle](https://github.com/sydney-runkle) in [#9812](https://github.com/pydantic/pydantic/pull/9812) +* Fix list constraint json schema application by [@sydney-runkle](https://github.com/sydney-runkle) in [#9818](https://github.com/pydantic/pydantic/pull/9818) +* Support time duration more than 23 by [@nix010](https://github.com/nix010) in [pydantic/speedate#64](https://github.com/pydantic/speedate/pull/64) +* Fix millisecond fraction being handled with the wrong scale by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/speedate#65](https://github.com/pydantic/speedate/pull/65) +* Handle negative fractional durations correctly by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/speedate#71](https://github.com/pydantic/speedate/pull/71) + +## v2.8.0 (2024-07-01) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.8.0) + +The code released in v2.8.0 is functionally identical to that of v2.8.0b1. + +### What's Changed + +#### Packaging + +* Update citation version automatically with new releases by [@sydney-runkle](https://github.com/sydney-runkle) in [#9673](https://github.com/pydantic/pydantic/pull/9673) +* Bump pyright to `v1.1.367` and add type checking tests for pipeline API by [@adriangb](https://github.com/adriangb) in [#9674](https://github.com/pydantic/pydantic/pull/9674) +* Update `pydantic.v1` stub to `v1.10.17` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9707](https://github.com/pydantic/pydantic/pull/9707) +* General package updates to prep for `v2.8.0b1` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9741](https://github.com/pydantic/pydantic/pull/9741) +* Bump `pydantic-core` to `v2.20.0` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9745](https://github.com/pydantic/pydantic/pull/9745) +* Add support for Python 3.13 by [@sydney-runkle](https://github.com/sydney-runkle) in [#9743](https://github.com/pydantic/pydantic/pull/9743) +* Update `pdm` version used for `pdm.lock` to v2.16.1 by [@sydney-runkle](https://github.com/sydney-runkle) in [#9761](https://github.com/pydantic/pydantic/pull/9761) +* Update to `ruff` `v0.4.8` by [@Viicos](https://github.com/Viicos) in [#9585](https://github.com/pydantic/pydantic/pull/9585) + +#### New Features + +* Experimental: support `defer_build` for `TypeAdapter` by [@MarkusSintonen](https://github.com/MarkusSintonen) in [#8939](https://github.com/pydantic/pydantic/pull/8939) +* Implement `deprecated` field in json schema by [@NeevCohen](https://github.com/NeevCohen) in [#9298](https://github.com/pydantic/pydantic/pull/9298) +* Experimental: Add pipeline API by [@adriangb](https://github.com/adriangb) in [#9459](https://github.com/pydantic/pydantic/pull/9459) +* Add support for programmatic title generation by [@NeevCohen](https://github.com/NeevCohen) in [#9183](https://github.com/pydantic/pydantic/pull/9183) +* Implement `fail_fast` feature by [@uriyyo](https://github.com/uriyyo) in [#9708](https://github.com/pydantic/pydantic/pull/9708) +* Add `ser_json_inf_nan='strings'` mode to produce valid JSON by [@josh-newman](https://github.com/josh-newman) in [pydantic/pydantic-core#1307](https://github.com/pydantic/pydantic-core/pull/1307) + +#### Changes + +* Add warning when "alias" is set in ignored `Annotated` field by [@nix010](https://github.com/nix010) in [#9170](https://github.com/pydantic/pydantic/pull/9170) +* Support serialization of some serializable defaults in JSON schema by [@sydney-runkle](https://github.com/sydney-runkle) in [#9624](https://github.com/pydantic/pydantic/pull/9624) +* Relax type specification for `__validators__` values in `create_model` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9697](https://github.com/pydantic/pydantic/pull/9697) +* **Breaking Change:** Improve `smart` union matching logic by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1322](https://github.com/pydantic/pydantic-core/pull/1322) +You can read more about our `smart` union matching logic [here](https://docs.pydantic.dev/dev/concepts/unions/#smart-mode). In some cases, if the old behavior +is desired, you can switch to `left-to-right` mode and change the order of your `Union` members. + +#### Performance + +##### Internal Improvements + +* ⚡️ Speed up `_display_error_loc()` by 25% in `pydantic/v1/error_wrappers.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9653](https://github.com/pydantic/pydantic/pull/9653) +* ⚡️ Speed up `_get_all_json_refs()` by 34% in `pydantic/json_schema.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9650](https://github.com/pydantic/pydantic/pull/9650) +* ⚡️ Speed up `is_pydantic_dataclass()` by 41% in `pydantic/dataclasses.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9652](https://github.com/pydantic/pydantic/pull/9652) +* ⚡️ Speed up `to_snake()` by 27% in `pydantic/alias_generators.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9747](https://github.com/pydantic/pydantic/pull/9747) +* ⚡️ Speed up `unwrap_wrapped_function()` by 93% in `pydantic/_internal/_decorators.py` by [@misrasaurabh1](https://github.com/misrasaurabh1) in [#9727](https://github.com/pydantic/pydantic/pull/9727) + +#### Fixes + +* Replace `__spec__.parent` with `__package__` by [@hramezani](https://github.com/hramezani) in [#9331](https://github.com/pydantic/pydantic/pull/9331) +* Fix Outputted Model JSON Schema for `Sequence` type by [@anesmemisevic](https://github.com/anesmemisevic) in [#9303](https://github.com/pydantic/pydantic/pull/9303) +* Fix typing of `_frame_depth` by [@Viicos](https://github.com/Viicos) in [#9353](https://github.com/pydantic/pydantic/pull/9353) +* Make `ImportString` json schema compatible by [@amitschang](https://github.com/amitschang) in [#9344](https://github.com/pydantic/pydantic/pull/9344) +* Hide private attributes (`PrivateAttr`) from `__init__` signature in type checkers by [@idan22moral](https://github.com/idan22moral) in [#9293](https://github.com/pydantic/pydantic/pull/9293) +* Make detection of `TypeVar` defaults robust to the CPython `PEP-696` implementation by [@AlexWaygood](https://github.com/AlexWaygood) in [#9426](https://github.com/pydantic/pydantic/pull/9426) +* Fix usage of `PlainSerializer` with builtin types by [@Viicos](https://github.com/Viicos) in [#9450](https://github.com/pydantic/pydantic/pull/9450) +* Add more robust custom validation examples by [@ChrisPappalardo](https://github.com/ChrisPappalardo) in [#9468](https://github.com/pydantic/pydantic/pull/9468) +* Fix ignored `strict` specification for `StringConstraint(strict=False)` by [@vbmendes](https://github.com/vbmendes) in [#9476](https://github.com/pydantic/pydantic/pull/9476) +* Use `Self` where possible by [@Viicos](https://github.com/Viicos) in [#9479](https://github.com/pydantic/pydantic/pull/9479) +* Do not alter `RootModel.model_construct` signature in the `mypy` plugin by [@Viicos](https://github.com/Viicos) in [#9480](https://github.com/pydantic/pydantic/pull/9480) +* Fixed type hint of `validation_context` by [@OhioDschungel6](https://github.com/OhioDschungel6) in [#9508](https://github.com/pydantic/pydantic/pull/9508) +* Support context being passed to TypeAdapter's `dump_json`/`dump_python` by [@alexcouper](https://github.com/alexcouper) in [#9495](https://github.com/pydantic/pydantic/pull/9495) +* Updates type signature for `Field()` constructor by [@bjmc](https://github.com/bjmc) in [#9484](https://github.com/pydantic/pydantic/pull/9484) +* Improve builtin alias generators by [@sydney-runkle](https://github.com/sydney-runkle) in [#9561](https://github.com/pydantic/pydantic/pull/9561) +* Fix typing of `TypeAdapter` by [@Viicos](https://github.com/Viicos) in [#9570](https://github.com/pydantic/pydantic/pull/9570) +* Add fallback default value for private fields in `__setstate__` of BaseModel by [@anhpham1509](https://github.com/anhpham1509) in [#9584](https://github.com/pydantic/pydantic/pull/9584) +* Support `PEP 746` by [@adriangb](https://github.com/adriangb) in [#9587](https://github.com/pydantic/pydantic/pull/9587) +* Allow validator and serializer functions to have default values by [@Viicos](https://github.com/Viicos) in [#9478](https://github.com/pydantic/pydantic/pull/9478) +* Fix bug with mypy plugin's handling of covariant `TypeVar` fields by [@dmontagu](https://github.com/dmontagu) in [#9606](https://github.com/pydantic/pydantic/pull/9606) +* Fix multiple annotation / constraint application logic by [@sydney-runkle](https://github.com/sydney-runkle) in [#9623](https://github.com/pydantic/pydantic/pull/9623) +* Respect `regex` flags in validation and json schema by [@sydney-runkle](https://github.com/sydney-runkle) in [#9591](https://github.com/pydantic/pydantic/pull/9591) +* Fix type hint on `IpvAnyAddress` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9640](https://github.com/pydantic/pydantic/pull/9640) +* Allow a field specifier on `__pydantic_extra__` by [@dmontagu](https://github.com/dmontagu) in [#9659](https://github.com/pydantic/pydantic/pull/9659) +* Use normalized case for file path comparison by [@sydney-runkle](https://github.com/sydney-runkle) in [#9737](https://github.com/pydantic/pydantic/pull/9737) +* Modify constraint application logic to allow field constraints on `Optional[Decimal]` by [@lazyhope](https://github.com/lazyhope) in [#9754](https://github.com/pydantic/pydantic/pull/9754) +* `validate_call` type params fix by [@sydney-runkle](https://github.com/sydney-runkle) in [#9760](https://github.com/pydantic/pydantic/pull/9760) +* Check all warnings returned by pytest.warns() by [@s-t-e-v-e-n-k](https://github.com/s-t-e-v-e-n-k) in [#9702](https://github.com/pydantic/pydantic/pull/9702) +* Reuse `re.Pattern` object in regex patterns to allow for regex flags by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1318](https://github.com/pydantic/pydantic-core/pull/1318) + +### New Contributors + +* [@idan22moral](https://github.com/idan22moral) made their first contribution in [#9294](https://github.com/pydantic/pydantic/pull/9294) +* [@anesmemisevic](https://github.com/anesmemisevic) made their first contribution in [#9303](https://github.com/pydantic/pydantic/pull/9303) +* [@max-muoto](https://github.com/max-muoto) made their first contribution in [#9338](https://github.com/pydantic/pydantic/pull/9338) +* [@amitschang](https://github.com/amitschang) made their first contribution in [#9344](https://github.com/pydantic/pydantic/pull/9344) +* [@paulmartin91](https://github.com/paulmartin91) made their first contribution in [#9410](https://github.com/pydantic/pydantic/pull/9410) +* [@OhioDschungel6](https://github.com/OhioDschungel6) made their first contribution in [#9405](https://github.com/pydantic/pydantic/pull/9405) +* [@AlexWaygood](https://github.com/AlexWaygood) made their first contribution in [#9426](https://github.com/pydantic/pydantic/pull/9426) +* [@kinuax](https://github.com/kinuax) made their first contribution in [#9433](https://github.com/pydantic/pydantic/pull/9433) +* [@antoni-jamiolkowski](https://github.com/antoni-jamiolkowski) made their first contribution in [#9431](https://github.com/pydantic/pydantic/pull/9431) +* [@candleindark](https://github.com/candleindark) made their first contribution in [#9448](https://github.com/pydantic/pydantic/pull/9448) +* [@nix010](https://github.com/nix010) made their first contribution in [#9170](https://github.com/pydantic/pydantic/pull/9170) +* [@tomy0000000](https://github.com/tomy0000000) made their first contribution in [#9457](https://github.com/pydantic/pydantic/pull/9457) +* [@vbmendes](https://github.com/vbmendes) made their first contribution in [#9470](https://github.com/pydantic/pydantic/pull/9470) +* [@micheleAlberto](https://github.com/micheleAlberto) made their first contribution in [#9471](https://github.com/pydantic/pydantic/pull/9471) +* [@ChrisPappalardo](https://github.com/ChrisPappalardo) made their first contribution in [#9468](https://github.com/pydantic/pydantic/pull/9468) +* [@blueTurtz](https://github.com/blueTurtz) made their first contribution in [#9475](https://github.com/pydantic/pydantic/pull/9475) +* [@WinterBlue16](https://github.com/WinterBlue16) made their first contribution in [#9477](https://github.com/pydantic/pydantic/pull/9477) +* [@bittner](https://github.com/bittner) made their first contribution in [#9500](https://github.com/pydantic/pydantic/pull/9500) +* [@alexcouper](https://github.com/alexcouper) made their first contribution in [#9495](https://github.com/pydantic/pydantic/pull/9495) +* [@bjmc](https://github.com/bjmc) made their first contribution in [#9484](https://github.com/pydantic/pydantic/pull/9484) +* [@pjvv](https://github.com/pjvv) made their first contribution in [#9529](https://github.com/pydantic/pydantic/pull/9529) +* [@nedbat](https://github.com/nedbat) made their first contribution in [#9530](https://github.com/pydantic/pydantic/pull/9530) +* [@gunnellEvan](https://github.com/gunnellEvan) made their first contribution in [#9469](https://github.com/pydantic/pydantic/pull/9469) +* [@jaymbans](https://github.com/jaymbans) made their first contribution in [#9531](https://github.com/pydantic/pydantic/pull/9531) +* [@MarcBresson](https://github.com/MarcBresson) made their first contribution in [#9534](https://github.com/pydantic/pydantic/pull/9534) +* [@anhpham1509](https://github.com/anhpham1509) made their first contribution in [#9584](https://github.com/pydantic/pydantic/pull/9584) +* [@K-dash](https://github.com/K-dash) made their first contribution in [#9595](https://github.com/pydantic/pydantic/pull/9595) +* [@s-t-e-v-e-n-k](https://github.com/s-t-e-v-e-n-k) made their first contribution in [#9527](https://github.com/pydantic/pydantic/pull/9527) +* [@airwoodix](https://github.com/airwoodix) made their first contribution in [#9506](https://github.com/pydantic/pydantic/pull/9506) +* [@misrasaurabh1](https://github.com/misrasaurabh1) made their first contribution in [#9653](https://github.com/pydantic/pydantic/pull/9653) +* [@AlessandroMiola](https://github.com/AlessandroMiola) made their first contribution in [#9740](https://github.com/pydantic/pydantic/pull/9740) +* [@mylapallilavanyaa](https://github.com/mylapallilavanyaa) made their first contribution in [#9746](https://github.com/pydantic/pydantic/pull/9746) +* [@lazyhope](https://github.com/lazyhope) made their first contribution in [#9754](https://github.com/pydantic/pydantic/pull/9754) +* [@YassinNouh21](https://github.com/YassinNouh21) made their first contribution in [#9759](https://github.com/pydantic/pydantic/pull/9759) + +## v2.8.0b1 (2024-06-27) + +Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.8.0b1) for details. + +## v2.7.4 (2024-06-12) + +[Github release](https://github.com/pydantic/pydantic/releases/tag/v2.7.4) + +### What's Changed + +#### Packaging + +* Bump `pydantic.v1` to `v1.10.16` reference by [@sydney-runkle](https://github.com/sydney-runkle) in [#9639](https://github.com/pydantic/pydantic/pull/9639) + +#### Fixes + +* Specify `recursive_guard` as kwarg in `FutureRef._evaluate` by [@vfazio](https://github.com/vfazio) in [#9612](https://github.com/pydantic/pydantic/pull/9612) + +## v2.7.3 (2024-06-03) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.3) + +### What's Changed + +#### Packaging + +* Bump `pydantic-core` to `v2.18.4` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9550](https://github.com/pydantic/pydantic/pull/9550) + +#### Fixes + +* Fix u style unicode strings in python [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/jiter#110](https://github.com/pydantic/jiter/pull/110) + +## v2.7.2 (2024-05-28) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.2) + +### What's Changed + +#### Packaging + +* Bump `pydantic-core` to `v2.18.3` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9515](https://github.com/pydantic/pydantic/pull/9515) + +#### Fixes + +* Replace `__spec__.parent` with `__package__` by [@hramezani](https://github.com/hramezani) in [#9331](https://github.com/pydantic/pydantic/pull/9331) +* Fix validation of `int`s with leading unary minus by [@RajatRajdeep](https://github.com/RajatRajdeep) in [pydantic/pydantic-core#1291](https://github.com/pydantic/pydantic-core/pull/1291) +* Fix `str` subclass validation for enums by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1273](https://github.com/pydantic/pydantic-core/pull/1273) +* Support `BigInt`s in `Literal`s and `Enum`s by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1297](https://github.com/pydantic/pydantic-core/pull/1297) +* Fix: uuid - allow `str` subclass as input by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1296](https://github.com/pydantic/pydantic-core/pull/1296) + +## v2.7.1 (2024-04-23) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.1) + +### What's Changed + +#### Packaging + +* Bump `pydantic-core` to `v2.18.2` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9307](https://github.com/pydantic/pydantic/pull/9307) + +#### New Features + +* Ftp and Websocket connection strings support by [@CherrySuryp](https://github.com/CherrySuryp) in [#9205](https://github.com/pydantic/pydantic/pull/9205) + +#### Changes + +* Use field description for RootModel schema description when there is `…` by [@LouisGobert](https://github.com/LouisGobert) in [#9214](https://github.com/pydantic/pydantic/pull/9214) + +#### Fixes + +* Fix `validation_alias` behavior with `model_construct` for `AliasChoices` and `AliasPath` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9223](https://github.com/pydantic/pydantic/pull/9223) +* Revert `typing.Literal` and import it outside the TYPE_CHECKING block by [@frost-nzcr4](https://github.com/frost-nzcr4) in [#9232](https://github.com/pydantic/pydantic/pull/9232) +* Fix `Secret` serialization schema, applicable for unions by [@sydney-runkle](https://github.com/sydney-runkle) in [#9240](https://github.com/pydantic/pydantic/pull/9240) +* Fix `strict` application to `function-after` with `use_enum_values` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9279](https://github.com/pydantic/pydantic/pull/9279) +* Address case where `model_construct` on a class which defines `model_post_init` fails with `AttributeError` by [@babygrimes](https://github.com/babygrimes) in [#9168](https://github.com/pydantic/pydantic/pull/9168) +* Fix `model_json_schema` with config types by [@NeevCohen](https://github.com/NeevCohen) in [#9287](https://github.com/pydantic/pydantic/pull/9287) +* Support multiple zeros as an `int` by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1269](https://github.com/pydantic/pydantic-core/pull/1269) +* Fix validation of `int`s with leading unary plus by [@cknv](https://github.com/cknv) in [pydantic/pydantic-core#1272](https://github.com/pydantic/pydantic-core/pull/1272) +* Fix interaction between `extra != 'ignore'` and `from_attributes=True` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1276](https://github.com/pydantic/pydantic-core/pull/1276) +* Handle error from `Enum`'s `missing` function as `ValidationError` by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1274](https://github.com/pydantic/pydantic-core/pull/1754) +* Fix memory leak with `Iterable` validation by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1271](https://github.com/pydantic/pydantic-core/pull/1751) + +### New Contributors + +* [@zzstoatzz](https://github.com/zzstoatzz) made their first contribution in [#9219](https://github.com/pydantic/pydantic/pull/9219) +* [@frost-nzcr4](https://github.com/frost-nzcr4) made their first contribution in [#9232](https://github.com/pydantic/pydantic/pull/9232) +* [@CherrySuryp](https://github.com/CherrySuryp) made their first contribution in [#9205](https://github.com/pydantic/pydantic/pull/9205) +* [@vagenas](https://github.com/vagenas) made their first contribution in [#9268](https://github.com/pydantic/pydantic/pull/9268) +* [@ollz272](https://github.com/ollz272) made their first contribution in [#9262](https://github.com/pydantic/pydantic/pull/9262) +* [@babygrimes](https://github.com/babygrimes) made their first contribution in [#9168](https://github.com/pydantic/pydantic/pull/9168) +* [@swelborn](https://github.com/swelborn) made their first contribution in [#9296](https://github.com/pydantic/pydantic/pull/9296) +* [@kf-novi](https://github.com/kf-novi) made their first contribution in [#9236](https://github.com/pydantic/pydantic/pull/9236) +* [@lgeiger](https://github.com/lgeiger) made their first contribution in [#9288](https://github.com/pydantic/pydantic/pull/9288) + +## v2.7.0 (2024-04-11) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.0) + +The code released in v2.7.0 is practically identical to that of v2.7.0b1. + +### What's Changed + +#### Packaging + +* Reorganize `pyproject.toml` sections by [@Viicos](https://github.com/Viicos) in [#8899](https://github.com/pydantic/pydantic/pull/8899) +* Bump `pydantic-core` to `v2.18.1` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9211](https://github.com/pydantic/pydantic/pull/9211) +* Adopt `jiter` `v0.2.0` by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1250](https://github.com/pydantic/pydantic-core/pull/1250) + +#### New Features + +* Extract attribute docstrings from `FieldInfo.description` by [@Viicos](https://github.com/Viicos) in [#6563](https://github.com/pydantic/pydantic/pull/6563) +* Add a `with_config` decorator to comply with typing spec by [@Viicos](https://github.com/Viicos) in [#8611](https://github.com/pydantic/pydantic/pull/8611) +* Allow an optional separator splitting the value and unit of the result of `ByteSize.human_readable` by [@jks15satoshi](https://github.com/jks15satoshi) in [#8706](https://github.com/pydantic/pydantic/pull/8706) +* Add generic `Secret` base type by [@conradogarciaberrotaran](https://github.com/conradogarciaberrotaran) in [#8519](https://github.com/pydantic/pydantic/pull/8519) +* Make use of `Sphinx` inventories for cross references in docs by [@Viicos](https://github.com/Viicos) in [#8682](https://github.com/pydantic/pydantic/pull/8682) +* Add environment variable to disable plugins by [@geospackle](https://github.com/geospackle) in [#8767](https://github.com/pydantic/pydantic/pull/8767) +* Add support for `deprecated` fields by [@Viicos](https://github.com/Viicos) in [#8237](https://github.com/pydantic/pydantic/pull/8237) +* Allow `field_serializer('*')` by [@ornariece](https://github.com/ornariece) in [#9001](https://github.com/pydantic/pydantic/pull/9001) +* Handle a case when `model_config` is defined as a model property by [@alexeyt101](https://github.com/alexeyt101) in [#9004](https://github.com/pydantic/pydantic/pull/9004) +* Update `create_model()` to support `typing.Annotated` as input by [@wannieman98](https://github.com/wannieman98) in [#8947](https://github.com/pydantic/pydantic/pull/8947) +* Add `ClickhouseDsn` support by [@solidguy7](https://github.com/solidguy7) in [#9062](https://github.com/pydantic/pydantic/pull/9062) +* Add support for `re.Pattern[str]` to `pattern` field by [@jag-k](https://github.com/jag-k) in [#9053](https://github.com/pydantic/pydantic/pull/9053) +* Support for `serialize_as_any` runtime setting by [@sydney-runkle](https://github.com/sydney-runkle) in [#8830](https://github.com/pydantic/pydantic/pull/8830) +* Add support for `typing.Self` by [@Youssefares](https://github.com/Youssefares) in [#9023](https://github.com/pydantic/pydantic/pull/9023) +* Ability to pass `context` to serialization by [@ornariece](https://github.com/ornariece) in [#8965](https://github.com/pydantic/pydantic/pull/8965) +* Add feedback widget to docs with flarelytics integration by [@sydney-runkle](https://github.com/sydney-runkle) in [#9129](https://github.com/pydantic/pydantic/pull/9129) +* Support for parsing partial JSON strings in Python by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/jiter#66](https://github.com/pydantic/jiter/pull/66) + +**Finalized in v2.7.0, rather than v2.7.0b1:** +* Add support for field level number to str coercion option by [@NeevCohen](https://github.com/NeevCohen) in [#9137](https://github.com/pydantic/pydantic/pull/9137) +* Update `warnings` parameter for serialization utilities to allow raising a warning by [@Lance-Drane](https://github.com/Lance-Drane) in [#9166](https://github.com/pydantic/pydantic/pull/9166) + +#### Changes + +* Correct docs, logic for `model_construct` behavior with `extra` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8807](https://github.com/pydantic/pydantic/pull/8807) +* Improve error message for improper `RootModel` subclasses by [@sydney-runkle](https://github.com/sydney-runkle) in [#8857](https://github.com/pydantic/pydantic/pull/8857) +* Use `PEP570` syntax by [@Viicos](https://github.com/Viicos) in [#8940](https://github.com/pydantic/pydantic/pull/8940) +* Add `enum` and `type` to the JSON schema for single item literals by [@dmontagu](https://github.com/dmontagu) in [#8944](https://github.com/pydantic/pydantic/pull/8944) +* Deprecate `update_json_schema` internal function by [@sydney-runkle](https://github.com/sydney-runkle) in [#9125](https://github.com/pydantic/pydantic/pull/9125) +* Serialize duration to hour minute second, instead of just seconds by [@kakilangit](https://github.com/kakilangit) in [pydantic/speedate#50](https://github.com/pydantic/speedate/pull/50) +* Trimming str before parsing to int and float by [@hungtsetse](https://github.com/hungtsetse) in [pydantic/pydantic-core#1203](https://github.com/pydantic/pydantic-core/pull/1203) + +#### Performance + +* `enum` validator improvements by [@samuelcolvin](https://github.com/samuelcolvin) in [#9045](https://github.com/pydantic/pydantic/pull/9045) +* Move `enum` validation and serialization to Rust by [@samuelcolvin](https://github.com/samuelcolvin) in [#9064](https://github.com/pydantic/pydantic/pull/9064) +* Improve schema generation for nested dataclasses by [@sydney-runkle](https://github.com/sydney-runkle) in [#9114](https://github.com/pydantic/pydantic/pull/9114) +* Fast path for ASCII python string creation in JSON by [@samuelcolvin](https://github.com/samuelcolvin) in in [pydantic/jiter#72](https://github.com/pydantic/jiter/pull/72) +* SIMD integer and string JSON parsing on `aarch64`(**Note:** SIMD on x86 will be implemented in a future release) by [@samuelcolvin](https://github.com/samuelcolvin) in in [pydantic/jiter#65](https://github.com/pydantic/jiter/pull/65) +* Support JSON `Cow` from `jiter` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1231](https://github.com/pydantic/pydantic-core/pull/1231) +* MAJOR performance improvement: update to PyO3 0.21 final by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1248](https://github.com/pydantic/pydantic-core/pull/1248) +* cache Python strings by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1240](https://github.com/pydantic/pydantic-core/pull/1240) + +#### Fixes + +* Fix strict parsing for some `Sequence`s by [@sydney-runkle](https://github.com/sydney-runkle) in [#8614](https://github.com/pydantic/pydantic/pull/8614) +* Add a check on the existence of `__qualname__` by [@anci3ntr0ck](https://github.com/anci3ntr0ck) in [#8642](https://github.com/pydantic/pydantic/pull/8642) +* Handle `__pydantic_extra__` annotation being a string or inherited by [@alexmojaki](https://github.com/alexmojaki) in [#8659](https://github.com/pydantic/pydantic/pull/8659) +* Fix json validation for `NameEmail` by [@Holi0317](https://github.com/Holi0317) in [#8650](https://github.com/pydantic/pydantic/pull/8650) +* Fix type-safety of attribute access in `BaseModel` by [@bluenote10](https://github.com/bluenote10) in [#8651](https://github.com/pydantic/pydantic/pull/8651) +* Fix bug with `mypy` plugin and `no_strict_optional = True` by [@dmontagu](https://github.com/dmontagu) in [#8666](https://github.com/pydantic/pydantic/pull/8666) +* Fix `ByteSize` error `type` change by [@sydney-runkle](https://github.com/sydney-runkle) in [#8681](https://github.com/pydantic/pydantic/pull/8681) +* Fix inheriting annotations in dataclasses by [@sydney-runkle](https://github.com/sydney-runkle) in [#8679](https://github.com/pydantic/pydantic/pull/8679) +* Fix regression in core schema generation for indirect definition references by [@dmontagu](https://github.com/dmontagu) in [#8702](https://github.com/pydantic/pydantic/pull/8702) +* Fix unsupported types bug with plain validator by [@sydney-runkle](https://github.com/sydney-runkle) in [#8710](https://github.com/pydantic/pydantic/pull/8710) +* Reverting problematic fix from 2.6 release, fixing schema building bug by [@sydney-runkle](https://github.com/sydney-runkle) in [#8718](https://github.com/pydantic/pydantic/pull/8718) +* fixes `__pydantic_config__` ignored for TypeDict by [@13sin](https://github.com/13sin) in [#8734](https://github.com/pydantic/pydantic/pull/8734) +* Fix test failures with `pytest v8.0.0` due to `pytest.warns()` starting to work inside `pytest.raises()` by [@mgorny](https://github.com/mgorny) in [#8678](https://github.com/pydantic/pydantic/pull/8678) +* Use `is_valid_field` from 1.x for `mypy` plugin by [@DanielNoord](https://github.com/DanielNoord) in [#8738](https://github.com/pydantic/pydantic/pull/8738) +* Better-support `mypy` strict equality flag by [@dmontagu](https://github.com/dmontagu) in [#8799](https://github.com/pydantic/pydantic/pull/8799) +* model_json_schema export with Annotated types misses 'required' parameters by [@LouisGobert](https://github.com/LouisGobert) in [#8793](https://github.com/pydantic/pydantic/pull/8793) +* Fix default inclusion in `FieldInfo.__repr_args__` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8801](https://github.com/pydantic/pydantic/pull/8801) +* Fix resolution of forward refs in dataclass base classes that are not present in the subclass module namespace by [@matsjoyce-refeyn](https://github.com/matsjoyce-refeyn) in [#8751](https://github.com/pydantic/pydantic/pull/8751) +* Fix `BaseModel` type annotations to be resolvable by `typing.get_type_hints` by [@devmonkey22](https://github.com/devmonkey22) in [#7680](https://github.com/pydantic/pydantic/pull/7680) +* Fix: allow empty string aliases with `AliasGenerator` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8810](https://github.com/pydantic/pydantic/pull/8810) +* Fix test along with `date` -> `datetime` timezone assumption fix by [@sydney-runkle](https://github.com/sydney-runkle) in [#8823](https://github.com/pydantic/pydantic/pull/8823) +* Fix deprecation warning with usage of `ast.Str` by [@Viicos](https://github.com/Viicos) in [#8837](https://github.com/pydantic/pydantic/pull/8837) +* Add missing `deprecated` decorators by [@Viicos](https://github.com/Viicos) in [#8877](https://github.com/pydantic/pydantic/pull/8877) +* Fix serialization of `NameEmail` if name includes an email address by [@NeevCohen](https://github.com/NeevCohen) in [#8860](https://github.com/pydantic/pydantic/pull/8860) +* Add information about class in error message of schema generation by [@Czaki](https://github.com/Czaki) in [#8917](https://github.com/pydantic/pydantic/pull/8917) +* Make `TypeAdapter`'s typing compatible with special forms by [@adriangb](https://github.com/adriangb) in [#8923](https://github.com/pydantic/pydantic/pull/8923) +* Fix issue with config behavior being baked into the ref schema for `enum`s by [@dmontagu](https://github.com/dmontagu) in [#8920](https://github.com/pydantic/pydantic/pull/8920) +* More helpful error re wrong `model_json_schema` usage by [@sydney-runkle](https://github.com/sydney-runkle) in [#8928](https://github.com/pydantic/pydantic/pull/8928) +* Fix nested discriminated union schema gen, pt 2 by [@sydney-runkle](https://github.com/sydney-runkle) in [#8932](https://github.com/pydantic/pydantic/pull/8932) +* Fix schema build for nested dataclasses / TypedDicts with discriminators by [@sydney-runkle](https://github.com/sydney-runkle) in [#8950](https://github.com/pydantic/pydantic/pull/8950) +* Remove unnecessary logic for definitions schema gen with discriminated unions by [@sydney-runkle](https://github.com/sydney-runkle) in [#8951](https://github.com/pydantic/pydantic/pull/8951) +* Fix handling of optionals in `mypy` plugin by [@dmontagu](https://github.com/dmontagu) in [#9008](https://github.com/pydantic/pydantic/pull/9008) +* Fix `PlainSerializer` usage with std type constructor by [@sydney-runkle](https://github.com/sydney-runkle) in [#9031](https://github.com/pydantic/pydantic/pull/9031) +* Remove unnecessary warning for config in plugin by [@dmontagu](https://github.com/dmontagu) in [#9039](https://github.com/pydantic/pydantic/pull/9039) +* Fix default value serializing by [@NeevCohen](https://github.com/NeevCohen) in [#9066](https://github.com/pydantic/pydantic/pull/9066) +* Fix extra fields check in `Model.__getattr__()` by [@NeevCohen](https://github.com/NeevCohen) in [#9082](https://github.com/pydantic/pydantic/pull/9082) +* Fix `ClassVar` forward ref inherited from parent class by [@alexmojaki](https://github.com/alexmojaki) in [#9097](https://github.com/pydantic/pydantic/pull/9097) +* fix sequence like validator with strict `True` by [@andresliszt](https://github.com/andresliszt) in [#8977](https://github.com/pydantic/pydantic/pull/8977) +* Improve warning message when a field name shadows a field in a parent model by [@chan-vince](https://github.com/chan-vince) in [#9105](https://github.com/pydantic/pydantic/pull/9105) +* Do not warn about shadowed fields if they are not redefined in a child class by [@chan-vince](https://github.com/chan-vince) in [#9111](https://github.com/pydantic/pydantic/pull/9111) +* Fix discriminated union bug with unsubstituted type var by [@sydney-runkle](https://github.com/sydney-runkle) in [#9124](https://github.com/pydantic/pydantic/pull/9124) +* Support serialization of `deque` when passed to `Sequence[blah blah blah]` by [@sydney-runkle](https://github.com/sydney-runkle) in [#9128](https://github.com/pydantic/pydantic/pull/9128) +* Init private attributes from super-types in `model_post_init` by [@Viicos](https://github.com/Viicos) in [#9134](https://github.com/pydantic/pydantic/pull/9134) +* fix `model_construct` with `validation_alias` by [@ornariece](https://github.com/ornariece) in [#9144](https://github.com/pydantic/pydantic/pull/9144) +* Ensure json-schema generator handles `Literal` `null` types by [@bruno-f-cruz](https://github.com/bruno-f-cruz) in [#9135](https://github.com/pydantic/pydantic/pull/9135) +* **Fixed in v2.7.0**: Fix allow extra generic by [@dmontagu](https://github.com/dmontagu) in [#9193](https://github.com/pydantic/pydantic/pull/9193) + +### New Contributors + +* [@hungtsetse](https://github.com/hungtsetse) made their first contribution in [#8546](https://github.com/pydantic/pydantic/pull/8546) +* [@StrawHatDrag0n](https://github.com/StrawHatDrag0n) made their first contribution in [#8583](https://github.com/pydantic/pydantic/pull/8583) +* [@anci3ntr0ck](https://github.com/anci3ntr0ck) made their first contribution in [#8642](https://github.com/pydantic/pydantic/pull/8642) +* [@Holi0317](https://github.com/Holi0317) made their first contribution in [#8650](https://github.com/pydantic/pydantic/pull/8650) +* [@bluenote10](https://github.com/bluenote10) made their first contribution in [#8651](https://github.com/pydantic/pydantic/pull/8651) +* [@ADSteele916](https://github.com/ADSteele916) made their first contribution in [#8703](https://github.com/pydantic/pydantic/pull/8703) +* [@musicinmybrain](https://github.com/musicinmybrain) made their first contribution in [#8731](https://github.com/pydantic/pydantic/pull/8731) +* [@jks15satoshi](https://github.com/jks15satoshi) made their first contribution in [#8706](https://github.com/pydantic/pydantic/pull/8706) +* [@13sin](https://github.com/13sin) made their first contribution in [#8734](https://github.com/pydantic/pydantic/pull/8734) +* [@DanielNoord](https://github.com/DanielNoord) made their first contribution in [#8738](https://github.com/pydantic/pydantic/pull/8738) +* [@conradogarciaberrotaran](https://github.com/conradogarciaberrotaran) made their first contribution in [#8519](https://github.com/pydantic/pydantic/pull/8519) +* [@chris-griffin](https://github.com/chris-griffin) made their first contribution in [#8775](https://github.com/pydantic/pydantic/pull/8775) +* [@LouisGobert](https://github.com/LouisGobert) made their first contribution in [#8793](https://github.com/pydantic/pydantic/pull/8793) +* [@matsjoyce-refeyn](https://github.com/matsjoyce-refeyn) made their first contribution in [#8751](https://github.com/pydantic/pydantic/pull/8751) +* [@devmonkey22](https://github.com/devmonkey22) made their first contribution in [#7680](https://github.com/pydantic/pydantic/pull/7680) +* [@adamency](https://github.com/adamency) made their first contribution in [#8847](https://github.com/pydantic/pydantic/pull/8847) +* [@MamfTheKramf](https://github.com/MamfTheKramf) made their first contribution in [#8851](https://github.com/pydantic/pydantic/pull/8851) +* [@ornariece](https://github.com/ornariece) made their first contribution in [#9001](https://github.com/pydantic/pydantic/pull/9001) +* [@alexeyt101](https://github.com/alexeyt101) made their first contribution in [#9004](https://github.com/pydantic/pydantic/pull/9004) +* [@wannieman98](https://github.com/wannieman98) made their first contribution in [#8947](https://github.com/pydantic/pydantic/pull/8947) +* [@solidguy7](https://github.com/solidguy7) made their first contribution in [#9062](https://github.com/pydantic/pydantic/pull/9062) +* [@kloczek](https://github.com/kloczek) made their first contribution in [#9047](https://github.com/pydantic/pydantic/pull/9047) +* [@jag-k](https://github.com/jag-k) made their first contribution in [#9053](https://github.com/pydantic/pydantic/pull/9053) +* [@priya-gitTest](https://github.com/priya-gitTest) made their first contribution in [#9088](https://github.com/pydantic/pydantic/pull/9088) +* [@Youssefares](https://github.com/Youssefares) made their first contribution in [#9023](https://github.com/pydantic/pydantic/pull/9023) +* [@chan-vince](https://github.com/chan-vince) made their first contribution in [#9105](https://github.com/pydantic/pydantic/pull/9105) +* [@bruno-f-cruz](https://github.com/bruno-f-cruz) made their first contribution in [#9135](https://github.com/pydantic/pydantic/pull/9135) +* [@Lance-Drane](https://github.com/Lance-Drane) made their first contribution in [#9166](https://github.com/pydantic/pydantic/pull/9166) + +## v2.7.0b1 (2024-04-03) + +Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.7.0b1) for details. + +## v2.6.4 (2024-03-12) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.4) + +### What's Changed + +#### Fixes + +* Fix usage of `AliasGenerator` with `computed_field` decorator by [@sydney-runkle](https://github.com/sydney-runkle) in [#8806](https://github.com/pydantic/pydantic/pull/8806) +* Fix nested discriminated union schema gen, pt 2 by [@sydney-runkle](https://github.com/sydney-runkle) in [#8932](https://github.com/pydantic/pydantic/pull/8932) +* Fix bug with no_strict_optional=True caused by API deferral by [@dmontagu](https://github.com/dmontagu) in [#8826](https://github.com/pydantic/pydantic/pull/8826) + + +## v2.6.3 (2024-02-27) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.3) + +### What's Changed + +#### Packaging + +* Update `pydantic-settings` version in the docs by [@hramezani](https://github.com/hramezani) in [#8906](https://github.com/pydantic/pydantic/pull/8906) + +#### Fixes + +* Fix discriminated union schema gen bug by [@sydney-runkle](https://github.com/sydney-runkle) in [#8904](https://github.com/pydantic/pydantic/pull/8904) + + +## v2.6.2 (2024-02-23) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.2) + +### What's Changed + +#### Packaging + +* Upgrade to `pydantic-core` 2.16.3 by [@sydney-runkle](https://github.com/sydney-runkle) in [#8879](https://github.com/pydantic/pydantic/pull/8879) + +#### Fixes + +* 'YYYY-MM-DD' date string coerced to datetime shouldn't infer timezone by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1193](https://github.com/pydantic/pydantic-core/pull/1193) + + +## v2.6.1 (2024-02-05) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.1) + +### What's Changed + +#### Packaging + +* Upgrade to `pydantic-core` 2.16.2 by [@sydney-runkle](https://github.com/sydney-runkle) in [#8717](https://github.com/pydantic/pydantic/pull/8717) + +#### Fixes + +* Fix bug with `mypy` plugin and `no_strict_optional = True` by [@dmontagu](https://github.com/dmontagu) in [#8666](https://github.com/pydantic/pydantic/pull/8666) +* Fix `ByteSize` error `type` change by [@sydney-runkle](https://github.com/sydney-runkle) in [#8681](https://github.com/pydantic/pydantic/pull/8681) +* Fix inheriting `Field` annotations in dataclasses by [@sydney-runkle](https://github.com/sydney-runkle) in [#8679](https://github.com/pydantic/pydantic/pull/8679) +* Fix regression in core schema generation for indirect definition references by [@dmontagu](https://github.com/dmontagu) in [#8702](https://github.com/pydantic/pydantic/pull/8702) +* Fix unsupported types bug with `PlainValidator` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8710](https://github.com/pydantic/pydantic/pull/8710) +* Reverting problematic fix from 2.6 release, fixing schema building bug by [@sydney-runkle](https://github.com/sydney-runkle) in [#8718](https://github.com/pydantic/pydantic/pull/8718) +* Fix warning for tuple of wrong size in `Union` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1174](https://github.com/pydantic/pydantic-core/pull/1174) +* Fix `computed_field` JSON serializer `exclude_none` behavior by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1187](https://github.com/pydantic/pydantic-core/pull/1187) + + +## v2.6.0 (2024-01-23) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.0) + +The code released in v2.6.0 is practically identical to that of v2.6.0b1. + +### What's Changed + +#### Packaging + +* Check for `email-validator` version >= 2.0 by [@commonism](https://github.com/commonism) in [#6033](https://github.com/pydantic/pydantic/pull/6033) +* Upgrade `ruff`` target version to Python 3.8 by [@Elkiwa](https://github.com/Elkiwa) in [#8341](https://github.com/pydantic/pydantic/pull/8341) +* Update to `pydantic-extra-types==2.4.1` by [@yezz123](https://github.com/yezz123) in [#8478](https://github.com/pydantic/pydantic/pull/8478) +* Update to `pyright==1.1.345` by [@Viicos](https://github.com/Viicos) in [#8453](https://github.com/pydantic/pydantic/pull/8453) +* Update pydantic-core from 2.14.6 to 2.16.1, significant changes from these updates are described below, full changelog [here](https://github.com/pydantic/pydantic-core/compare/v2.14.6...v2.16.1) + +#### New Features + +* Add `NatsDsn` by [@ekeew](https://github.com/ekeew) in [#6874](https://github.com/pydantic/pydantic/pull/6874) +* Add `ConfigDict.ser_json_inf_nan` by [@davidhewitt](https://github.com/davidhewitt) in [#8159](https://github.com/pydantic/pydantic/pull/8159) +* Add `types.OnErrorOmit` by [@adriangb](https://github.com/adriangb) in [#8222](https://github.com/pydantic/pydantic/pull/8222) +* Support `AliasGenerator` usage by [@sydney-runkle](https://github.com/sydney-runkle) in [#8282](https://github.com/pydantic/pydantic/pull/8282) +* Add Pydantic People Page to docs by [@sydney-runkle](https://github.com/sydney-runkle) in [#8345](https://github.com/pydantic/pydantic/pull/8345) +* Support `yyyy-MM-DD` datetime parsing by [@sydney-runkle](https://github.com/sydney-runkle) in [#8404](https://github.com/pydantic/pydantic/pull/8404) +* Added bits conversions to the `ByteSize` class [#8415](https://github.com/pydantic/pydantic/issues/8415) by [@luca-matei](https://github.com/luca-matei) in [#8507](https://github.com/pydantic/pydantic/pull/8507) +* Enable json schema creation with type `ByteSize` by [@geospackle](https://github.com/geospackle) in [#8537](https://github.com/pydantic/pydantic/pull/8537) +* Add `eval_type_backport` to handle union operator and builtin generic subscripting in older Pythons by [@alexmojaki](https://github.com/alexmojaki) in [#8209](https://github.com/pydantic/pydantic/pull/8209) +* Add support for `dataclass` fields `init` by [@dmontagu](https://github.com/dmontagu) in [#8552](https://github.com/pydantic/pydantic/pull/8552) +* Implement pickling for `ValidationError` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1119](https://github.com/pydantic/pydantic-core/pull/1119) +* Add unified tuple validator that can handle "variadic" tuples via PEP-646 by [@dmontagu](https://github.com/dmontagu) in [pydantic/pydantic-core#865](https://github.com/pydantic/pydantic-core/pull/865) + +#### Changes + +* Drop Python3.7 support by [@hramezani](https://github.com/hramezani) in [#7188](https://github.com/pydantic/pydantic/pull/7188) +* Drop Python 3.7, and PyPy 3.7 and 3.8 by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1129](https://github.com/pydantic/pydantic-core/pull/1129) +* Use positional-only `self` in `BaseModel` constructor, so no field name can ever conflict with it by [@ariebovenberg](https://github.com/ariebovenberg) in [#8072](https://github.com/pydantic/pydantic/pull/8072) +* Make `@validate_call` return a function instead of a custom descriptor - fixes binding issue with inheritance and adds `self/cls` argument to validation errors by [@alexmojaki](https://github.com/alexmojaki) in [#8268](https://github.com/pydantic/pydantic/pull/8268) +* Exclude `BaseModel` docstring from JSON schema description by [@sydney-runkle](https://github.com/sydney-runkle) in [#8352](https://github.com/pydantic/pydantic/pull/8352) +* Introducing `classproperty` decorator for `model_computed_fields` by [@Jocelyn-Gas](https://github.com/Jocelyn-Gas) in [#8437](https://github.com/pydantic/pydantic/pull/8437) +* Explicitly raise an error if field names clashes with types by [@Viicos](https://github.com/Viicos) in [#8243](https://github.com/pydantic/pydantic/pull/8243) +* Use stricter serializer for unions of simple types by [@alexdrydew](https://github.com/alexdrydew) [pydantic/pydantic-core#1132](https://github.com/pydantic/pydantic-core/pull/1132) + +#### Performance + +* Add Codspeed profiling Actions workflow by [@lambertsbennett](https://github.com/lambertsbennett) in [#8054](https://github.com/pydantic/pydantic/pull/8054) +* Improve `int` extraction by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1155](https://github.com/pydantic/pydantic-core/pull/1155) +* Improve performance of recursion guard by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1156](https://github.com/pydantic/pydantic-core/pull/1156) +* `dataclass` serialization speedups by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1162](https://github.com/pydantic/pydantic-core/pull/1162) +* Avoid `HashMap` creation when looking up small JSON objects in `LazyIndexMaps` by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/jiter#55](https://github.com/pydantic/jiter/pull/55) +* use hashbrown to speedup python string caching by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/jiter#51](https://github.com/pydantic/jiter/pull/51) +* Replace `Peak` with more efficient `Peek` by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/jiter#48](https://github.com/pydantic/jiter/pull/48) + +#### Fixes + +* Move `getattr` warning in deprecated `BaseConfig` by [@tlambert03](https://github.com/tlambert03) in [#7183](https://github.com/pydantic/pydantic/pull/7183) +* Only hash `model_fields`, not whole `__dict__` by [@alexmojaki](https://github.com/alexmojaki) in [#7786](https://github.com/pydantic/pydantic/pull/7786) +* Fix mishandling of unions while freezing types in the `mypy` plugin by [@dmontagu](https://github.com/dmontagu) in [#7411](https://github.com/pydantic/pydantic/pull/7411) +* Fix `mypy` error on untyped `ClassVar` by [@vincent-hachin-wmx](https://github.com/vincent-hachin-wmx) in [#8138](https://github.com/pydantic/pydantic/pull/8138) +* Only compare pydantic fields in `BaseModel.__eq__` instead of whole `__dict__` by [@QuentinSoubeyranAqemia](https://github.com/QuentinSoubeyranAqemia) in [#7825](https://github.com/pydantic/pydantic/pull/7825) +* Update `strict` docstring in `model_validate` method. by [@LukeTonin](https://github.com/LukeTonin) in [#8223](https://github.com/pydantic/pydantic/pull/8223) +* Fix overload position of `computed_field` by [@Viicos](https://github.com/Viicos) in [#8227](https://github.com/pydantic/pydantic/pull/8227) +* Fix custom type type casting used in multiple attributes by [@ianhfc](https://github.com/ianhfc) in [#8066](https://github.com/pydantic/pydantic/pull/8066) +* Fix issue not allowing `validate_call` decorator to be dynamically assigned to a class method by [@jusexton](https://github.com/jusexton) in [#8249](https://github.com/pydantic/pydantic/pull/8249) +* Fix issue `unittest.mock` deprecation warnings by [@ibleedicare](https://github.com/ibleedicare) in [#8262](https://github.com/pydantic/pydantic/pull/8262) +* Added tests for the case `JsonValue` contains subclassed primitive values by [@jusexton](https://github.com/jusexton) in [#8286](https://github.com/pydantic/pydantic/pull/8286) +* Fix `mypy` error on free before validator (classmethod) by [@sydney-runkle](https://github.com/sydney-runkle) in [#8285](https://github.com/pydantic/pydantic/pull/8285) +* Fix `to_snake` conversion by [@jevins09](https://github.com/jevins09) in [#8316](https://github.com/pydantic/pydantic/pull/8316) +* Fix type annotation of `ModelMetaclass.__prepare__` by [@slanzmich](https://github.com/slanzmich) in [#8305](https://github.com/pydantic/pydantic/pull/8305) +* Disallow `config` specification when initializing a `TypeAdapter` when the annotated type has config already by [@sydney-runkle](https://github.com/sydney-runkle) in [#8365](https://github.com/pydantic/pydantic/pull/8365) +* Fix a naming issue with JSON schema for generics parametrized by recursive type aliases by [@dmontagu](https://github.com/dmontagu) in [#8389](https://github.com/pydantic/pydantic/pull/8389) +* Fix type annotation in pydantic people script by [@shenxiangzhuang](https://github.com/shenxiangzhuang) in [#8402](https://github.com/pydantic/pydantic/pull/8402) +* Add support for field `alias` in `dataclass` signature by [@NeevCohen](https://github.com/NeevCohen) in [#8387](https://github.com/pydantic/pydantic/pull/8387) +* Fix bug with schema generation with `Field(...)` in a forward ref by [@dmontagu](https://github.com/dmontagu) in [#8494](https://github.com/pydantic/pydantic/pull/8494) +* Fix ordering of keys in `__dict__` with `model_construct` call by [@sydney-runkle](https://github.com/sydney-runkle) in [#8500](https://github.com/pydantic/pydantic/pull/8500) +* Fix module `path_type` creation when globals does not contain `__name__` by [@hramezani](https://github.com/hramezani) in [#8470](https://github.com/pydantic/pydantic/pull/8470) +* Fix for namespace issue with dataclasses with `from __future__ import annotations` by [@sydney-runkle](https://github.com/sydney-runkle) in [#8513](https://github.com/pydantic/pydantic/pull/8513) +* Fix: make function validator types positional-only by [@pmmmwh](https://github.com/pmmmwh) in [#8479](https://github.com/pydantic/pydantic/pull/8479) +* Fix usage of `@deprecated` by [@Viicos](https://github.com/Viicos) in [#8294](https://github.com/pydantic/pydantic/pull/8294) +* Add more support for private attributes in `model_construct` call by [@sydney-runkle](https://github.com/sydney-runkle) in [#8525](https://github.com/pydantic/pydantic/pull/8525) +* Use a stack for the types namespace by [@dmontagu](https://github.com/dmontagu) in [#8378](https://github.com/pydantic/pydantic/pull/8378) +* Fix schema-building bug with `TypeAliasType` for types with refs by [@dmontagu](https://github.com/dmontagu) in [#8526](https://github.com/pydantic/pydantic/pull/8526) +* Support `pydantic.Field(repr=False)` in dataclasses by [@tigeryy2](https://github.com/tigeryy2) in [#8511](https://github.com/pydantic/pydantic/pull/8511) +* Override `dataclass_transform` behavior for `RootModel` by [@Viicos](https://github.com/Viicos) in [#8163](https://github.com/pydantic/pydantic/pull/8163) +* Refactor signature generation for simplicity by [@sydney-runkle](https://github.com/sydney-runkle) in [#8572](https://github.com/pydantic/pydantic/pull/8572) +* Fix ordering bug of PlainValidator annotation by [@Anvil](https://github.com/Anvil) in [#8567](https://github.com/pydantic/pydantic/pull/8567) +* Fix `exclude_none` for json serialization of `computed_field`s by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1098](https://github.com/pydantic/pydantic-core/pull/1098) +* Support yyyy-MM-DD string for datetimes by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1124](https://github.com/pydantic/pydantic-core/pull/1124) +* Tweak ordering of definitions in generated schemas by [@StrawHatDrag0n](https://github.com/StrawHatDrag0n) in [#8583](https://github.com/pydantic/pydantic/pull/8583) + + +### New Contributors + +#### `pydantic` +* [@ekeew](https://github.com/ekeew) made their first contribution in [#6874](https://github.com/pydantic/pydantic/pull/6874) +* [@lambertsbennett](https://github.com/lambertsbennett) made their first contribution in [#8054](https://github.com/pydantic/pydantic/pull/8054) +* [@vincent-hachin-wmx](https://github.com/vincent-hachin-wmx) made their first contribution in [#8138](https://github.com/pydantic/pydantic/pull/8138) +* [@QuentinSoubeyranAqemia](https://github.com/QuentinSoubeyranAqemia) made their first contribution in [#7825](https://github.com/pydantic/pydantic/pull/7825) +* [@ariebovenberg](https://github.com/ariebovenberg) made their first contribution in [#8072](https://github.com/pydantic/pydantic/pull/8072) +* [@LukeTonin](https://github.com/LukeTonin) made their first contribution in [#8223](https://github.com/pydantic/pydantic/pull/8223) +* [@denisart](https://github.com/denisart) made their first contribution in [#8231](https://github.com/pydantic/pydantic/pull/8231) +* [@ianhfc](https://github.com/ianhfc) made their first contribution in [#8066](https://github.com/pydantic/pydantic/pull/8066) +* [@eonu](https://github.com/eonu) made their first contribution in [#8255](https://github.com/pydantic/pydantic/pull/8255) +* [@amandahla](https://github.com/amandahla) made their first contribution in [#8263](https://github.com/pydantic/pydantic/pull/8263) +* [@ibleedicare](https://github.com/ibleedicare) made their first contribution in [#8262](https://github.com/pydantic/pydantic/pull/8262) +* [@jevins09](https://github.com/jevins09) made their first contribution in [#8316](https://github.com/pydantic/pydantic/pull/8316) +* [@cuu508](https://github.com/cuu508) made their first contribution in [#8322](https://github.com/pydantic/pydantic/pull/8322) +* [@slanzmich](https://github.com/slanzmich) made their first contribution in [#8305](https://github.com/pydantic/pydantic/pull/8305) +* [@jensenbox](https://github.com/jensenbox) made their first contribution in [#8331](https://github.com/pydantic/pydantic/pull/8331) +* [@szepeviktor](https://github.com/szepeviktor) made their first contribution in [#8356](https://github.com/pydantic/pydantic/pull/8356) +* [@Elkiwa](https://github.com/Elkiwa) made their first contribution in [#8341](https://github.com/pydantic/pydantic/pull/8341) +* [@parhamfh](https://github.com/parhamfh) made their first contribution in [#8395](https://github.com/pydantic/pydantic/pull/8395) +* [@shenxiangzhuang](https://github.com/shenxiangzhuang) made their first contribution in [#8402](https://github.com/pydantic/pydantic/pull/8402) +* [@NeevCohen](https://github.com/NeevCohen) made their first contribution in [#8387](https://github.com/pydantic/pydantic/pull/8387) +* [@zby](https://github.com/zby) made their first contribution in [#8497](https://github.com/pydantic/pydantic/pull/8497) +* [@patelnets](https://github.com/patelnets) made their first contribution in [#8491](https://github.com/pydantic/pydantic/pull/8491) +* [@edwardwli](https://github.com/edwardwli) made their first contribution in [#8503](https://github.com/pydantic/pydantic/pull/8503) +* [@luca-matei](https://github.com/luca-matei) made their first contribution in [#8507](https://github.com/pydantic/pydantic/pull/8507) +* [@Jocelyn-Gas](https://github.com/Jocelyn-Gas) made their first contribution in [#8437](https://github.com/pydantic/pydantic/pull/8437) +* [@bL34cHig0](https://github.com/bL34cHig0) made their first contribution in [#8501](https://github.com/pydantic/pydantic/pull/8501) +* [@tigeryy2](https://github.com/tigeryy2) made their first contribution in [#8511](https://github.com/pydantic/pydantic/pull/8511) +* [@geospackle](https://github.com/geospackle) made their first contribution in [#8537](https://github.com/pydantic/pydantic/pull/8537) +* [@Anvil](https://github.com/Anvil) made their first contribution in [#8567](https://github.com/pydantic/pydantic/pull/8567) +* [@hungtsetse](https://github.com/hungtsetse) made their first contribution in [#8546](https://github.com/pydantic/pydantic/pull/8546) +* [@StrawHatDrag0n](https://github.com/StrawHatDrag0n) made their first contribution in [#8583](https://github.com/pydantic/pydantic/pull/8583) + +#### `pydantic-core` +* [@mariuswinger](https://github.com/mariuswinger) made their first contribution in [pydantic/pydantic-core#1087](https://github.com/pydantic/pydantic-core/pull/1087) +* [@adamchainz](https://github.com/adamchainz) made their first contribution in [pydantic/pydantic-core#1090](https://github.com/pydantic/pydantic-core/pull/1090) +* [@akx](https://github.com/akx) made their first contribution in [pydantic/pydantic-core#1123](https://github.com/pydantic/pydantic-core/pull/1123) + +## v2.6.0b1 (2024-01-19) + +Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.6.0b1) for details. + +## v2.5.3 (2023-12-22) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.3) + +### What's Changed + +#### Packaging + +* uprev `pydantic-core` to 2.14.6 + +#### Fixes + +* Fix memory leak with recursive definitions creating reference cycles by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1125](https://github.com/pydantic/pydantic-core/pull/1125) + +## v2.5.2 (2023-11-22) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.2) + +### What's Changed + +#### Packaging + +* uprev `pydantic-core` to 2.14.5 + +#### New Features + +* Add `ConfigDict.ser_json_inf_nan` by [@davidhewitt](https://github.com/davidhewitt) in [#8159](https://github.com/pydantic/pydantic/pull/8159) + +#### Fixes + +* Fix validation of `Literal` from JSON keys when used as `dict` key by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1075](https://github.com/pydantic/pydantic-core/pull/1075) +* Fix bug re `custom_init` on members of `Union` by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1076](https://github.com/pydantic/pydantic-core/pull/1076) +* Fix `JsonValue` `bool` serialization by [@sydney-runkle](https://github.com/sydney-runkle) in [#8190](https://github.com/pydantic/pydantic/pull/8159) +* Fix handling of unhashable inputs with `Literal` in `Union`s by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1089](https://github.com/pydantic/pydantic-core/pull/1089) + +## v2.5.1 (2023-11-15) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.1) + +### What's Changed + +#### Packaging + +* uprev pydantic-core to 2.14.3 by [@samuelcolvin](https://github.com/samuelcolvin) in [#8120](https://github.com/pydantic/pydantic/pull/8120) + +#### Fixes + +* Fix package description limit by [@dmontagu](https://github.com/dmontagu) in [#8097](https://github.com/pydantic/pydantic/pull/8097) +* Fix `ValidateCallWrapper` error when creating a model which has a [@validate_call](https://github.com/validate_call) wrapped field annotation by [@sydney-runkle](https://github.com/sydney-runkle) in [#8110](https://github.com/pydantic/pydantic/pull/8110) + +## v2.5.0 (2023-11-13) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.0) + +The code released in v2.5.0 is functionally identical to that of v2.5.0b1. + +### What's Changed + +#### Packaging + +* Update pydantic-core from 2.10.1 to 2.14.1, significant changes from these updates are described below, full changelog [here](https://github.com/pydantic/pydantic-core/compare/v2.10.1...v2.14.1) +* Update to `pyright==1.1.335` by [@Viicos](https://github.com/Viicos) in [#8075](https://github.com/pydantic/pydantic/pull/8075) + +#### New Features + +* Allow plugins to catch non `ValidationError` errors by [@adriangb](https://github.com/adriangb) in [#7806](https://github.com/pydantic/pydantic/pull/7806) +* Support `__doc__` argument in `create_model()` by [@chris-spann](https://github.com/chris-spann) in [#7863](https://github.com/pydantic/pydantic/pull/7863) +* Expose `regex_engine` flag - meaning you can use with the Rust or Python regex libraries in constraints by [@utkini](https://github.com/utkini) in [#7768](https://github.com/pydantic/pydantic/pull/7768) +* Save return type generated from type annotation in `ComputedFieldInfo` by [@alexmojaki](https://github.com/alexmojaki) in [#7889](https://github.com/pydantic/pydantic/pull/7889) +* Adopting `ruff` formatter by [@Luca-Blight](https://github.com/Luca-Blight) in [#7930](https://github.com/pydantic/pydantic/pull/7930) +* Added `validation_error_cause` to config by [@zakstucke](https://github.com/zakstucke) in [#7626](https://github.com/pydantic/pydantic/pull/7626) +* Make path of the item to validate available in plugin by [@hramezani](https://github.com/hramezani) in [#7861](https://github.com/pydantic/pydantic/pull/7861) +* Add `CallableDiscriminator` and `Tag` by [@dmontagu](https://github.com/dmontagu) in [#7983](https://github.com/pydantic/pydantic/pull/7983) + * `CallableDiscriminator` renamed to `Discriminator` by [@dmontagu](https://github.com/dmontagu) in [#8047](https://github.com/pydantic/pydantic/pull/8047) +* Make union case tags affect union error messages by [@dmontagu](https://github.com/dmontagu) in [#8001](https://github.com/pydantic/pydantic/pull/8001) +* Add `examples` and `json_schema_extra` to `@computed_field` by [@alexmojaki](https://github.com/alexmojaki) in [#8013](https://github.com/pydantic/pydantic/pull/8013) +* Add `JsonValue` type by [@dmontagu](https://github.com/dmontagu) in [#7998](https://github.com/pydantic/pydantic/pull/7998) +* Allow `str` as argument to `Discriminator` by [@dmontagu](https://github.com/dmontagu) in [#8047](https://github.com/pydantic/pydantic/pull/8047) +* Add `SchemaSerializer.__reduce__` method to enable pickle serialization by [@edoakes](https://github.com/edoakes) in [pydantic/pydantic-core#1006](https://github.com/pydantic/pydantic-core/pull/1006) + +#### Changes + +* **Significant Change:** replace `ultra_strict` with new smart union implementation, the way unions are validated has changed significantly to improve performance and correctness, we have worked hard to absolutely minimise the number of cases where behaviour has changed, see the PR for details - by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#867](https://github.com/pydantic/pydantic-core/pull/867) +* Add support for instance method reassignment when `extra='allow'` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7683](https://github.com/pydantic/pydantic/pull/7683) +* Support JSON schema generation for `Enum` types with no cases by [@sydney-runkle](https://github.com/sydney-runkle) in [#7927](https://github.com/pydantic/pydantic/pull/7927) +* Warn if a class inherits from `Generic` before `BaseModel` by [@alexmojaki](https://github.com/alexmojaki) in [#7891](https://github.com/pydantic/pydantic/pull/7891) + +#### Performance + +* New custom JSON parser, `jiter` by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#974](https://github.com/pydantic/pydantic-core/pull/974) +* PGO build for MacOS M1 by [@samuelcolvin](https://github.com/samuelcolvin) in [pydantic/pydantic-core#1063](https://github.com/pydantic/pydantic-core/pull/1063) +* Use `__getattr__` for all package imports, improve import time by [@samuelcolvin](https://github.com/samuelcolvin) in [#7947](https://github.com/pydantic/pydantic/pull/7947) + +#### Fixes + +* Fix `mypy` issue with subclasses of `RootModel` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7677](https://github.com/pydantic/pydantic/pull/7677) +* Properly rebuild the `FieldInfo` when a forward ref gets evaluated by [@dmontagu](https://github.com/dmontagu) in [#7698](https://github.com/pydantic/pydantic/pull/7698) +* Fix failure to load `SecretStr` from JSON (regression in v2.4) by [@sydney-runkle](https://github.com/sydney-runkle) in [#7729](https://github.com/pydantic/pydantic/pull/7729) +* Fix `defer_build` behavior with `TypeAdapter` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7736](https://github.com/pydantic/pydantic/pull/7736) +* Improve compatibility with legacy `mypy` versions by [@dmontagu](https://github.com/dmontagu) in [#7742](https://github.com/pydantic/pydantic/pull/7742) +* Fix: update `TypeVar` handling when default is not set by [@pmmmwh](https://github.com/pmmmwh) in [#7719](https://github.com/pydantic/pydantic/pull/7719) +* Support specification of `strict` on `Enum` type fields by [@sydney-runkle](https://github.com/sydney-runkle) in [#7761](https://github.com/pydantic/pydantic/pull/7761) +* Wrap `weakref.ref` instead of subclassing to fix `cloudpickle` serialization by [@edoakes](https://github.com/edoakes) in [#7780](https://github.com/pydantic/pydantic/pull/7780) +* Keep values of private attributes set within `model_post_init` in subclasses by [@alexmojaki](https://github.com/alexmojaki) in [#7775](https://github.com/pydantic/pydantic/pull/7775) +* Add more specific type for non-callable `json_schema_extra` by [@alexmojaki](https://github.com/alexmojaki) in [#7803](https://github.com/pydantic/pydantic/pull/7803) +* Raise an error when deleting frozen (model) fields by [@alexmojaki](https://github.com/alexmojaki) in [#7800](https://github.com/pydantic/pydantic/pull/7800) +* Fix schema sorting bug with default values by [@sydney-runkle](https://github.com/sydney-runkle) in [#7817](https://github.com/pydantic/pydantic/pull/7817) +* Use generated alias for aliases that are not specified otherwise by [@alexmojaki](https://github.com/alexmojaki) in [#7802](https://github.com/pydantic/pydantic/pull/7802) +* Support `strict` specification for `UUID` types by [@sydney-runkle](https://github.com/sydney-runkle) in [#7865](https://github.com/pydantic/pydantic/pull/7865) +* JSON schema: fix extra parameter handling by [@me-and](https://github.com/me-and) in [#7810](https://github.com/pydantic/pydantic/pull/7810) +* Fix: support `pydantic.Field(kw_only=True)` with inherited dataclasses by [@PrettyWood](https://github.com/PrettyWood) in [#7827](https://github.com/pydantic/pydantic/pull/7827) +* Support `validate_call` decorator for methods in classes with `__slots__` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7883](https://github.com/pydantic/pydantic/pull/7883) +* Fix pydantic dataclass problem with `dataclasses.field` default by [@hramezani](https://github.com/hramezani) in [#7898](https://github.com/pydantic/pydantic/pull/7898) +* Fix schema generation for generics with union type bounds by [@sydney-runkle](https://github.com/sydney-runkle) in [#7899](https://github.com/pydantic/pydantic/pull/7899) +* Fix version for `importlib_metadata` on python 3.7 by [@sydney-runkle](https://github.com/sydney-runkle) in [#7904](https://github.com/pydantic/pydantic/pull/7904) +* Support `|` operator (Union) in PydanticRecursiveRef by [@alexmojaki](https://github.com/alexmojaki) in [#7892](https://github.com/pydantic/pydantic/pull/7892) +* Fix `display_as_type` for `TypeAliasType` in python 3.12 by [@dmontagu](https://github.com/dmontagu) in [#7929](https://github.com/pydantic/pydantic/pull/7929) +* Add support for `NotRequired` generics in `TypedDict` by [@sydney-runkle](https://github.com/sydney-runkle) in [#7932](https://github.com/pydantic/pydantic/pull/7932) +* Make generic `TypeAliasType` specifications produce different schema definitions by [@alexdrydew](https://github.com/alexdrydew) in [#7893](https://github.com/pydantic/pydantic/pull/7893) +* Added fix for signature of inherited dataclass by [@howsunjow](https://github.com/howsunjow) in [#7925](https://github.com/pydantic/pydantic/pull/7925) +* Make the model name generation more robust in JSON schema by [@joakimnordling](https://github.com/joakimnordling) in [#7881](https://github.com/pydantic/pydantic/pull/7881) +* Fix plurals in validation error messages (in tests) by [@Iipin](https://github.com/Iipin) in [#7972](https://github.com/pydantic/pydantic/pull/7972) +* `PrivateAttr` is passed from `Annotated` default position by [@tabassco](https://github.com/tabassco) in [#8004](https://github.com/pydantic/pydantic/pull/8004) +* Don't decode bytes (which may not be UTF8) when displaying SecretBytes by [@alexmojaki](https://github.com/alexmojaki) in [#8012](https://github.com/pydantic/pydantic/pull/8012) +* Use `classmethod` instead of `classmethod[Any, Any, Any]` by [@Mr-Pepe](https://github.com/Mr-Pepe) in [#7979](https://github.com/pydantic/pydantic/pull/7979) +* Clearer error on invalid Plugin by [@samuelcolvin](https://github.com/samuelcolvin) in [#8023](https://github.com/pydantic/pydantic/pull/8023) +* Correct pydantic dataclasses import by [@samuelcolvin](https://github.com/samuelcolvin) in [#8027](https://github.com/pydantic/pydantic/pull/8027) +* Fix misbehavior for models referencing redefined type aliases by [@dmontagu](https://github.com/dmontagu) in [#8050](https://github.com/pydantic/pydantic/pull/8050) +* Fix `Optional` field with `validate_default` only performing one field validation by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1002](https://github.com/pydantic/pydantic-core/pull/1002) +* Fix `definition-ref` bug with `Dict` keys by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1014](https://github.com/pydantic/pydantic-core/pull/1014) +* Fix bug allowing validation of `bool` types with `coerce_numbers_to_str=True` by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1017](https://github.com/pydantic/pydantic-core/pull/1017) +* Don't accept `NaN` in float and decimal constraints by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1037](https://github.com/pydantic/pydantic-core/pull/1037) +* Add `lax_str` and `lax_int` support for enum values not inherited from str/int by [@michaelhly](https://github.com/michaelhly) in [pydantic/pydantic-core#1015](https://github.com/pydantic/pydantic-core/pull/1015) +* Support subclasses in lists in `Union` of `List` types by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1039](https://github.com/pydantic/pydantic-core/pull/1039) +* Allow validation against `max_digits` and `decimals` to pass if normalized or non-normalized input is valid by [@sydney-runkle](https://github.com/sydney-runkle) in [pydantic/pydantic-core#1049](https://github.com/pydantic/pydantic-core/pull/1049) +* Fix: proper pluralization in `ValidationError` messages by [@Iipin](https://github.com/Iipin) in [pydantic/pydantic-core#1050](https://github.com/pydantic/pydantic-core/pull/1050) +* Disallow the string `'-'` as `datetime` input by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/speedate#52](https://github.com/pydantic/speedate/pull/52) & [pydantic/pydantic-core#1060](https://github.com/pydantic/pydantic-core/pull/1060) +* Fix: NaN and Inf float serialization by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1062](https://github.com/pydantic/pydantic-core/pull/1062) +* Restore manylinux-compatible PGO builds by [@davidhewitt](https://github.com/davidhewitt) in [pydantic/pydantic-core#1068](https://github.com/pydantic/pydantic-core/pull/1068) + +### New Contributors + +#### `pydantic` +* [@schneebuzz](https://github.com/schneebuzz) made their first contribution in [#7699](https://github.com/pydantic/pydantic/pull/7699) +* [@edoakes](https://github.com/edoakes) made their first contribution in [#7780](https://github.com/pydantic/pydantic/pull/7780) +* [@alexmojaki](https://github.com/alexmojaki) made their first contribution in [#7775](https://github.com/pydantic/pydantic/pull/7775) +* [@NickG123](https://github.com/NickG123) made their first contribution in [#7751](https://github.com/pydantic/pydantic/pull/7751) +* [@gowthamgts](https://github.com/gowthamgts) made their first contribution in [#7830](https://github.com/pydantic/pydantic/pull/7830) +* [@jamesbraza](https://github.com/jamesbraza) made their first contribution in [#7848](https://github.com/pydantic/pydantic/pull/7848) +* [@laundmo](https://github.com/laundmo) made their first contribution in [#7850](https://github.com/pydantic/pydantic/pull/7850) +* [@rahmatnazali](https://github.com/rahmatnazali) made their first contribution in [#7870](https://github.com/pydantic/pydantic/pull/7870) +* [@waterfountain1996](https://github.com/waterfountain1996) made their first contribution in [#7878](https://github.com/pydantic/pydantic/pull/7878) +* [@chris-spann](https://github.com/chris-spann) made their first contribution in [#7863](https://github.com/pydantic/pydantic/pull/7863) +* [@me-and](https://github.com/me-and) made their first contribution in [#7810](https://github.com/pydantic/pydantic/pull/7810) +* [@utkini](https://github.com/utkini) made their first contribution in [#7768](https://github.com/pydantic/pydantic/pull/7768) +* [@bn-l](https://github.com/bn-l) made their first contribution in [#7744](https://github.com/pydantic/pydantic/pull/7744) +* [@alexdrydew](https://github.com/alexdrydew) made their first contribution in [#7893](https://github.com/pydantic/pydantic/pull/7893) +* [@Luca-Blight](https://github.com/Luca-Blight) made their first contribution in [#7930](https://github.com/pydantic/pydantic/pull/7930) +* [@howsunjow](https://github.com/howsunjow) made their first contribution in [#7925](https://github.com/pydantic/pydantic/pull/7925) +* [@joakimnordling](https://github.com/joakimnordling) made their first contribution in [#7881](https://github.com/pydantic/pydantic/pull/7881) +* [@icfly2](https://github.com/icfly2) made their first contribution in [#7976](https://github.com/pydantic/pydantic/pull/7976) +* [@Yummy-Yums](https://github.com/Yummy-Yums) made their first contribution in [#8003](https://github.com/pydantic/pydantic/pull/8003) +* [@Iipin](https://github.com/Iipin) made their first contribution in [#7972](https://github.com/pydantic/pydantic/pull/7972) +* [@tabassco](https://github.com/tabassco) made their first contribution in [#8004](https://github.com/pydantic/pydantic/pull/8004) +* [@Mr-Pepe](https://github.com/Mr-Pepe) made their first contribution in [#7979](https://github.com/pydantic/pydantic/pull/7979) +* [@0x00cl](https://github.com/0x00cl) made their first contribution in [#8010](https://github.com/pydantic/pydantic/pull/8010) +* [@barraponto](https://github.com/barraponto) made their first contribution in [#8032](https://github.com/pydantic/pydantic/pull/8032) + +#### `pydantic-core` +* [@sisp](https://github.com/sisp) made their first contribution in [pydantic/pydantic-core#995](https://github.com/pydantic/pydantic-core/pull/995) +* [@michaelhly](https://github.com/michaelhly) made their first contribution in [pydantic/pydantic-core#1015](https://github.com/pydantic/pydantic-core/pull/1015) + +## v2.5.0b1 (2023-11-09) + +Pre-release, see [the GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.5.0b1) for details. + +## v2.4.2 (2023-09-27) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.4.2) + +### What's Changed + +#### Fixes + +* Fix bug with JSON schema for sequence of discriminated union by [@dmontagu](https://github.com/dmontagu) in [#7647](https://github.com/pydantic/pydantic/pull/7647) +* Fix schema references in discriminated unions by [@adriangb](https://github.com/adriangb) in [#7646](https://github.com/pydantic/pydantic/pull/7646) +* Fix json schema generation for recursive models by [@adriangb](https://github.com/adriangb) in [#7653](https://github.com/pydantic/pydantic/pull/7653) +* Fix `models_json_schema` for generic models by [@adriangb](https://github.com/adriangb) in [#7654](https://github.com/pydantic/pydantic/pull/7654) +* Fix xfailed test for generic model signatures by [@adriangb](https://github.com/adriangb) in [#7658](https://github.com/pydantic/pydantic/pull/7658) + +### New Contributors + +* [@austinorr](https://github.com/austinorr) made their first contribution in [#7657](https://github.com/pydantic/pydantic/pull/7657) +* [@peterHoburg](https://github.com/peterHoburg) made their first contribution in [#7670](https://github.com/pydantic/pydantic/pull/7670) + +## v2.4.1 (2023-09-26) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.4.1) + +### What's Changed + +#### Packaging + +* Update pydantic-core to 2.10.1 by [@davidhewitt](https://github.com/davidhewitt) in [#7633](https://github.com/pydantic/pydantic/pull/7633) + +#### Fixes + +* Serialize unsubstituted type vars as `Any` by [@adriangb](https://github.com/adriangb) in [#7606](https://github.com/pydantic/pydantic/pull/7606) +* Remove schema building caches by [@adriangb](https://github.com/adriangb) in [#7624](https://github.com/pydantic/pydantic/pull/7624) +* Fix an issue where JSON schema extras weren't JSON encoded by [@dmontagu](https://github.com/dmontagu) in [#7625](https://github.com/pydantic/pydantic/pull/7625) + +## v2.4.0 (2023-09-22) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.4.0) + +### What's Changed + +#### Packaging + +* Update pydantic-core to 2.10.0 by [@samuelcolvin](https://github.com/samuelcolvin) in [#7542](https://github.com/pydantic/pydantic/pull/7542) + +#### New Features + +* Add `Base64Url` types by [@dmontagu](https://github.com/dmontagu) in [#7286](https://github.com/pydantic/pydantic/pull/7286) +* Implement optional `number` to `str` coercion by [@lig](https://github.com/lig) in [#7508](https://github.com/pydantic/pydantic/pull/7508) +* Allow access to `field_name` and `data` in all validators if there is data and a field name by [@samuelcolvin](https://github.com/samuelcolvin) in [#7542](https://github.com/pydantic/pydantic/pull/7542) +* Add `BaseModel.model_validate_strings` and `TypeAdapter.validate_strings` by [@hramezani](https://github.com/hramezani) in [#7552](https://github.com/pydantic/pydantic/pull/7552) +* Add Pydantic `plugins` experimental implementation by [@lig](https://github.com/lig) [@samuelcolvin](https://github.com/samuelcolvin) and [@Kludex](https://github.com/Kludex) in [#6820](https://github.com/pydantic/pydantic/pull/6820) + +#### Changes + +* Do not override `model_post_init` in subclass with private attrs by [@Viicos](https://github.com/Viicos) in [#7302](https://github.com/pydantic/pydantic/pull/7302) +* Make fields with defaults not required in the serialization schema by default by [@dmontagu](https://github.com/dmontagu) in [#7275](https://github.com/pydantic/pydantic/pull/7275) +* Mark `Extra` as deprecated by [@disrupted](https://github.com/disrupted) in [#7299](https://github.com/pydantic/pydantic/pull/7299) +* Make `EncodedStr` a dataclass by [@Kludex](https://github.com/Kludex) in [#7396](https://github.com/pydantic/pydantic/pull/7396) +* Move `annotated_handlers` to be public by [@samuelcolvin](https://github.com/samuelcolvin) in [#7569](https://github.com/pydantic/pydantic/pull/7569) + +#### Performance + +* Simplify flattening and inlining of `CoreSchema` by [@adriangb](https://github.com/adriangb) in [#7523](https://github.com/pydantic/pydantic/pull/7523) +* Remove unused copies in `CoreSchema` walking by [@adriangb](https://github.com/adriangb) in [#7528](https://github.com/pydantic/pydantic/pull/7528) +* Add caches for collecting definitions and invalid schemas from a CoreSchema by [@adriangb](https://github.com/adriangb) in [#7527](https://github.com/pydantic/pydantic/pull/7527) +* Eagerly resolve discriminated unions and cache cases where we can't by [@adriangb](https://github.com/adriangb) in [#7529](https://github.com/pydantic/pydantic/pull/7529) +* Replace `dict.get` and `dict.setdefault` with more verbose versions in `CoreSchema` building hot paths by [@adriangb](https://github.com/adriangb) in [#7536](https://github.com/pydantic/pydantic/pull/7536) +* Cache invalid `CoreSchema` discovery by [@adriangb](https://github.com/adriangb) in [#7535](https://github.com/pydantic/pydantic/pull/7535) +* Allow disabling `CoreSchema` validation for faster startup times by [@adriangb](https://github.com/adriangb) in [#7565](https://github.com/pydantic/pydantic/pull/7565) + +#### Fixes + +* Fix config detection for `TypedDict` from grandparent classes by [@dmontagu](https://github.com/dmontagu) in [#7272](https://github.com/pydantic/pydantic/pull/7272) +* Fix hash function generation for frozen models with unusual MRO by [@dmontagu](https://github.com/dmontagu) in [#7274](https://github.com/pydantic/pydantic/pull/7274) +* Make `strict` config overridable in field for Path by [@hramezani](https://github.com/hramezani) in [#7281](https://github.com/pydantic/pydantic/pull/7281) +* Use `ser_json_` on default in `GenerateJsonSchema` by [@Kludex](https://github.com/Kludex) in [#7269](https://github.com/pydantic/pydantic/pull/7269) +* Adding a check that alias is validated as an identifier for Python by [@andree0](https://github.com/andree0) in [#7319](https://github.com/pydantic/pydantic/pull/7319) +* Raise an error when computed field overrides field by [@sydney-runkle](https://github.com/sydney-runkle) in [#7346](https://github.com/pydantic/pydantic/pull/7346) +* Fix applying `SkipValidation` to referenced schemas by [@adriangb](https://github.com/adriangb) in [#7381](https://github.com/pydantic/pydantic/pull/7381) +* Enforce behavior of private attributes having double leading underscore by [@lig](https://github.com/lig) in [#7265](https://github.com/pydantic/pydantic/pull/7265) +* Standardize `__get_pydantic_core_schema__` signature by [@hramezani](https://github.com/hramezani) in [#7415](https://github.com/pydantic/pydantic/pull/7415) +* Fix generic dataclass fields mutation bug (when using `TypeAdapter`) by [@sydney-runkle](https://github.com/sydney-runkle) in [#7435](https://github.com/pydantic/pydantic/pull/7435) +* Fix `TypeError` on `model_validator` in `wrap` mode by [@pmmmwh](https://github.com/pmmmwh) in [#7496](https://github.com/pydantic/pydantic/pull/7496) +* Improve enum error message by [@hramezani](https://github.com/hramezani) in [#7506](https://github.com/pydantic/pydantic/pull/7506) +* Make `repr` work for instances that failed initialization when handling `ValidationError`s by [@dmontagu](https://github.com/dmontagu) in [#7439](https://github.com/pydantic/pydantic/pull/7439) +* Fixed a regular expression denial of service issue by limiting whitespaces by [@prodigysml](https://github.com/prodigysml) in [#7360](https://github.com/pydantic/pydantic/pull/7360) +* Fix handling of `UUID` values having `UUID.version=None` by [@lig](https://github.com/lig) in [#7566](https://github.com/pydantic/pydantic/pull/7566) +* Fix `__iter__` returning private `cached_property` info by [@sydney-runkle](https://github.com/sydney-runkle) in [#7570](https://github.com/pydantic/pydantic/pull/7570) +* Improvements to version info message by [@samuelcolvin](https://github.com/samuelcolvin) in [#7594](https://github.com/pydantic/pydantic/pull/7594) + +### New Contributors +* [@15498th](https://github.com/15498th) made their first contribution in [#7238](https://github.com/pydantic/pydantic/pull/7238) +* [@GabrielCappelli](https://github.com/GabrielCappelli) made their first contribution in [#7213](https://github.com/pydantic/pydantic/pull/7213) +* [@tobni](https://github.com/tobni) made their first contribution in [#7184](https://github.com/pydantic/pydantic/pull/7184) +* [@redruin1](https://github.com/redruin1) made their first contribution in [#7282](https://github.com/pydantic/pydantic/pull/7282) +* [@FacerAin](https://github.com/FacerAin) made their first contribution in [#7288](https://github.com/pydantic/pydantic/pull/7288) +* [@acdha](https://github.com/acdha) made their first contribution in [#7297](https://github.com/pydantic/pydantic/pull/7297) +* [@andree0](https://github.com/andree0) made their first contribution in [#7319](https://github.com/pydantic/pydantic/pull/7319) +* [@gordonhart](https://github.com/gordonhart) made their first contribution in [#7375](https://github.com/pydantic/pydantic/pull/7375) +* [@pmmmwh](https://github.com/pmmmwh) made their first contribution in [#7496](https://github.com/pydantic/pydantic/pull/7496) +* [@disrupted](https://github.com/disrupted) made their first contribution in [#7299](https://github.com/pydantic/pydantic/pull/7299) +* [@prodigysml](https://github.com/prodigysml) made their first contribution in [#7360](https://github.com/pydantic/pydantic/pull/7360) + +## v2.3.0 (2023-08-23) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.3.0) + +* 🔥 Remove orphaned changes file from repo by [@lig](https://github.com/lig) in [#7168](https://github.com/pydantic/pydantic/pull/7168) +* Add copy button on documentation by [@Kludex](https://github.com/Kludex) in [#7190](https://github.com/pydantic/pydantic/pull/7190) +* Fix docs on JSON type by [@Kludex](https://github.com/Kludex) in [#7189](https://github.com/pydantic/pydantic/pull/7189) +* Update mypy 1.5.0 to 1.5.1 in CI by [@hramezani](https://github.com/hramezani) in [#7191](https://github.com/pydantic/pydantic/pull/7191) +* fix download links badge by [@samuelcolvin](https://github.com/samuelcolvin) in [#7200](https://github.com/pydantic/pydantic/pull/7200) +* add 2.2.1 to changelog by [@samuelcolvin](https://github.com/samuelcolvin) in [#7212](https://github.com/pydantic/pydantic/pull/7212) +* Make ModelWrapValidator protocols generic by [@dmontagu](https://github.com/dmontagu) in [#7154](https://github.com/pydantic/pydantic/pull/7154) +* Correct `Field(..., exclude: bool)` docs by [@samuelcolvin](https://github.com/samuelcolvin) in [#7214](https://github.com/pydantic/pydantic/pull/7214) +* Make shadowing attributes a warning instead of an error by [@adriangb](https://github.com/adriangb) in [#7193](https://github.com/pydantic/pydantic/pull/7193) +* Document `Base64Str` and `Base64Bytes` by [@Kludex](https://github.com/Kludex) in [#7192](https://github.com/pydantic/pydantic/pull/7192) +* Fix `config.defer_build` for serialization first cases by [@samuelcolvin](https://github.com/samuelcolvin) in [#7024](https://github.com/pydantic/pydantic/pull/7024) +* clean Model docstrings in JSON Schema by [@samuelcolvin](https://github.com/samuelcolvin) in [#7210](https://github.com/pydantic/pydantic/pull/7210) +* fix [#7228](https://github.com/pydantic/pydantic/pull/7228) (typo): docs in `validators.md` to correct `validate_default` kwarg by [@lmmx](https://github.com/lmmx) in [#7229](https://github.com/pydantic/pydantic/pull/7229) +* ✅ Implement `tzinfo.fromutc` method for `TzInfo` in `pydantic-core` by [@lig](https://github.com/lig) in [#7019](https://github.com/pydantic/pydantic/pull/7019) +* Support `__get_validators__` by [@hramezani](https://github.com/hramezani) in [#7197](https://github.com/pydantic/pydantic/pull/7197) + +## v2.2.1 (2023-08-18) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.2.1) + +* Make `xfail`ing test for root model extra stop `xfail`ing by [@dmontagu](https://github.com/dmontagu) in [#6937](https://github.com/pydantic/pydantic/pull/6937) +* Optimize recursion detection by stopping on the second visit for the same object by [@mciucu](https://github.com/mciucu) in [#7160](https://github.com/pydantic/pydantic/pull/7160) +* fix link in docs by [@tlambert03](https://github.com/tlambert03) in [#7166](https://github.com/pydantic/pydantic/pull/7166) +* Replace MiMalloc w/ default allocator by [@adriangb](https://github.com/adriangb) in [pydantic/pydantic-core#900](https://github.com/pydantic/pydantic-core/pull/900) +* Bump pydantic-core to 2.6.1 and prepare 2.2.1 release by [@adriangb](https://github.com/adriangb) in [#7176](https://github.com/pydantic/pydantic/pull/7176) + +## v2.2.0 (2023-08-17) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.2.0) + +* Split "pipx install" setup command into two commands on the documentation site by [@nomadmtb](https://github.com/nomadmtb) in [#6869](https://github.com/pydantic/pydantic/pull/6869) +* Deprecate `Field.include` by [@hramezani](https://github.com/hramezani) in [#6852](https://github.com/pydantic/pydantic/pull/6852) +* Fix typo in default factory error msg by [@hramezani](https://github.com/hramezani) in [#6880](https://github.com/pydantic/pydantic/pull/6880) +* Simplify handling of typing.Annotated in GenerateSchema by [@dmontagu](https://github.com/dmontagu) in [#6887](https://github.com/pydantic/pydantic/pull/6887) +* Re-enable fastapi tests in CI by [@dmontagu](https://github.com/dmontagu) in [#6883](https://github.com/pydantic/pydantic/pull/6883) +* Make it harder to hit collisions with json schema defrefs by [@dmontagu](https://github.com/dmontagu) in [#6566](https://github.com/pydantic/pydantic/pull/6566) +* Cleaner error for invalid input to `Path` fields by [@samuelcolvin](https://github.com/samuelcolvin) in [#6903](https://github.com/pydantic/pydantic/pull/6903) +* :memo: support Coordinate Type by [@yezz123](https://github.com/yezz123) in [#6906](https://github.com/pydantic/pydantic/pull/6906) +* Fix `ForwardRef` wrapper for py 3.10.0 (shim until bpo-45166) by [@randomir](https://github.com/randomir) in [#6919](https://github.com/pydantic/pydantic/pull/6919) +* Fix misbehavior related to copying of RootModel by [@dmontagu](https://github.com/dmontagu) in [#6918](https://github.com/pydantic/pydantic/pull/6918) +* Fix issue with recursion error caused by ParamSpec by [@dmontagu](https://github.com/dmontagu) in [#6923](https://github.com/pydantic/pydantic/pull/6923) +* Add section about Constrained classes to the Migration Guide by [@Kludex](https://github.com/Kludex) in [#6924](https://github.com/pydantic/pydantic/pull/6924) +* Use `main` branch for badge links by [@Viicos](https://github.com/Viicos) in [#6925](https://github.com/pydantic/pydantic/pull/6925) +* Add test for v1/v2 Annotated discrepancy by [@carlbordum](https://github.com/carlbordum) in [#6926](https://github.com/pydantic/pydantic/pull/6926) +* Make the v1 mypy plugin work with both v1 and v2 by [@dmontagu](https://github.com/dmontagu) in [#6921](https://github.com/pydantic/pydantic/pull/6921) +* Fix issue where generic models couldn't be parametrized with BaseModel by [@dmontagu](https://github.com/dmontagu) in [#6933](https://github.com/pydantic/pydantic/pull/6933) +* Remove xfail for discriminated union with alias by [@dmontagu](https://github.com/dmontagu) in [#6938](https://github.com/pydantic/pydantic/pull/6938) +* add field_serializer to computed_field by [@andresliszt](https://github.com/andresliszt) in [#6965](https://github.com/pydantic/pydantic/pull/6965) +* Use union_schema with Type[Union[...]] by [@JeanArhancet](https://github.com/JeanArhancet) in [#6952](https://github.com/pydantic/pydantic/pull/6952) +* Fix inherited typeddict attributes / config by [@adriangb](https://github.com/adriangb) in [#6981](https://github.com/pydantic/pydantic/pull/6981) +* fix dataclass annotated before validator called twice by [@davidhewitt](https://github.com/davidhewitt) in [#6998](https://github.com/pydantic/pydantic/pull/6998) +* Update test-fastapi deselected tests by [@hramezani](https://github.com/hramezani) in [#7014](https://github.com/pydantic/pydantic/pull/7014) +* Fix validator doc format by [@hramezani](https://github.com/hramezani) in [#7015](https://github.com/pydantic/pydantic/pull/7015) +* Fix typo in docstring of model_json_schema by [@AdamVinch-Federated](https://github.com/AdamVinch-Federated) in [#7032](https://github.com/pydantic/pydantic/pull/7032) +* remove unused "type ignores" with pyright by [@samuelcolvin](https://github.com/samuelcolvin) in [#7026](https://github.com/pydantic/pydantic/pull/7026) +* Add benchmark representing FastAPI startup time by [@adriangb](https://github.com/adriangb) in [#7030](https://github.com/pydantic/pydantic/pull/7030) +* Fix json_encoders for Enum subclasses by [@adriangb](https://github.com/adriangb) in [#7029](https://github.com/pydantic/pydantic/pull/7029) +* Update docstring of `ser_json_bytes` regarding base64 encoding by [@Viicos](https://github.com/Viicos) in [#7052](https://github.com/pydantic/pydantic/pull/7052) +* Allow `@validate_call` to work on async methods by [@adriangb](https://github.com/adriangb) in [#7046](https://github.com/pydantic/pydantic/pull/7046) +* Fix: mypy error with `Settings` and `SettingsConfigDict` by [@JeanArhancet](https://github.com/JeanArhancet) in [#7002](https://github.com/pydantic/pydantic/pull/7002) +* Fix some typos (repeated words and it's/its) by [@eumiro](https://github.com/eumiro) in [#7063](https://github.com/pydantic/pydantic/pull/7063) +* Fix the typo in docstring by [@harunyasar](https://github.com/harunyasar) in [#7062](https://github.com/pydantic/pydantic/pull/7062) +* Docs: Fix broken URL in the pydantic-settings package recommendation by [@swetjen](https://github.com/swetjen) in [#6995](https://github.com/pydantic/pydantic/pull/6995) +* Handle constraints being applied to schemas that don't accept it by [@adriangb](https://github.com/adriangb) in [#6951](https://github.com/pydantic/pydantic/pull/6951) +* Replace almost_equal_floats with math.isclose by [@eumiro](https://github.com/eumiro) in [#7082](https://github.com/pydantic/pydantic/pull/7082) +* bump pydantic-core to 2.5.0 by [@davidhewitt](https://github.com/davidhewitt) in [#7077](https://github.com/pydantic/pydantic/pull/7077) +* Add `short_version` and use it in links by [@hramezani](https://github.com/hramezani) in [#7115](https://github.com/pydantic/pydantic/pull/7115) +* 📝 Add usage link to `RootModel` by [@Kludex](https://github.com/Kludex) in [#7113](https://github.com/pydantic/pydantic/pull/7113) +* Revert "Fix default port for mongosrv DSNs (#6827)" by [@Kludex](https://github.com/Kludex) in [#7116](https://github.com/pydantic/pydantic/pull/7116) +* Clarify validate_default and _Unset handling in usage docs and migration guide by [@benbenbang](https://github.com/benbenbang) in [#6950](https://github.com/pydantic/pydantic/pull/6950) +* Tweak documentation of `Field.exclude` by [@Viicos](https://github.com/Viicos) in [#7086](https://github.com/pydantic/pydantic/pull/7086) +* Do not require `validate_assignment` to use `Field.frozen` by [@Viicos](https://github.com/Viicos) in [#7103](https://github.com/pydantic/pydantic/pull/7103) +* tweaks to `_core_utils` by [@samuelcolvin](https://github.com/samuelcolvin) in [#7040](https://github.com/pydantic/pydantic/pull/7040) +* Make DefaultDict working with set by [@hramezani](https://github.com/hramezani) in [#7126](https://github.com/pydantic/pydantic/pull/7126) +* Don't always require typing.Generic as a base for partially parametrized models by [@dmontagu](https://github.com/dmontagu) in [#7119](https://github.com/pydantic/pydantic/pull/7119) +* Fix issue with JSON schema incorrectly using parent class core schema by [@dmontagu](https://github.com/dmontagu) in [#7020](https://github.com/pydantic/pydantic/pull/7020) +* Fix xfailed test related to TypedDict and alias_generator by [@dmontagu](https://github.com/dmontagu) in [#6940](https://github.com/pydantic/pydantic/pull/6940) +* Improve error message for NameEmail by [@dmontagu](https://github.com/dmontagu) in [#6939](https://github.com/pydantic/pydantic/pull/6939) +* Fix generic computed fields by [@dmontagu](https://github.com/dmontagu) in [#6988](https://github.com/pydantic/pydantic/pull/6988) +* Reflect namedtuple default values during validation by [@dmontagu](https://github.com/dmontagu) in [#7144](https://github.com/pydantic/pydantic/pull/7144) +* Update dependencies, fix pydantic-core usage, fix CI issues by [@dmontagu](https://github.com/dmontagu) in [#7150](https://github.com/pydantic/pydantic/pull/7150) +* Add mypy 1.5.0 by [@hramezani](https://github.com/hramezani) in [#7118](https://github.com/pydantic/pydantic/pull/7118) +* Handle non-json native enum values by [@adriangb](https://github.com/adriangb) in [#7056](https://github.com/pydantic/pydantic/pull/7056) +* document `round_trip` in Json type documentation by [@jc-louis](https://github.com/jc-louis) in [#7137](https://github.com/pydantic/pydantic/pull/7137) +* Relax signature checks to better support builtins and C extension functions as validators by [@adriangb](https://github.com/adriangb) in [#7101](https://github.com/pydantic/pydantic/pull/7101) +* add union_mode='left_to_right' by [@davidhewitt](https://github.com/davidhewitt) in [#7151](https://github.com/pydantic/pydantic/pull/7151) +* Include an error message hint for inherited ordering by [@yvalencia91](https://github.com/yvalencia91) in [#7124](https://github.com/pydantic/pydantic/pull/7124) +* Fix one docs link and resolve some warnings for two others by [@dmontagu](https://github.com/dmontagu) in [#7153](https://github.com/pydantic/pydantic/pull/7153) +* Include Field extra keys name in warning by [@hramezani](https://github.com/hramezani) in [#7136](https://github.com/pydantic/pydantic/pull/7136) + +## v2.1.1 (2023-07-25) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.1.1) + +* Skip FieldInfo merging when unnecessary by [@dmontagu](https://github.com/dmontagu) in [#6862](https://github.com/pydantic/pydantic/pull/6862) + +## v2.1.0 (2023-07-25) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.1.0) + +* Add `StringConstraints` for use as Annotated metadata by [@adriangb](https://github.com/adriangb) in [#6605](https://github.com/pydantic/pydantic/pull/6605) +* Try to fix intermittently failing CI by [@adriangb](https://github.com/adriangb) in [#6683](https://github.com/pydantic/pydantic/pull/6683) +* Remove redundant example of optional vs default. by [@ehiggs-deliverect](https://github.com/ehiggs-deliverect) in [#6676](https://github.com/pydantic/pydantic/pull/6676) +* Docs update by [@samuelcolvin](https://github.com/samuelcolvin) in [#6692](https://github.com/pydantic/pydantic/pull/6692) +* Remove the Validate always section in validator docs by [@adriangb](https://github.com/adriangb) in [#6679](https://github.com/pydantic/pydantic/pull/6679) +* Fix recursion error in json schema generation by [@adriangb](https://github.com/adriangb) in [#6720](https://github.com/pydantic/pydantic/pull/6720) +* Fix incorrect subclass check for secretstr by [@AlexVndnblcke](https://github.com/AlexVndnblcke) in [#6730](https://github.com/pydantic/pydantic/pull/6730) +* update pdm / pdm lockfile to 2.8.0 by [@davidhewitt](https://github.com/davidhewitt) in [#6714](https://github.com/pydantic/pydantic/pull/6714) +* unpin pdm on more CI jobs by [@davidhewitt](https://github.com/davidhewitt) in [#6755](https://github.com/pydantic/pydantic/pull/6755) +* improve source locations for auxiliary packages in docs by [@davidhewitt](https://github.com/davidhewitt) in [#6749](https://github.com/pydantic/pydantic/pull/6749) +* Assume builtins don't accept an info argument by [@adriangb](https://github.com/adriangb) in [#6754](https://github.com/pydantic/pydantic/pull/6754) +* Fix bug where calling `help(BaseModelSubclass)` raises errors by [@hramezani](https://github.com/hramezani) in [#6758](https://github.com/pydantic/pydantic/pull/6758) +* Fix mypy plugin handling of `@model_validator(mode="after")` by [@ljodal](https://github.com/ljodal) in [#6753](https://github.com/pydantic/pydantic/pull/6753) +* update pydantic-core to 2.3.1 by [@davidhewitt](https://github.com/davidhewitt) in [#6756](https://github.com/pydantic/pydantic/pull/6756) +* Mypy plugin for settings by [@hramezani](https://github.com/hramezani) in [#6760](https://github.com/pydantic/pydantic/pull/6760) +* Use `contentSchema` keyword for JSON schema by [@dmontagu](https://github.com/dmontagu) in [#6715](https://github.com/pydantic/pydantic/pull/6715) +* fast-path checking finite decimals by [@davidhewitt](https://github.com/davidhewitt) in [#6769](https://github.com/pydantic/pydantic/pull/6769) +* Docs update by [@samuelcolvin](https://github.com/samuelcolvin) in [#6771](https://github.com/pydantic/pydantic/pull/6771) +* Improve json schema doc by [@hramezani](https://github.com/hramezani) in [#6772](https://github.com/pydantic/pydantic/pull/6772) +* Update validator docs by [@adriangb](https://github.com/adriangb) in [#6695](https://github.com/pydantic/pydantic/pull/6695) +* Fix typehint for wrap validator by [@dmontagu](https://github.com/dmontagu) in [#6788](https://github.com/pydantic/pydantic/pull/6788) +* 🐛 Fix validation warning for unions of Literal and other type by [@lig](https://github.com/lig) in [#6628](https://github.com/pydantic/pydantic/pull/6628) +* Update documentation for generics support in V2 by [@tpdorsey](https://github.com/tpdorsey) in [#6685](https://github.com/pydantic/pydantic/pull/6685) +* add pydantic-core build info to `version_info()` by [@samuelcolvin](https://github.com/samuelcolvin) in [#6785](https://github.com/pydantic/pydantic/pull/6785) +* Fix pydantic dataclasses that use slots with default values by [@dmontagu](https://github.com/dmontagu) in [#6796](https://github.com/pydantic/pydantic/pull/6796) +* Fix inheritance of hash function for frozen models by [@dmontagu](https://github.com/dmontagu) in [#6789](https://github.com/pydantic/pydantic/pull/6789) +* ✨ Add `SkipJsonSchema` annotation by [@Kludex](https://github.com/Kludex) in [#6653](https://github.com/pydantic/pydantic/pull/6653) +* Error if an invalid field name is used with Field by [@dmontagu](https://github.com/dmontagu) in [#6797](https://github.com/pydantic/pydantic/pull/6797) +* Add `GenericModel` to `MOVED_IN_V2` by [@adriangb](https://github.com/adriangb) in [#6776](https://github.com/pydantic/pydantic/pull/6776) +* Remove unused code from `docs/usage/types/custom.md` by [@hramezani](https://github.com/hramezani) in [#6803](https://github.com/pydantic/pydantic/pull/6803) +* Fix `float` -> `Decimal` coercion precision loss by [@adriangb](https://github.com/adriangb) in [#6810](https://github.com/pydantic/pydantic/pull/6810) +* remove email validation from the north star benchmark by [@davidhewitt](https://github.com/davidhewitt) in [#6816](https://github.com/pydantic/pydantic/pull/6816) +* Fix link to mypy by [@progsmile](https://github.com/progsmile) in [#6824](https://github.com/pydantic/pydantic/pull/6824) +* Improve initialization hooks example by [@hramezani](https://github.com/hramezani) in [#6822](https://github.com/pydantic/pydantic/pull/6822) +* Fix default port for mongosrv DSNs by [@dmontagu](https://github.com/dmontagu) in [#6827](https://github.com/pydantic/pydantic/pull/6827) +* Improve API documentation, in particular more links between usage and API docs by [@samuelcolvin](https://github.com/samuelcolvin) in [#6780](https://github.com/pydantic/pydantic/pull/6780) +* update pydantic-core to 2.4.0 by [@davidhewitt](https://github.com/davidhewitt) in [#6831](https://github.com/pydantic/pydantic/pull/6831) +* Fix `annotated_types.MaxLen` validator for custom sequence types by [@ImogenBits](https://github.com/ImogenBits) in [#6809](https://github.com/pydantic/pydantic/pull/6809) +* Update V1 by [@hramezani](https://github.com/hramezani) in [#6833](https://github.com/pydantic/pydantic/pull/6833) +* Make it so callable JSON schema extra works by [@dmontagu](https://github.com/dmontagu) in [#6798](https://github.com/pydantic/pydantic/pull/6798) +* Fix serialization issue with `InstanceOf` by [@dmontagu](https://github.com/dmontagu) in [#6829](https://github.com/pydantic/pydantic/pull/6829) +* Add back support for `json_encoders` by [@adriangb](https://github.com/adriangb) in [#6811](https://github.com/pydantic/pydantic/pull/6811) +* Update field annotations when building the schema by [@dmontagu](https://github.com/dmontagu) in [#6838](https://github.com/pydantic/pydantic/pull/6838) +* Use `WeakValueDictionary` to fix generic memory leak by [@dmontagu](https://github.com/dmontagu) in [#6681](https://github.com/pydantic/pydantic/pull/6681) +* Add `config.defer_build` to optionally make model building lazy by [@samuelcolvin](https://github.com/samuelcolvin) in [#6823](https://github.com/pydantic/pydantic/pull/6823) +* delegate `UUID` serialization to pydantic-core by [@davidhewitt](https://github.com/davidhewitt) in [#6850](https://github.com/pydantic/pydantic/pull/6850) +* Update `json_encoders` docs by [@adriangb](https://github.com/adriangb) in [#6848](https://github.com/pydantic/pydantic/pull/6848) +* Fix error message for `staticmethod`/`classmethod` order with validate_call by [@dmontagu](https://github.com/dmontagu) in [#6686](https://github.com/pydantic/pydantic/pull/6686) +* Improve documentation for `Config` by [@samuelcolvin](https://github.com/samuelcolvin) in [#6847](https://github.com/pydantic/pydantic/pull/6847) +* Update serialization doc to mention `Field.exclude` takes priority over call-time `include/exclude` by [@hramezani](https://github.com/hramezani) in [#6851](https://github.com/pydantic/pydantic/pull/6851) +* Allow customizing core schema generation by making `GenerateSchema` public by [@adriangb](https://github.com/adriangb) in [#6737](https://github.com/pydantic/pydantic/pull/6737) + +## v2.0.3 (2023-07-05) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.0.3) + +* Mention PyObject (v1) moving to ImportString (v2) in migration doc by [@slafs](https://github.com/slafs) in [#6456](https://github.com/pydantic/pydantic/pull/6456) +* Fix release-tweet CI by [@Kludex](https://github.com/Kludex) in [#6461](https://github.com/pydantic/pydantic/pull/6461) +* Revise the section on required / optional / nullable fields. by [@ybressler](https://github.com/ybressler) in [#6468](https://github.com/pydantic/pydantic/pull/6468) +* Warn if a type hint is not in fact a type by [@adriangb](https://github.com/adriangb) in [#6479](https://github.com/pydantic/pydantic/pull/6479) +* Replace TransformSchema with GetPydanticSchema by [@dmontagu](https://github.com/dmontagu) in [#6484](https://github.com/pydantic/pydantic/pull/6484) +* Fix the un-hashability of various annotation types, for use in caching generic containers by [@dmontagu](https://github.com/dmontagu) in [#6480](https://github.com/pydantic/pydantic/pull/6480) +* PYD-164: Rework custom types docs by [@adriangb](https://github.com/adriangb) in [#6490](https://github.com/pydantic/pydantic/pull/6490) +* Fix ci by [@adriangb](https://github.com/adriangb) in [#6507](https://github.com/pydantic/pydantic/pull/6507) +* Fix forward ref in generic by [@adriangb](https://github.com/adriangb) in [#6511](https://github.com/pydantic/pydantic/pull/6511) +* Fix generation of serialization JSON schemas for core_schema.ChainSchema by [@dmontagu](https://github.com/dmontagu) in [#6515](https://github.com/pydantic/pydantic/pull/6515) +* Document the change in `Field.alias` behavior in Pydantic V2 by [@hramezani](https://github.com/hramezani) in [#6508](https://github.com/pydantic/pydantic/pull/6508) +* Give better error message attempting to compute the json schema of a model with undefined fields by [@dmontagu](https://github.com/dmontagu) in [#6519](https://github.com/pydantic/pydantic/pull/6519) +* Document `alias_priority` by [@tpdorsey](https://github.com/tpdorsey) in [#6520](https://github.com/pydantic/pydantic/pull/6520) +* Add redirect for types documentation by [@tpdorsey](https://github.com/tpdorsey) in [#6513](https://github.com/pydantic/pydantic/pull/6513) +* Allow updating docs without release by [@samuelcolvin](https://github.com/samuelcolvin) in [#6551](https://github.com/pydantic/pydantic/pull/6551) +* Ensure docs tests always run in the right folder by [@dmontagu](https://github.com/dmontagu) in [#6487](https://github.com/pydantic/pydantic/pull/6487) +* Defer evaluation of return type hints for serializer functions by [@dmontagu](https://github.com/dmontagu) in [#6516](https://github.com/pydantic/pydantic/pull/6516) +* Disable E501 from Ruff and rely on just Black by [@adriangb](https://github.com/adriangb) in [#6552](https://github.com/pydantic/pydantic/pull/6552) +* Update JSON Schema documentation for V2 by [@tpdorsey](https://github.com/tpdorsey) in [#6492](https://github.com/pydantic/pydantic/pull/6492) +* Add documentation of cyclic reference handling by [@dmontagu](https://github.com/dmontagu) in [#6493](https://github.com/pydantic/pydantic/pull/6493) +* Remove the need for change files by [@samuelcolvin](https://github.com/samuelcolvin) in [#6556](https://github.com/pydantic/pydantic/pull/6556) +* add "north star" benchmark by [@davidhewitt](https://github.com/davidhewitt) in [#6547](https://github.com/pydantic/pydantic/pull/6547) +* Update Dataclasses docs by [@tpdorsey](https://github.com/tpdorsey) in [#6470](https://github.com/pydantic/pydantic/pull/6470) +* ♻️ Use different error message on v1 redirects by [@Kludex](https://github.com/Kludex) in [#6595](https://github.com/pydantic/pydantic/pull/6595) +* ⬆ Upgrade `pydantic-core` to v2.2.0 by [@lig](https://github.com/lig) in [#6589](https://github.com/pydantic/pydantic/pull/6589) +* Fix serialization for IPvAny by [@dmontagu](https://github.com/dmontagu) in [#6572](https://github.com/pydantic/pydantic/pull/6572) +* Improve CI by using PDM instead of pip to install typing-extensions by [@adriangb](https://github.com/adriangb) in [#6602](https://github.com/pydantic/pydantic/pull/6602) +* Add `enum` error type docs by [@lig](https://github.com/lig) in [#6603](https://github.com/pydantic/pydantic/pull/6603) +* 🐛 Fix `max_length` for unicode strings by [@lig](https://github.com/lig) in [#6559](https://github.com/pydantic/pydantic/pull/6559) +* Add documentation for accessing features via `pydantic.v1` by [@tpdorsey](https://github.com/tpdorsey) in [#6604](https://github.com/pydantic/pydantic/pull/6604) +* Include extra when iterating over a model by [@adriangb](https://github.com/adriangb) in [#6562](https://github.com/pydantic/pydantic/pull/6562) +* Fix typing of model_validator by [@adriangb](https://github.com/adriangb) in [#6514](https://github.com/pydantic/pydantic/pull/6514) +* Touch up Decimal validator by [@adriangb](https://github.com/adriangb) in [#6327](https://github.com/pydantic/pydantic/pull/6327) +* Fix various docstrings using fixed pytest-examples by [@dmontagu](https://github.com/dmontagu) in [#6607](https://github.com/pydantic/pydantic/pull/6607) +* Handle function validators in a discriminated union by [@dmontagu](https://github.com/dmontagu) in [#6570](https://github.com/pydantic/pydantic/pull/6570) +* Review json_schema.md by [@tpdorsey](https://github.com/tpdorsey) in [#6608](https://github.com/pydantic/pydantic/pull/6608) +* Make validate_call work on basemodel methods by [@dmontagu](https://github.com/dmontagu) in [#6569](https://github.com/pydantic/pydantic/pull/6569) +* add test for big int json serde by [@davidhewitt](https://github.com/davidhewitt) in [#6614](https://github.com/pydantic/pydantic/pull/6614) +* Fix pydantic dataclass problem with dataclasses.field default_factory by [@hramezani](https://github.com/hramezani) in [#6616](https://github.com/pydantic/pydantic/pull/6616) +* Fixed mypy type inference for TypeAdapter by [@zakstucke](https://github.com/zakstucke) in [#6617](https://github.com/pydantic/pydantic/pull/6617) +* Make it work to use None as a generic parameter by [@dmontagu](https://github.com/dmontagu) in [#6609](https://github.com/pydantic/pydantic/pull/6609) +* Make it work to use `$ref` as an alias by [@dmontagu](https://github.com/dmontagu) in [#6568](https://github.com/pydantic/pydantic/pull/6568) +* add note to migration guide about changes to `AnyUrl` etc by [@davidhewitt](https://github.com/davidhewitt) in [#6618](https://github.com/pydantic/pydantic/pull/6618) +* 🐛 Support defining `json_schema_extra` on `RootModel` using `Field` by [@lig](https://github.com/lig) in [#6622](https://github.com/pydantic/pydantic/pull/6622) +* Update pre-commit to prevent commits to main branch on accident by [@dmontagu](https://github.com/dmontagu) in [#6636](https://github.com/pydantic/pydantic/pull/6636) +* Fix PDM CI for python 3.7 on MacOS/windows by [@dmontagu](https://github.com/dmontagu) in [#6627](https://github.com/pydantic/pydantic/pull/6627) +* Produce more accurate signatures for pydantic dataclasses by [@dmontagu](https://github.com/dmontagu) in [#6633](https://github.com/pydantic/pydantic/pull/6633) +* Updates to Url types for Pydantic V2 by [@tpdorsey](https://github.com/tpdorsey) in [#6638](https://github.com/pydantic/pydantic/pull/6638) +* Fix list markdown in `transform` docstring by [@StefanBRas](https://github.com/StefanBRas) in [#6649](https://github.com/pydantic/pydantic/pull/6649) +* simplify slots_dataclass construction to appease mypy by [@davidhewitt](https://github.com/davidhewitt) in [#6639](https://github.com/pydantic/pydantic/pull/6639) +* Update TypedDict schema generation docstring by [@adriangb](https://github.com/adriangb) in [#6651](https://github.com/pydantic/pydantic/pull/6651) +* Detect and lint-error for prints by [@dmontagu](https://github.com/dmontagu) in [#6655](https://github.com/pydantic/pydantic/pull/6655) +* Add xfailing test for pydantic-core PR 766 by [@dmontagu](https://github.com/dmontagu) in [#6641](https://github.com/pydantic/pydantic/pull/6641) +* Ignore unrecognized fields from dataclasses metadata by [@dmontagu](https://github.com/dmontagu) in [#6634](https://github.com/pydantic/pydantic/pull/6634) +* Make non-existent class getattr a mypy error by [@dmontagu](https://github.com/dmontagu) in [#6658](https://github.com/pydantic/pydantic/pull/6658) +* Update pydantic-core to 2.3.0 by [@hramezani](https://github.com/hramezani) in [#6648](https://github.com/pydantic/pydantic/pull/6648) +* Use OrderedDict from typing_extensions by [@dmontagu](https://github.com/dmontagu) in [#6664](https://github.com/pydantic/pydantic/pull/6664) +* Fix typehint for JSON schema extra callable by [@dmontagu](https://github.com/dmontagu) in [#6659](https://github.com/pydantic/pydantic/pull/6659) + +## v2.0.2 (2023-07-05) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.0.2) + +* Fix bug where round-trip pickling/unpickling a `RootModel` would change the value of `__dict__`, [#6457](https://github.com/pydantic/pydantic/pull/6457) by [@dmontagu](https://github.com/dmontagu) +* Allow single-item discriminated unions, [#6405](https://github.com/pydantic/pydantic/pull/6405) by [@dmontagu](https://github.com/dmontagu) +* Fix issue with union parsing of enums, [#6440](https://github.com/pydantic/pydantic/pull/6440) by [@dmontagu](https://github.com/dmontagu) +* Docs: Fixed `constr` documentation, renamed old `regex` to new `pattern`, [#6452](https://github.com/pydantic/pydantic/pull/6452) by [@miili](https://github.com/miili) +* Change `GenerateJsonSchema.generate_definitions` signature, [#6436](https://github.com/pydantic/pydantic/pull/6436) by [@dmontagu](https://github.com/dmontagu) + +See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0.2) + +## v2.0.1 (2023-07-04) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.0.1) + +First patch release of Pydantic V2 + +* Extra fields added via `setattr` (i.e. `m.some_extra_field = 'extra_value'`) + are added to `.model_extra` if `model_config` `extra='allowed'`. Fixed [#6333](https://github.com/pydantic/pydantic/pull/6333), [#6365](https://github.com/pydantic/pydantic/pull/6365) by [@aaraney](https://github.com/aaraney) +* Automatically unpack JSON schema '$ref' for custom types, [#6343](https://github.com/pydantic/pydantic/pull/6343) by [@adriangb](https://github.com/adriangb) +* Fix tagged unions multiple processing in submodels, [#6340](https://github.com/pydantic/pydantic/pull/6340) by [@suharnikov](https://github.com/suharnikov) + +See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0.1) + +## v2.0 (2023-06-30) + +[GitHub release](https://github.com/pydantic/pydantic/releases/tag/v2.0) + +Pydantic V2 is here! :tada: + +See [this post](https://docs.pydantic.dev/2.0/blog/pydantic-v2-final/) for more details. + +## v2.0b3 (2023-06-16) + +Third beta pre-release of Pydantic V2 + +See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0b3) + +## v2.0b2 (2023-06-03) + +Add `from_attributes` runtime flag to `TypeAdapter.validate_python` and `BaseModel.model_validate`. + +See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0b2) + +## v2.0b1 (2023-06-01) + +First beta pre-release of Pydantic V2 + +See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0b1) + +## v2.0a4 (2023-05-05) + +Fourth pre-release of Pydantic V2 + +See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0a4) + +## v2.0a3 (2023-04-20) + +Third pre-release of Pydantic V2 + +See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0a3) + +## v2.0a2 (2023-04-12) + +Second pre-release of Pydantic V2 + +See the full changelog [here](https://github.com/pydantic/pydantic/releases/tag/v2.0a2) + +## v2.0a1 (2023-04-03) + +First pre-release of Pydantic V2! + +See [this post](https://docs.pydantic.dev/blog/pydantic-v2-alpha/) for more details. + + +... see [here](https://docs.pydantic.dev/changelog/#v0322-2019-08-17) for earlier changes. diff --git a/env/Lib/site-packages/pydantic-2.8.2.dist-info/RECORD b/env/Lib/site-packages/pydantic-2.8.2.dist-info/RECORD new file mode 100644 index 0000000..d60553f --- /dev/null +++ b/env/Lib/site-packages/pydantic-2.8.2.dist-info/RECORD @@ -0,0 +1,207 @@ +pydantic-2.8.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pydantic-2.8.2.dist-info/METADATA,sha256=H8IPn6l33xNo3SR-xJDe1NhEYzxEsCIl2C2RkhQohu4,125181 +pydantic-2.8.2.dist-info/RECORD,, +pydantic-2.8.2.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87 +pydantic-2.8.2.dist-info/licenses/LICENSE,sha256=qeGG88oWte74QxjnpwFyE1GgDLe4rjpDlLZ7SeNSnvM,1129 +pydantic/__init__.py,sha256=UfcGIDJ0chxdnl0_o6dTyys-5isaoZwlKVMAwwBwPPo,13931 +pydantic/__pycache__/__init__.cpython-311.pyc,, +pydantic/__pycache__/_migration.cpython-311.pyc,, +pydantic/__pycache__/alias_generators.cpython-311.pyc,, +pydantic/__pycache__/aliases.cpython-311.pyc,, +pydantic/__pycache__/annotated_handlers.cpython-311.pyc,, +pydantic/__pycache__/class_validators.cpython-311.pyc,, +pydantic/__pycache__/color.cpython-311.pyc,, +pydantic/__pycache__/config.cpython-311.pyc,, +pydantic/__pycache__/dataclasses.cpython-311.pyc,, +pydantic/__pycache__/datetime_parse.cpython-311.pyc,, +pydantic/__pycache__/decorator.cpython-311.pyc,, +pydantic/__pycache__/env_settings.cpython-311.pyc,, +pydantic/__pycache__/error_wrappers.cpython-311.pyc,, +pydantic/__pycache__/errors.cpython-311.pyc,, +pydantic/__pycache__/fields.cpython-311.pyc,, +pydantic/__pycache__/functional_serializers.cpython-311.pyc,, +pydantic/__pycache__/functional_validators.cpython-311.pyc,, +pydantic/__pycache__/generics.cpython-311.pyc,, +pydantic/__pycache__/json.cpython-311.pyc,, +pydantic/__pycache__/json_schema.cpython-311.pyc,, +pydantic/__pycache__/main.cpython-311.pyc,, +pydantic/__pycache__/mypy.cpython-311.pyc,, +pydantic/__pycache__/networks.cpython-311.pyc,, +pydantic/__pycache__/parse.cpython-311.pyc,, +pydantic/__pycache__/root_model.cpython-311.pyc,, +pydantic/__pycache__/schema.cpython-311.pyc,, +pydantic/__pycache__/tools.cpython-311.pyc,, +pydantic/__pycache__/type_adapter.cpython-311.pyc,, +pydantic/__pycache__/types.cpython-311.pyc,, +pydantic/__pycache__/typing.cpython-311.pyc,, +pydantic/__pycache__/utils.cpython-311.pyc,, +pydantic/__pycache__/validate_call_decorator.cpython-311.pyc,, +pydantic/__pycache__/validators.cpython-311.pyc,, +pydantic/__pycache__/version.cpython-311.pyc,, +pydantic/__pycache__/warnings.cpython-311.pyc,, +pydantic/_internal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pydantic/_internal/__pycache__/__init__.cpython-311.pyc,, +pydantic/_internal/__pycache__/_config.cpython-311.pyc,, +pydantic/_internal/__pycache__/_core_metadata.cpython-311.pyc,, +pydantic/_internal/__pycache__/_core_utils.cpython-311.pyc,, +pydantic/_internal/__pycache__/_dataclasses.cpython-311.pyc,, +pydantic/_internal/__pycache__/_decorators.cpython-311.pyc,, +pydantic/_internal/__pycache__/_decorators_v1.cpython-311.pyc,, +pydantic/_internal/__pycache__/_discriminated_union.cpython-311.pyc,, +pydantic/_internal/__pycache__/_docs_extraction.cpython-311.pyc,, +pydantic/_internal/__pycache__/_fields.cpython-311.pyc,, +pydantic/_internal/__pycache__/_forward_ref.cpython-311.pyc,, +pydantic/_internal/__pycache__/_generate_schema.cpython-311.pyc,, +pydantic/_internal/__pycache__/_generics.cpython-311.pyc,, +pydantic/_internal/__pycache__/_git.cpython-311.pyc,, +pydantic/_internal/__pycache__/_internal_dataclass.cpython-311.pyc,, +pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-311.pyc,, +pydantic/_internal/__pycache__/_mock_val_ser.cpython-311.pyc,, +pydantic/_internal/__pycache__/_model_construction.cpython-311.pyc,, +pydantic/_internal/__pycache__/_repr.cpython-311.pyc,, +pydantic/_internal/__pycache__/_schema_generation_shared.cpython-311.pyc,, +pydantic/_internal/__pycache__/_signature.cpython-311.pyc,, +pydantic/_internal/__pycache__/_std_types_schema.cpython-311.pyc,, +pydantic/_internal/__pycache__/_typing_extra.cpython-311.pyc,, +pydantic/_internal/__pycache__/_utils.cpython-311.pyc,, +pydantic/_internal/__pycache__/_validate_call.cpython-311.pyc,, +pydantic/_internal/__pycache__/_validators.cpython-311.pyc,, +pydantic/_internal/_config.py,sha256=goVcoEMMsf2ltFE3WHTEiDvu6h5gPo01ZJ5h6PVQqrU,12605 +pydantic/_internal/_core_metadata.py,sha256=Da-e0-DXK__dJvog0e8CZLQ4r_k9RpldG6KQTGrYlHg,3521 +pydantic/_internal/_core_utils.py,sha256=6aD8J26n4_tP2R-Sermk66DGwHpFpksOrwHdI0O22jg,24268 +pydantic/_internal/_dataclasses.py,sha256=EvE43UHTVZZydVt8DjrkYLyciy5S46bXFgt8bsfWEWo,8733 +pydantic/_internal/_decorators.py,sha256=OnUIAbX_CTcHRXu4K5Qav8a5TC0YCXuwPq3bRiZQ04Y,31954 +pydantic/_internal/_decorators_v1.py,sha256=I7Px8gUMJod80_zBMlNkRVq0Mp2Z6mk1T1A4b_0a3Ps,6203 +pydantic/_internal/_discriminated_union.py,sha256=XDzlfKc7LAkJJErQWAZ4EuP_G_CQXJSVFKtwuHRJEmg,26435 +pydantic/_internal/_docs_extraction.py,sha256=bIWhw7nFKFt-qD-txtKRAb5VqGlAD0H9YzEEXE3PHj4,3791 +pydantic/_internal/_fields.py,sha256=_CCzAro7gGA3wsfUVDuRK9Tcrp-EMzH5ddyQ5JfgWQg,14934 +pydantic/_internal/_forward_ref.py,sha256=5n3Y7-3AKLn8_FS3Yc7KutLiPUhyXmAtkEZOaFnonwM,611 +pydantic/_internal/_generate_schema.py,sha256=JWt_d7_bQw_XaLzPAWV_Crvi_3N1N-usAt2lrUGj5BQ,105375 +pydantic/_internal/_generics.py,sha256=56zgcmvHOMQIXTn0r2aKfoFOvpBuFiWKfBu_dXnESig,22206 +pydantic/_internal/_git.py,sha256=lN6QlZm8RNSuNsUdHHC1F5a4VToe8vu5tlUxAfaJgGE,784 +pydantic/_internal/_internal_dataclass.py,sha256=_bedc1XbuuygRGiLZqkUkwwFpQaoR1hKLlR501nyySY,144 +pydantic/_internal/_known_annotated_metadata.py,sha256=qZDjQsw7bZiqzvzY_th2VLfG0KswT22twwYHp4QmE0s,14189 +pydantic/_internal/_mock_val_ser.py,sha256=g_RJhhodJOWnIrxwYRGNGA1v21eh5UrlfTP-7-ommMw,7315 +pydantic/_internal/_model_construction.py,sha256=nloFfqqBmPVomMYeefeEC_95tuTfq4jyDTW_iZfR-bo,31361 +pydantic/_internal/_repr.py,sha256=OxFN-gJMTefCv1yjsi5SRogstTMxRLhhTKCmR8jyJNU,4569 +pydantic/_internal/_schema_generation_shared.py,sha256=SB5kMqd9pzW9V4M4qjyI7R99MHzU1rfQVkNWP-KsiLM,4853 +pydantic/_internal/_signature.py,sha256=gJvpQ9vklQuYfYKI4d0zvHOGhCR44Oa_xltdMUMg59g,6293 +pydantic/_internal/_std_types_schema.py,sha256=3kvNnWRKmaB9RworxQoMaXRUHdMfSHV5bFz9AN6t6k8,28881 +pydantic/_internal/_typing_extra.py,sha256=9dD-4bReZ-FSBzjrvFKMY3aQXvEGcwOdcwClf5ypn84,19430 +pydantic/_internal/_utils.py,sha256=DM-CdDvaCd136ZFIJxvjgaNuaM6oYjYzif-nExcwL1k,12661 +pydantic/_internal/_validate_call.py,sha256=2kLSQjH1NB0d3PKv6JiujcqO8s7mKiyI5CvyOLcz6U0,3791 +pydantic/_internal/_validators.py,sha256=yi301I0sLQAfXWtq92jUwX2og1axVsXvDrR-psPu3Po,11118 +pydantic/_migration.py,sha256=j6TbRpJofjAX8lr-k2nVnQcBR9RD2B91I7Ulcw_ZzEo,11913 +pydantic/alias_generators.py,sha256=KM1n3u4JfLSBl1UuYg3hoYHzXJD-yvgrnq8u1ccwh_A,2124 +pydantic/aliases.py,sha256=X34YwPmkWSXTqaiVisRnxoPXcMbceeDZhMsMPxnOZyk,4819 +pydantic/annotated_handlers.py,sha256=yCeE8kQnLxZCWzT8f689hvwqqepEBW_byDUpVRJwnrM,4353 +pydantic/class_validators.py,sha256=i_V3j-PYdGLSLmj_IJZekTRjunO8SIVz8LMlquPyP7E,148 +pydantic/color.py,sha256=4GrtPvFCBKdM-1NpLVFOC7KkLejyZd1BiELfCKvT2yw,21494 +pydantic/config.py,sha256=9I5EyqzBKvFtlpoIxkrtMu2oxvYhENPaNBA532q2Ahc,35112 +pydantic/dataclasses.py,sha256=wEPHOsFGBjH2wsi2woff7SpwYm_2b_28-Yv-cYIvNOc,13909 +pydantic/datetime_parse.py,sha256=QC-WgMxMr_wQ_mNXUS7AVf-2hLEhvvsPY1PQyhSGOdk,150 +pydantic/decorator.py,sha256=YX-jUApu5AKaVWKPoaV-n-4l7UbS69GEt9Ra3hszmKI,145 +pydantic/deprecated/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pydantic/deprecated/__pycache__/__init__.cpython-311.pyc,, +pydantic/deprecated/__pycache__/class_validators.cpython-311.pyc,, +pydantic/deprecated/__pycache__/config.cpython-311.pyc,, +pydantic/deprecated/__pycache__/copy_internals.cpython-311.pyc,, +pydantic/deprecated/__pycache__/decorator.cpython-311.pyc,, +pydantic/deprecated/__pycache__/json.cpython-311.pyc,, +pydantic/deprecated/__pycache__/parse.cpython-311.pyc,, +pydantic/deprecated/__pycache__/tools.cpython-311.pyc,, +pydantic/deprecated/class_validators.py,sha256=Wt68ZLT5cQe_BwOsxNzlS9YRSxY1LrQ0XC0e9ejuv70,10254 +pydantic/deprecated/config.py,sha256=eKhnG--ZQtJ4A7KA3xeF76E15-4pVau3B5T8D39ptFs,2663 +pydantic/deprecated/copy_internals.py,sha256=SoUj1MevXt3fnloqNg5wivSUHSDPnuSj_YydzkEMzu0,7595 +pydantic/deprecated/decorator.py,sha256=P2V1bCwk8wNJ3g_s2p2ASFefXPLKn8bsUVw-Y8Wwcvk,10776 +pydantic/deprecated/json.py,sha256=Cn4f5r4JR3ondHQN-jpBSQC57nvnSNIbqXl3tcBcEx0,4596 +pydantic/deprecated/parse.py,sha256=Gzd6b_g8zJXcuE7QRq5adhx_EMJahXfcpXCF0RgrqqI,2511 +pydantic/deprecated/tools.py,sha256=XUoIW9W4sgOUWQ6Xzf-Z_NukUC1l_yUwz2_n0fE3MEI,3336 +pydantic/env_settings.py,sha256=6IHeeWEqlUPRUv3V-AXiF_W91fg2Jw_M3O0l34J_eyA,148 +pydantic/error_wrappers.py,sha256=RK6mqATc9yMD-KBD9IJS9HpKCprWHd8wo84Bnm-3fR8,150 +pydantic/errors.py,sha256=ht5bwtXWzq2DrwIVI7pU0tk9IAUjQjcVgPBULEXXMCk,4835 +pydantic/experimental/__init__.py,sha256=j08eROfz-xW4k_X9W4m2AW26IVdyF3Eg1OzlIGA11vk,328 +pydantic/experimental/__pycache__/__init__.cpython-311.pyc,, +pydantic/experimental/__pycache__/pipeline.cpython-311.pyc,, +pydantic/experimental/pipeline.py,sha256=PjiTnmaN5XwLUk-Nlzfr2C2R-xrMz7Nz-XVC8kiFGyU,23979 +pydantic/fields.py,sha256=zez1lSdoSZm3fN7AK3htTtqyt3iO7FIBf5aRVddRUC8,51746 +pydantic/functional_serializers.py,sha256=3RjQu_pxWaeesbJr1rwMgAUlO6wdTC8j_8CBh729b7A,14616 +pydantic/functional_validators.py,sha256=OKrL-nym0Me5bHou_BJCs9h-m2Gb-b3Asy58rJG-lkM,24224 +pydantic/generics.py,sha256=0ZqZ9O9annIj_3mGBRqps4htey3b5lV1-d2tUxPMMnA,144 +pydantic/json.py,sha256=ZH8RkI7h4Bz-zp8OdTAxbJUoVvcoU-jhMdRZ0B-k0xc,140 +pydantic/json_schema.py,sha256=A2GXiNigkfJb1yeRTteEaAWlJGteRSBlgQyHDfAk9x8,106297 +pydantic/main.py,sha256=zQVy0XYPN4-ve3qCCyxr8_6dbdmTSZYWtKWezwQXg1A,70106 +pydantic/mypy.py,sha256=diTpkBZ9hONAGyEU0npoPnVqf7rOleKCIoBHb-qqitQ,56972 +pydantic/networks.py,sha256=XjKPcKTDVGiCNTI_9B8iQKsO8xa9lfzkgUmvE0JIky4,22713 +pydantic/parse.py,sha256=wkd82dgtvWtD895U_I6E1htqMlGhBSYEV39cuBSeo3A,141 +pydantic/plugin/__init__.py,sha256=5pgHgEKA5kZXsaKhJYj2RdWZJ22nK1QAYojlcy2MxAs,6116 +pydantic/plugin/__pycache__/__init__.cpython-311.pyc,, +pydantic/plugin/__pycache__/_loader.cpython-311.pyc,, +pydantic/plugin/__pycache__/_schema_validator.cpython-311.pyc,, +pydantic/plugin/_loader.py,sha256=rmLbIwThDmVR1JwFVi_XvrLH7b1A5teMED-O3pr6Gk4,2140 +pydantic/plugin/_schema_validator.py,sha256=VFaNQpVNSuI2ymRDkTwBGaMKeKmySk1TbW-3rQeozxk,5240 +pydantic/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pydantic/root_model.py,sha256=54JLqe3_x5ZOEobsaMmNHBVPIpQy1tdW4tJnZGUI1pY,6194 +pydantic/schema.py,sha256=Vqqjvq_LnapVknebUd3Bp_J1p2gXZZnZRgL48bVEG7o,142 +pydantic/tools.py,sha256=iHQpd8SJ5DCTtPV5atAV06T89bjSaMFeZZ2LX9lasZY,141 +pydantic/type_adapter.py,sha256=-Jr6N3aPBbrOr_kSXuJEXHwoT6qsV6G8xZ9tWC74UgI,24974 +pydantic/types.py,sha256=wBUol6w4wcLtV0wLC0hre6ZdWseZSSZrRjf_R63Y_uY,95744 +pydantic/typing.py,sha256=P7feA35MwTcLsR1uL7db0S-oydBxobmXa55YDoBgajQ,138 +pydantic/utils.py,sha256=15nR2QpqTBFlQV4TNtTItMyTJx_fbyV-gPmIEY1Gooc,141 +pydantic/v1/__init__.py,sha256=SxQPklgBs4XHJwE6BZ9qoewYoGiNyYUnmHzEFCZbfnI,2946 +pydantic/v1/__pycache__/__init__.cpython-311.pyc,, +pydantic/v1/__pycache__/_hypothesis_plugin.cpython-311.pyc,, +pydantic/v1/__pycache__/annotated_types.cpython-311.pyc,, +pydantic/v1/__pycache__/class_validators.cpython-311.pyc,, +pydantic/v1/__pycache__/color.cpython-311.pyc,, +pydantic/v1/__pycache__/config.cpython-311.pyc,, +pydantic/v1/__pycache__/dataclasses.cpython-311.pyc,, +pydantic/v1/__pycache__/datetime_parse.cpython-311.pyc,, +pydantic/v1/__pycache__/decorator.cpython-311.pyc,, +pydantic/v1/__pycache__/env_settings.cpython-311.pyc,, +pydantic/v1/__pycache__/error_wrappers.cpython-311.pyc,, +pydantic/v1/__pycache__/errors.cpython-311.pyc,, +pydantic/v1/__pycache__/fields.cpython-311.pyc,, +pydantic/v1/__pycache__/generics.cpython-311.pyc,, +pydantic/v1/__pycache__/json.cpython-311.pyc,, +pydantic/v1/__pycache__/main.cpython-311.pyc,, +pydantic/v1/__pycache__/mypy.cpython-311.pyc,, +pydantic/v1/__pycache__/networks.cpython-311.pyc,, +pydantic/v1/__pycache__/parse.cpython-311.pyc,, +pydantic/v1/__pycache__/schema.cpython-311.pyc,, +pydantic/v1/__pycache__/tools.cpython-311.pyc,, +pydantic/v1/__pycache__/types.cpython-311.pyc,, +pydantic/v1/__pycache__/typing.cpython-311.pyc,, +pydantic/v1/__pycache__/utils.cpython-311.pyc,, +pydantic/v1/__pycache__/validators.cpython-311.pyc,, +pydantic/v1/__pycache__/version.cpython-311.pyc,, +pydantic/v1/_hypothesis_plugin.py,sha256=5ES5xWuw1FQAsymLezy8QgnVz0ZpVfU3jkmT74H27VQ,14847 +pydantic/v1/annotated_types.py,sha256=uk2NAAxqiNELKjiHhyhxKaIOh8F1lYW_LzrW3X7oZBc,3157 +pydantic/v1/class_validators.py,sha256=ULOaIUgYUDBsHL7EEVEarcM-UubKUggoN8hSbDonsFE,14672 +pydantic/v1/color.py,sha256=iZABLYp6OVoo2AFkP9Ipri_wSc6-Kklu8YuhSartd5g,16844 +pydantic/v1/config.py,sha256=a6P0Wer9x4cbwKW7Xv8poSUqM4WP-RLWwX6YMpYq9AA,6532 +pydantic/v1/dataclasses.py,sha256=784cqvInbwIPWr9usfpX3ch7z4t3J2tTK6N067_wk1o,18172 +pydantic/v1/datetime_parse.py,sha256=4Qy1kQpq3rNVZJeIHeSPDpuS2Bvhp1KPtzJG1xu-H00,7724 +pydantic/v1/decorator.py,sha256=zaaxxxoWPCm818D1bs0yhapRjXm32V8G0ZHWCdM1uXA,10339 +pydantic/v1/env_settings.py,sha256=A9VXwtRl02AY-jH0C0ouy5VNw3fi6F_pkzuHDjgAAOM,14105 +pydantic/v1/error_wrappers.py,sha256=6625Mfw9qkC2NwitB_JFAWe8B-Xv6zBU7rL9k28tfyo,5196 +pydantic/v1/errors.py,sha256=mIwPED5vGM5Q5v4C4Z1JPldTRH-omvEylH6ksMhOmPw,17726 +pydantic/v1/fields.py,sha256=VqWJCriUNiEyptXroDVJ501JpVA0en2VANcksqXL2b8,50649 +pydantic/v1/generics.py,sha256=VzC9YUV-EbPpQ3aAfk1cNFej79_IzznkQ7WrmTTZS9E,17871 +pydantic/v1/json.py,sha256=WQ5Hy_hIpfdR3YS8k6N2E6KMJzsdbBi_ldWOPJaV81M,3390 +pydantic/v1/main.py,sha256=A48ds4KJN4SgI34YLgPGqi6K3LhO7OwZ3QEy6GERiUc,44541 +pydantic/v1/mypy.py,sha256=kLQ7SHwisFxg0qb68clCLyoiwE6fl1TojeE6y-LY8I0,38774 +pydantic/v1/networks.py,sha256=HYNtKAfOmOnKJpsDg1g6SIkj9WPhU_-i8l5e2JKBpG4,22124 +pydantic/v1/parse.py,sha256=BJtdqiZRtav9VRFCmOxoY-KImQmjPy-A_NoojiFUZxY,1821 +pydantic/v1/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +pydantic/v1/schema.py,sha256=JLnq9550F6qx9imoZbc5mJvMMTqqU4ju-5rX5Qg23qQ,47760 +pydantic/v1/tools.py,sha256=1lDdXHk0jL5uP3u5RCYAvUAlGClgAO-45lkq9j7fyBA,2881 +pydantic/v1/types.py,sha256=Fltx5GoP_qaUmAktlGz7nFeJa13yNy3FY1-RcMzEVt8,35455 +pydantic/v1/typing.py,sha256=GjThObaqHMhLaECzYUrDk0X-RHjo7x6vsv4Z4qUYV8I,19387 +pydantic/v1/utils.py,sha256=fjlWL8SStFZj0w3sbfuOVfDITK1vdFfZ5pcgml9Kq7k,25919 +pydantic/v1/validators.py,sha256=Dxcx36zVQjBUfYdjQLs_E0qpYqTeNbrF8PQTcasYgrI,21996 +pydantic/v1/version.py,sha256=DFN4uMBemx_gHk_6i1SK0oMa3VMe9G_wLFyw6KInipg,1039 +pydantic/validate_call_decorator.py,sha256=jj1T9Yz9_sQMhBjBmUn9sv7YK9dyLXJm5podxxsbDfI,2127 +pydantic/validators.py,sha256=pwbIJXVb1CV2mAE4w_EGfNj7DwzsKaWw_tTL6cviTus,146 +pydantic/version.py,sha256=5udPEl9gYDPmqid2QS91qnZNBhLyo6-KHTl_tXkPMv0,2442 +pydantic/warnings.py,sha256=7f5TxYmLkZOCMPb2uGLlJCE6uAGd4XF0qea6n-hv-ys,2711 diff --git a/env/Lib/site-packages/pydantic-2.8.2.dist-info/WHEEL b/env/Lib/site-packages/pydantic-2.8.2.dist-info/WHEEL new file mode 100644 index 0000000..cdd68a4 --- /dev/null +++ b/env/Lib/site-packages/pydantic-2.8.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.25.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/env/Lib/site-packages/pydantic-2.8.2.dist-info/licenses/LICENSE b/env/Lib/site-packages/pydantic-2.8.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000..488c626 --- /dev/null +++ b/env/Lib/site-packages/pydantic-2.8.2.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 to present Pydantic Services Inc. and individual contributors. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/env/Lib/site-packages/pydantic/__init__.py b/env/Lib/site-packages/pydantic/__init__.py new file mode 100644 index 0000000..2dcb91c --- /dev/null +++ b/env/Lib/site-packages/pydantic/__init__.py @@ -0,0 +1,409 @@ +import typing + +from ._migration import getattr_migration +from .version import VERSION + +if typing.TYPE_CHECKING: + # import of virtually everything is supported via `__getattr__` below, + # but we need them here for type checking and IDE support + import pydantic_core + from pydantic_core.core_schema import ( + FieldSerializationInfo, + SerializationInfo, + SerializerFunctionWrapHandler, + ValidationInfo, + ValidatorFunctionWrapHandler, + ) + + from . import dataclasses + from ._internal._generate_schema import GenerateSchema as GenerateSchema + from .aliases import AliasChoices, AliasGenerator, AliasPath + from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler + from .config import ConfigDict, with_config + from .errors import * + from .fields import Field, PrivateAttr, computed_field + from .functional_serializers import ( + PlainSerializer, + SerializeAsAny, + WrapSerializer, + field_serializer, + model_serializer, + ) + from .functional_validators import ( + AfterValidator, + BeforeValidator, + InstanceOf, + PlainValidator, + SkipValidation, + WrapValidator, + field_validator, + model_validator, + ) + from .json_schema import WithJsonSchema + from .main import * + from .networks import * + from .type_adapter import TypeAdapter + from .types import * + from .validate_call_decorator import validate_call + from .warnings import ( + PydanticDeprecatedSince20, + PydanticDeprecatedSince26, + PydanticDeprecationWarning, + PydanticExperimentalWarning, + ) + + # this encourages pycharm to import `ValidationError` from here, not pydantic_core + ValidationError = pydantic_core.ValidationError + from .deprecated.class_validators import root_validator, validator + from .deprecated.config import BaseConfig, Extra + from .deprecated.tools import * + from .root_model import RootModel + +__version__ = VERSION +__all__ = ( + # dataclasses + 'dataclasses', + # functional validators + 'field_validator', + 'model_validator', + 'AfterValidator', + 'BeforeValidator', + 'PlainValidator', + 'WrapValidator', + 'SkipValidation', + 'InstanceOf', + # JSON Schema + 'WithJsonSchema', + # deprecated V1 functional validators, these are imported via `__getattr__` below + 'root_validator', + 'validator', + # functional serializers + 'field_serializer', + 'model_serializer', + 'PlainSerializer', + 'SerializeAsAny', + 'WrapSerializer', + # config + 'ConfigDict', + 'with_config', + # deprecated V1 config, these are imported via `__getattr__` below + 'BaseConfig', + 'Extra', + # validate_call + 'validate_call', + # errors + 'PydanticErrorCodes', + 'PydanticUserError', + 'PydanticSchemaGenerationError', + 'PydanticImportError', + 'PydanticUndefinedAnnotation', + 'PydanticInvalidForJsonSchema', + # fields + 'Field', + 'computed_field', + 'PrivateAttr', + # alias + 'AliasChoices', + 'AliasGenerator', + 'AliasPath', + # main + 'BaseModel', + 'create_model', + # network + 'AnyUrl', + 'AnyHttpUrl', + 'FileUrl', + 'HttpUrl', + 'FtpUrl', + 'WebsocketUrl', + 'AnyWebsocketUrl', + 'UrlConstraints', + 'EmailStr', + 'NameEmail', + 'IPvAnyAddress', + 'IPvAnyInterface', + 'IPvAnyNetwork', + 'PostgresDsn', + 'CockroachDsn', + 'AmqpDsn', + 'RedisDsn', + 'MongoDsn', + 'KafkaDsn', + 'NatsDsn', + 'MySQLDsn', + 'MariaDBDsn', + 'ClickHouseDsn', + 'validate_email', + # root_model + 'RootModel', + # deprecated tools, these are imported via `__getattr__` below + 'parse_obj_as', + 'schema_of', + 'schema_json_of', + # types + 'Strict', + 'StrictStr', + 'conbytes', + 'conlist', + 'conset', + 'confrozenset', + 'constr', + 'StringConstraints', + 'ImportString', + 'conint', + 'PositiveInt', + 'NegativeInt', + 'NonNegativeInt', + 'NonPositiveInt', + 'confloat', + 'PositiveFloat', + 'NegativeFloat', + 'NonNegativeFloat', + 'NonPositiveFloat', + 'FiniteFloat', + 'condecimal', + 'condate', + 'UUID1', + 'UUID3', + 'UUID4', + 'UUID5', + 'FilePath', + 'DirectoryPath', + 'NewPath', + 'Json', + 'Secret', + 'SecretStr', + 'SecretBytes', + 'StrictBool', + 'StrictBytes', + 'StrictInt', + 'StrictFloat', + 'PaymentCardNumber', + 'ByteSize', + 'PastDate', + 'FutureDate', + 'PastDatetime', + 'FutureDatetime', + 'AwareDatetime', + 'NaiveDatetime', + 'AllowInfNan', + 'EncoderProtocol', + 'EncodedBytes', + 'EncodedStr', + 'Base64Encoder', + 'Base64Bytes', + 'Base64Str', + 'Base64UrlBytes', + 'Base64UrlStr', + 'GetPydanticSchema', + 'Tag', + 'Discriminator', + 'JsonValue', + 'FailFast', + # type_adapter + 'TypeAdapter', + # version + '__version__', + 'VERSION', + # warnings + 'PydanticDeprecatedSince20', + 'PydanticDeprecatedSince26', + 'PydanticDeprecationWarning', + 'PydanticExperimentalWarning', + # annotated handlers + 'GetCoreSchemaHandler', + 'GetJsonSchemaHandler', + # generate schema from ._internal + 'GenerateSchema', + # pydantic_core + 'ValidationError', + 'ValidationInfo', + 'SerializationInfo', + 'ValidatorFunctionWrapHandler', + 'FieldSerializationInfo', + 'SerializerFunctionWrapHandler', + 'OnErrorOmit', +) + +# A mapping of {: (package, )} defining dynamic imports +_dynamic_imports: 'dict[str, tuple[str, str]]' = { + 'dataclasses': (__spec__.parent, '__module__'), + # functional validators + 'field_validator': (__spec__.parent, '.functional_validators'), + 'model_validator': (__spec__.parent, '.functional_validators'), + 'AfterValidator': (__spec__.parent, '.functional_validators'), + 'BeforeValidator': (__spec__.parent, '.functional_validators'), + 'PlainValidator': (__spec__.parent, '.functional_validators'), + 'WrapValidator': (__spec__.parent, '.functional_validators'), + 'SkipValidation': (__spec__.parent, '.functional_validators'), + 'InstanceOf': (__spec__.parent, '.functional_validators'), + # JSON Schema + 'WithJsonSchema': (__spec__.parent, '.json_schema'), + # functional serializers + 'field_serializer': (__spec__.parent, '.functional_serializers'), + 'model_serializer': (__spec__.parent, '.functional_serializers'), + 'PlainSerializer': (__spec__.parent, '.functional_serializers'), + 'SerializeAsAny': (__spec__.parent, '.functional_serializers'), + 'WrapSerializer': (__spec__.parent, '.functional_serializers'), + # config + 'ConfigDict': (__spec__.parent, '.config'), + 'with_config': (__spec__.parent, '.config'), + # validate call + 'validate_call': (__spec__.parent, '.validate_call_decorator'), + # errors + 'PydanticErrorCodes': (__spec__.parent, '.errors'), + 'PydanticUserError': (__spec__.parent, '.errors'), + 'PydanticSchemaGenerationError': (__spec__.parent, '.errors'), + 'PydanticImportError': (__spec__.parent, '.errors'), + 'PydanticUndefinedAnnotation': (__spec__.parent, '.errors'), + 'PydanticInvalidForJsonSchema': (__spec__.parent, '.errors'), + # fields + 'Field': (__spec__.parent, '.fields'), + 'computed_field': (__spec__.parent, '.fields'), + 'PrivateAttr': (__spec__.parent, '.fields'), + # alias + 'AliasChoices': (__spec__.parent, '.aliases'), + 'AliasGenerator': (__spec__.parent, '.aliases'), + 'AliasPath': (__spec__.parent, '.aliases'), + # main + 'BaseModel': (__spec__.parent, '.main'), + 'create_model': (__spec__.parent, '.main'), + # network + 'AnyUrl': (__spec__.parent, '.networks'), + 'AnyHttpUrl': (__spec__.parent, '.networks'), + 'FileUrl': (__spec__.parent, '.networks'), + 'HttpUrl': (__spec__.parent, '.networks'), + 'FtpUrl': (__spec__.parent, '.networks'), + 'WebsocketUrl': (__spec__.parent, '.networks'), + 'AnyWebsocketUrl': (__spec__.parent, '.networks'), + 'UrlConstraints': (__spec__.parent, '.networks'), + 'EmailStr': (__spec__.parent, '.networks'), + 'NameEmail': (__spec__.parent, '.networks'), + 'IPvAnyAddress': (__spec__.parent, '.networks'), + 'IPvAnyInterface': (__spec__.parent, '.networks'), + 'IPvAnyNetwork': (__spec__.parent, '.networks'), + 'PostgresDsn': (__spec__.parent, '.networks'), + 'CockroachDsn': (__spec__.parent, '.networks'), + 'AmqpDsn': (__spec__.parent, '.networks'), + 'RedisDsn': (__spec__.parent, '.networks'), + 'MongoDsn': (__spec__.parent, '.networks'), + 'KafkaDsn': (__spec__.parent, '.networks'), + 'NatsDsn': (__spec__.parent, '.networks'), + 'MySQLDsn': (__spec__.parent, '.networks'), + 'MariaDBDsn': (__spec__.parent, '.networks'), + 'ClickHouseDsn': (__spec__.parent, '.networks'), + 'validate_email': (__spec__.parent, '.networks'), + # root_model + 'RootModel': (__spec__.parent, '.root_model'), + # types + 'Strict': (__spec__.parent, '.types'), + 'StrictStr': (__spec__.parent, '.types'), + 'conbytes': (__spec__.parent, '.types'), + 'conlist': (__spec__.parent, '.types'), + 'conset': (__spec__.parent, '.types'), + 'confrozenset': (__spec__.parent, '.types'), + 'constr': (__spec__.parent, '.types'), + 'StringConstraints': (__spec__.parent, '.types'), + 'ImportString': (__spec__.parent, '.types'), + 'conint': (__spec__.parent, '.types'), + 'PositiveInt': (__spec__.parent, '.types'), + 'NegativeInt': (__spec__.parent, '.types'), + 'NonNegativeInt': (__spec__.parent, '.types'), + 'NonPositiveInt': (__spec__.parent, '.types'), + 'confloat': (__spec__.parent, '.types'), + 'PositiveFloat': (__spec__.parent, '.types'), + 'NegativeFloat': (__spec__.parent, '.types'), + 'NonNegativeFloat': (__spec__.parent, '.types'), + 'NonPositiveFloat': (__spec__.parent, '.types'), + 'FiniteFloat': (__spec__.parent, '.types'), + 'condecimal': (__spec__.parent, '.types'), + 'condate': (__spec__.parent, '.types'), + 'UUID1': (__spec__.parent, '.types'), + 'UUID3': (__spec__.parent, '.types'), + 'UUID4': (__spec__.parent, '.types'), + 'UUID5': (__spec__.parent, '.types'), + 'FilePath': (__spec__.parent, '.types'), + 'DirectoryPath': (__spec__.parent, '.types'), + 'NewPath': (__spec__.parent, '.types'), + 'Json': (__spec__.parent, '.types'), + 'Secret': (__spec__.parent, '.types'), + 'SecretStr': (__spec__.parent, '.types'), + 'SecretBytes': (__spec__.parent, '.types'), + 'StrictBool': (__spec__.parent, '.types'), + 'StrictBytes': (__spec__.parent, '.types'), + 'StrictInt': (__spec__.parent, '.types'), + 'StrictFloat': (__spec__.parent, '.types'), + 'PaymentCardNumber': (__spec__.parent, '.types'), + 'ByteSize': (__spec__.parent, '.types'), + 'PastDate': (__spec__.parent, '.types'), + 'FutureDate': (__spec__.parent, '.types'), + 'PastDatetime': (__spec__.parent, '.types'), + 'FutureDatetime': (__spec__.parent, '.types'), + 'AwareDatetime': (__spec__.parent, '.types'), + 'NaiveDatetime': (__spec__.parent, '.types'), + 'AllowInfNan': (__spec__.parent, '.types'), + 'EncoderProtocol': (__spec__.parent, '.types'), + 'EncodedBytes': (__spec__.parent, '.types'), + 'EncodedStr': (__spec__.parent, '.types'), + 'Base64Encoder': (__spec__.parent, '.types'), + 'Base64Bytes': (__spec__.parent, '.types'), + 'Base64Str': (__spec__.parent, '.types'), + 'Base64UrlBytes': (__spec__.parent, '.types'), + 'Base64UrlStr': (__spec__.parent, '.types'), + 'GetPydanticSchema': (__spec__.parent, '.types'), + 'Tag': (__spec__.parent, '.types'), + 'Discriminator': (__spec__.parent, '.types'), + 'JsonValue': (__spec__.parent, '.types'), + 'OnErrorOmit': (__spec__.parent, '.types'), + 'FailFast': (__spec__.parent, '.types'), + # type_adapter + 'TypeAdapter': (__spec__.parent, '.type_adapter'), + # warnings + 'PydanticDeprecatedSince20': (__spec__.parent, '.warnings'), + 'PydanticDeprecatedSince26': (__spec__.parent, '.warnings'), + 'PydanticDeprecationWarning': (__spec__.parent, '.warnings'), + 'PydanticExperimentalWarning': (__spec__.parent, '.warnings'), + # annotated handlers + 'GetCoreSchemaHandler': (__spec__.parent, '.annotated_handlers'), + 'GetJsonSchemaHandler': (__spec__.parent, '.annotated_handlers'), + # generate schema from ._internal + 'GenerateSchema': (__spec__.parent, '._internal._generate_schema'), + # pydantic_core stuff + 'ValidationError': ('pydantic_core', '.'), + 'ValidationInfo': ('pydantic_core', '.core_schema'), + 'SerializationInfo': ('pydantic_core', '.core_schema'), + 'ValidatorFunctionWrapHandler': ('pydantic_core', '.core_schema'), + 'FieldSerializationInfo': ('pydantic_core', '.core_schema'), + 'SerializerFunctionWrapHandler': ('pydantic_core', '.core_schema'), + # deprecated, mostly not included in __all__ + 'root_validator': (__spec__.parent, '.deprecated.class_validators'), + 'validator': (__spec__.parent, '.deprecated.class_validators'), + 'BaseConfig': (__spec__.parent, '.deprecated.config'), + 'Extra': (__spec__.parent, '.deprecated.config'), + 'parse_obj_as': (__spec__.parent, '.deprecated.tools'), + 'schema_of': (__spec__.parent, '.deprecated.tools'), + 'schema_json_of': (__spec__.parent, '.deprecated.tools'), + 'FieldValidationInfo': ('pydantic_core', '.core_schema'), +} + +_getattr_migration = getattr_migration(__name__) + + +def __getattr__(attr_name: str) -> object: + dynamic_attr = _dynamic_imports.get(attr_name) + if dynamic_attr is None: + return _getattr_migration(attr_name) + + package, module_name = dynamic_attr + + from importlib import import_module + + if module_name == '__module__': + return import_module(f'.{attr_name}', package=package) + else: + module = import_module(module_name, package=package) + return getattr(module, attr_name) + + +def __dir__() -> 'list[str]': + return list(__all__) diff --git a/env/Lib/site-packages/pydantic/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..e3159ca Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/_migration.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/_migration.cpython-311.pyc new file mode 100644 index 0000000..27b4117 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/_migration.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/alias_generators.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/alias_generators.cpython-311.pyc new file mode 100644 index 0000000..77f7cb0 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/alias_generators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/aliases.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/aliases.cpython-311.pyc new file mode 100644 index 0000000..296b5c8 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/aliases.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-311.pyc new file mode 100644 index 0000000..e76495f Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/annotated_handlers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/class_validators.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/class_validators.cpython-311.pyc new file mode 100644 index 0000000..1d46726 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/class_validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/color.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/color.cpython-311.pyc new file mode 100644 index 0000000..c2e59de Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/color.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/config.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000..15249f3 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/config.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/dataclasses.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/dataclasses.cpython-311.pyc new file mode 100644 index 0000000..33a5798 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/dataclasses.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/datetime_parse.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/datetime_parse.cpython-311.pyc new file mode 100644 index 0000000..ff76ad5 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/datetime_parse.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/decorator.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/decorator.cpython-311.pyc new file mode 100644 index 0000000..7dedd6e Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/decorator.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/env_settings.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/env_settings.cpython-311.pyc new file mode 100644 index 0000000..a219138 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/env_settings.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/error_wrappers.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/error_wrappers.cpython-311.pyc new file mode 100644 index 0000000..9f30d11 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/error_wrappers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/errors.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000..c847353 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/errors.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/fields.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/fields.cpython-311.pyc new file mode 100644 index 0000000..220ccc6 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/fields.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/functional_serializers.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/functional_serializers.cpython-311.pyc new file mode 100644 index 0000000..5b067d1 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/functional_serializers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/functional_validators.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/functional_validators.cpython-311.pyc new file mode 100644 index 0000000..f47f97d Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/functional_validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/generics.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/generics.cpython-311.pyc new file mode 100644 index 0000000..0e17d85 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/generics.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/json.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/json.cpython-311.pyc new file mode 100644 index 0000000..3a7a441 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/json.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/json_schema.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/json_schema.cpython-311.pyc new file mode 100644 index 0000000..68cac8f Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/json_schema.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/main.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000..b448b12 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/main.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/mypy.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/mypy.cpython-311.pyc new file mode 100644 index 0000000..161cef8 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/mypy.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/networks.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/networks.cpython-311.pyc new file mode 100644 index 0000000..053fd68 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/networks.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/parse.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/parse.cpython-311.pyc new file mode 100644 index 0000000..7584ca7 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/parse.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/root_model.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/root_model.cpython-311.pyc new file mode 100644 index 0000000..6a5209b Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/root_model.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/schema.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/schema.cpython-311.pyc new file mode 100644 index 0000000..fde4318 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/schema.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/tools.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/tools.cpython-311.pyc new file mode 100644 index 0000000..7e64ab2 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/tools.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/type_adapter.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/type_adapter.cpython-311.pyc new file mode 100644 index 0000000..90f11e8 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/type_adapter.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/types.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000..4344131 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/types.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/typing.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/typing.cpython-311.pyc new file mode 100644 index 0000000..075d97e Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/typing.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/utils.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000..536ad04 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/validate_call_decorator.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/validate_call_decorator.cpython-311.pyc new file mode 100644 index 0000000..df4873f Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/validate_call_decorator.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/validators.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/validators.cpython-311.pyc new file mode 100644 index 0000000..9fff91a Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/version.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000..ebbfb0f Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/version.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/__pycache__/warnings.cpython-311.pyc b/env/Lib/site-packages/pydantic/__pycache__/warnings.cpython-311.pyc new file mode 100644 index 0000000..aa7a3d2 Binary files /dev/null and b/env/Lib/site-packages/pydantic/__pycache__/warnings.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__init__.py b/env/Lib/site-packages/pydantic/_internal/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..8174f80 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_config.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_config.cpython-311.pyc new file mode 100644 index 0000000..65cd850 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_config.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-311.pyc new file mode 100644 index 0000000..b5097b8 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_core_metadata.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-311.pyc new file mode 100644 index 0000000..a9af42e Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_core_utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_dataclasses.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_dataclasses.cpython-311.pyc new file mode 100644 index 0000000..5e8cefd Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_dataclasses.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-311.pyc new file mode 100644 index 0000000..735f440 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_decorators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_decorators_v1.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_decorators_v1.cpython-311.pyc new file mode 100644 index 0000000..390bb63 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_decorators_v1.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-311.pyc new file mode 100644 index 0000000..a98d204 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_discriminated_union.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-311.pyc new file mode 100644 index 0000000..f1b05b5 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_docs_extraction.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_fields.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_fields.cpython-311.pyc new file mode 100644 index 0000000..20c1319 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_fields.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-311.pyc new file mode 100644 index 0000000..43b9ba6 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_forward_ref.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_generate_schema.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_generate_schema.cpython-311.pyc new file mode 100644 index 0000000..31dc4ad Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_generate_schema.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_generics.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_generics.cpython-311.pyc new file mode 100644 index 0000000..e6ea29e Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_generics.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_git.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_git.cpython-311.pyc new file mode 100644 index 0000000..7d88b32 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_git.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_internal_dataclass.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_internal_dataclass.cpython-311.pyc new file mode 100644 index 0000000..95d9d41 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_internal_dataclass.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-311.pyc new file mode 100644 index 0000000..3f82572 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_known_annotated_metadata.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-311.pyc new file mode 100644 index 0000000..afcff11 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_mock_val_ser.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-311.pyc new file mode 100644 index 0000000..5bd6a80 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_model_construction.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_repr.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_repr.cpython-311.pyc new file mode 100644 index 0000000..2007d01 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_repr.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_schema_generation_shared.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_schema_generation_shared.cpython-311.pyc new file mode 100644 index 0000000..53283b7 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_schema_generation_shared.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_signature.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_signature.cpython-311.pyc new file mode 100644 index 0000000..5448aee Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_signature.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_std_types_schema.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_std_types_schema.cpython-311.pyc new file mode 100644 index 0000000..e52cf81 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_std_types_schema.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-311.pyc new file mode 100644 index 0000000..6bf08d8 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_typing_extra.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_utils.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_utils.cpython-311.pyc new file mode 100644 index 0000000..931d4b0 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_validate_call.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_validate_call.cpython-311.pyc new file mode 100644 index 0000000..1f4c723 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_validate_call.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/__pycache__/_validators.cpython-311.pyc b/env/Lib/site-packages/pydantic/_internal/__pycache__/_validators.cpython-311.pyc new file mode 100644 index 0000000..5e2c2d5 Binary files /dev/null and b/env/Lib/site-packages/pydantic/_internal/__pycache__/_validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/_internal/_config.py b/env/Lib/site-packages/pydantic/_internal/_config.py new file mode 100644 index 0000000..d27e3bb --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_config.py @@ -0,0 +1,341 @@ +from __future__ import annotations as _annotations + +import warnings +from contextlib import contextmanager +from typing import ( + TYPE_CHECKING, + Any, + Callable, + cast, +) + +from pydantic_core import core_schema +from typing_extensions import ( + Literal, + Self, +) + +from ..aliases import AliasGenerator +from ..config import ConfigDict, ExtraValues, JsonDict, JsonEncoder, JsonSchemaExtraCallable +from ..errors import PydanticUserError +from ..warnings import PydanticDeprecatedSince20 + +if not TYPE_CHECKING: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + +if TYPE_CHECKING: + from .._internal._schema_generation_shared import GenerateSchema + from ..fields import ComputedFieldInfo, FieldInfo + +DEPRECATION_MESSAGE = 'Support for class-based `config` is deprecated, use ConfigDict instead.' + + +class ConfigWrapper: + """Internal wrapper for Config which exposes ConfigDict items as attributes.""" + + __slots__ = ('config_dict',) + + config_dict: ConfigDict + + # all annotations are copied directly from ConfigDict, and should be kept up to date, a test will fail if they + # stop matching + title: str | None + str_to_lower: bool + str_to_upper: bool + str_strip_whitespace: bool + str_min_length: int + str_max_length: int | None + extra: ExtraValues | None + frozen: bool + populate_by_name: bool + use_enum_values: bool + validate_assignment: bool + arbitrary_types_allowed: bool + from_attributes: bool + # whether to use the actual key provided in the data (e.g. alias or first alias for "field required" errors) instead of field_names + # to construct error `loc`s, default `True` + loc_by_alias: bool + alias_generator: Callable[[str], str] | AliasGenerator | None + model_title_generator: Callable[[type], str] | None + field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None + ignored_types: tuple[type, ...] + allow_inf_nan: bool + json_schema_extra: JsonDict | JsonSchemaExtraCallable | None + json_encoders: dict[type[object], JsonEncoder] | None + + # new in V2 + strict: bool + # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never' + revalidate_instances: Literal['always', 'never', 'subclass-instances'] + ser_json_timedelta: Literal['iso8601', 'float'] + ser_json_bytes: Literal['utf8', 'base64'] + ser_json_inf_nan: Literal['null', 'constants', 'strings'] + # whether to validate default values during validation, default False + validate_default: bool + validate_return: bool + protected_namespaces: tuple[str, ...] + hide_input_in_errors: bool + defer_build: bool + experimental_defer_build_mode: tuple[Literal['model', 'type_adapter'], ...] + plugin_settings: dict[str, object] | None + schema_generator: type[GenerateSchema] | None + json_schema_serialization_defaults_required: bool + json_schema_mode_override: Literal['validation', 'serialization', None] + coerce_numbers_to_str: bool + regex_engine: Literal['rust-regex', 'python-re'] + validation_error_cause: bool + use_attribute_docstrings: bool + cache_strings: bool | Literal['all', 'keys', 'none'] + + def __init__(self, config: ConfigDict | dict[str, Any] | type[Any] | None, *, check: bool = True): + if check: + self.config_dict = prepare_config(config) + else: + self.config_dict = cast(ConfigDict, config) + + @classmethod + def for_model(cls, bases: tuple[type[Any], ...], namespace: dict[str, Any], kwargs: dict[str, Any]) -> Self: + """Build a new `ConfigWrapper` instance for a `BaseModel`. + + The config wrapper built based on (in descending order of priority): + - options from `kwargs` + - options from the `namespace` + - options from the base classes (`bases`) + + Args: + bases: A tuple of base classes. + namespace: The namespace of the class being created. + kwargs: The kwargs passed to the class being created. + + Returns: + A `ConfigWrapper` instance for `BaseModel`. + """ + config_new = ConfigDict() + for base in bases: + config = getattr(base, 'model_config', None) + if config: + config_new.update(config.copy()) + + config_class_from_namespace = namespace.get('Config') + config_dict_from_namespace = namespace.get('model_config') + + raw_annotations = namespace.get('__annotations__', {}) + if raw_annotations.get('model_config') and not config_dict_from_namespace: + raise PydanticUserError( + '`model_config` cannot be used as a model field name. Use `model_config` for model configuration.', + code='model-config-invalid-field-name', + ) + + if config_class_from_namespace and config_dict_from_namespace: + raise PydanticUserError('"Config" and "model_config" cannot be used together', code='config-both') + + config_from_namespace = config_dict_from_namespace or prepare_config(config_class_from_namespace) + + config_new.update(config_from_namespace) + + for k in list(kwargs.keys()): + if k in config_keys: + config_new[k] = kwargs.pop(k) + + return cls(config_new) + + # we don't show `__getattr__` to type checkers so missing attributes cause errors + if not TYPE_CHECKING: # pragma: no branch + + def __getattr__(self, name: str) -> Any: + try: + return self.config_dict[name] + except KeyError: + try: + return config_defaults[name] + except KeyError: + raise AttributeError(f'Config has no attribute {name!r}') from None + + def core_config(self, obj: Any) -> core_schema.CoreConfig: + """Create a pydantic-core config, `obj` is just used to populate `title` if not set in config. + + Pass `obj=None` if you do not want to attempt to infer the `title`. + + We don't use getattr here since we don't want to populate with defaults. + + Args: + obj: An object used to populate `title` if not set in config. + + Returns: + A `CoreConfig` object created from config. + """ + + def dict_not_none(**kwargs: Any) -> Any: + return {k: v for k, v in kwargs.items() if v is not None} + + core_config = core_schema.CoreConfig( + **dict_not_none( + title=self.config_dict.get('title') or (obj and obj.__name__), + extra_fields_behavior=self.config_dict.get('extra'), + allow_inf_nan=self.config_dict.get('allow_inf_nan'), + populate_by_name=self.config_dict.get('populate_by_name'), + str_strip_whitespace=self.config_dict.get('str_strip_whitespace'), + str_to_lower=self.config_dict.get('str_to_lower'), + str_to_upper=self.config_dict.get('str_to_upper'), + strict=self.config_dict.get('strict'), + ser_json_timedelta=self.config_dict.get('ser_json_timedelta'), + ser_json_bytes=self.config_dict.get('ser_json_bytes'), + ser_json_inf_nan=self.config_dict.get('ser_json_inf_nan'), + from_attributes=self.config_dict.get('from_attributes'), + loc_by_alias=self.config_dict.get('loc_by_alias'), + revalidate_instances=self.config_dict.get('revalidate_instances'), + validate_default=self.config_dict.get('validate_default'), + str_max_length=self.config_dict.get('str_max_length'), + str_min_length=self.config_dict.get('str_min_length'), + hide_input_in_errors=self.config_dict.get('hide_input_in_errors'), + coerce_numbers_to_str=self.config_dict.get('coerce_numbers_to_str'), + regex_engine=self.config_dict.get('regex_engine'), + validation_error_cause=self.config_dict.get('validation_error_cause'), + cache_strings=self.config_dict.get('cache_strings'), + ) + ) + return core_config + + def __repr__(self): + c = ', '.join(f'{k}={v!r}' for k, v in self.config_dict.items()) + return f'ConfigWrapper({c})' + + +class ConfigWrapperStack: + """A stack of `ConfigWrapper` instances.""" + + def __init__(self, config_wrapper: ConfigWrapper): + self._config_wrapper_stack: list[ConfigWrapper] = [config_wrapper] + + @property + def tail(self) -> ConfigWrapper: + return self._config_wrapper_stack[-1] + + @contextmanager + def push(self, config_wrapper: ConfigWrapper | ConfigDict | None): + if config_wrapper is None: + yield + return + + if not isinstance(config_wrapper, ConfigWrapper): + config_wrapper = ConfigWrapper(config_wrapper, check=False) + + self._config_wrapper_stack.append(config_wrapper) + try: + yield + finally: + self._config_wrapper_stack.pop() + + +config_defaults = ConfigDict( + title=None, + str_to_lower=False, + str_to_upper=False, + str_strip_whitespace=False, + str_min_length=0, + str_max_length=None, + # let the model / dataclass decide how to handle it + extra=None, + frozen=False, + populate_by_name=False, + use_enum_values=False, + validate_assignment=False, + arbitrary_types_allowed=False, + from_attributes=False, + loc_by_alias=True, + alias_generator=None, + model_title_generator=None, + field_title_generator=None, + ignored_types=(), + allow_inf_nan=True, + json_schema_extra=None, + strict=False, + revalidate_instances='never', + ser_json_timedelta='iso8601', + ser_json_bytes='utf8', + ser_json_inf_nan='null', + validate_default=False, + validate_return=False, + protected_namespaces=('model_',), + hide_input_in_errors=False, + json_encoders=None, + defer_build=False, + experimental_defer_build_mode=('model',), + plugin_settings=None, + schema_generator=None, + json_schema_serialization_defaults_required=False, + json_schema_mode_override=None, + coerce_numbers_to_str=False, + regex_engine='rust-regex', + validation_error_cause=False, + use_attribute_docstrings=False, + cache_strings=True, +) + + +def prepare_config(config: ConfigDict | dict[str, Any] | type[Any] | None) -> ConfigDict: + """Create a `ConfigDict` instance from an existing dict, a class (e.g. old class-based config) or None. + + Args: + config: The input config. + + Returns: + A ConfigDict object created from config. + """ + if config is None: + return ConfigDict() + + if not isinstance(config, dict): + warnings.warn(DEPRECATION_MESSAGE, DeprecationWarning) + config = {k: getattr(config, k) for k in dir(config) if not k.startswith('__')} + + config_dict = cast(ConfigDict, config) + check_deprecated(config_dict) + return config_dict + + +config_keys = set(ConfigDict.__annotations__.keys()) + + +V2_REMOVED_KEYS = { + 'allow_mutation', + 'error_msg_templates', + 'fields', + 'getter_dict', + 'smart_union', + 'underscore_attrs_are_private', + 'json_loads', + 'json_dumps', + 'copy_on_model_validation', + 'post_init_call', +} +V2_RENAMED_KEYS = { + 'allow_population_by_field_name': 'populate_by_name', + 'anystr_lower': 'str_to_lower', + 'anystr_strip_whitespace': 'str_strip_whitespace', + 'anystr_upper': 'str_to_upper', + 'keep_untouched': 'ignored_types', + 'max_anystr_length': 'str_max_length', + 'min_anystr_length': 'str_min_length', + 'orm_mode': 'from_attributes', + 'schema_extra': 'json_schema_extra', + 'validate_all': 'validate_default', +} + + +def check_deprecated(config_dict: ConfigDict) -> None: + """Check for deprecated config keys and warn the user. + + Args: + config_dict: The input config. + """ + deprecated_removed_keys = V2_REMOVED_KEYS & config_dict.keys() + deprecated_renamed_keys = V2_RENAMED_KEYS.keys() & config_dict.keys() + if deprecated_removed_keys or deprecated_renamed_keys: + renamings = {k: V2_RENAMED_KEYS[k] for k in sorted(deprecated_renamed_keys)} + renamed_bullets = [f'* {k!r} has been renamed to {v!r}' for k, v in renamings.items()] + removed_bullets = [f'* {k!r} has been removed' for k in sorted(deprecated_removed_keys)] + message = '\n'.join(['Valid config keys have changed in V2:'] + renamed_bullets + removed_bullets) + warnings.warn(message, UserWarning) diff --git a/env/Lib/site-packages/pydantic/_internal/_core_metadata.py b/env/Lib/site-packages/pydantic/_internal/_core_metadata.py new file mode 100644 index 0000000..296d49f --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_core_metadata.py @@ -0,0 +1,92 @@ +from __future__ import annotations as _annotations + +import typing +from typing import Any + +import typing_extensions + +if typing.TYPE_CHECKING: + from ._schema_generation_shared import ( + CoreSchemaOrField as CoreSchemaOrField, + ) + from ._schema_generation_shared import ( + GetJsonSchemaFunction, + ) + + +class CoreMetadata(typing_extensions.TypedDict, total=False): + """A `TypedDict` for holding the metadata dict of the schema. + + Attributes: + pydantic_js_functions: List of JSON schema functions. + pydantic_js_prefer_positional_arguments: Whether JSON schema generator will + prefer positional over keyword arguments for an 'arguments' schema. + """ + + pydantic_js_functions: list[GetJsonSchemaFunction] + pydantic_js_annotation_functions: list[GetJsonSchemaFunction] + + # If `pydantic_js_prefer_positional_arguments` is True, the JSON schema generator will + # prefer positional over keyword arguments for an 'arguments' schema. + pydantic_js_prefer_positional_arguments: bool | None + + pydantic_typed_dict_cls: type[Any] | None # TODO: Consider moving this into the pydantic-core TypedDictSchema + + +class CoreMetadataHandler: + """Because the metadata field in pydantic_core is of type `Any`, we can't assume much about its contents. + + This class is used to interact with the metadata field on a CoreSchema object in a consistent + way throughout pydantic. + """ + + __slots__ = ('_schema',) + + def __init__(self, schema: CoreSchemaOrField): + self._schema = schema + + metadata = schema.get('metadata') + if metadata is None: + schema['metadata'] = CoreMetadata() + elif not isinstance(metadata, dict): + raise TypeError(f'CoreSchema metadata should be a dict; got {metadata!r}.') + + @property + def metadata(self) -> CoreMetadata: + """Retrieves the metadata dict from the schema, initializing it to a dict if it is None + and raises an error if it is not a dict. + """ + metadata = self._schema.get('metadata') + if metadata is None: + self._schema['metadata'] = metadata = CoreMetadata() + if not isinstance(metadata, dict): + raise TypeError(f'CoreSchema metadata should be a dict; got {metadata!r}.') + return metadata + + +def build_metadata_dict( + *, # force keyword arguments to make it easier to modify this signature in a backwards-compatible way + js_functions: list[GetJsonSchemaFunction] | None = None, + js_annotation_functions: list[GetJsonSchemaFunction] | None = None, + js_prefer_positional_arguments: bool | None = None, + typed_dict_cls: type[Any] | None = None, + initial_metadata: Any | None = None, +) -> Any: + """Builds a dict to use as the metadata field of a CoreSchema object in a manner that is consistent + with the CoreMetadataHandler class. + """ + if initial_metadata is not None and not isinstance(initial_metadata, dict): + raise TypeError(f'CoreSchema metadata should be a dict; got {initial_metadata!r}.') + + metadata = CoreMetadata( + pydantic_js_functions=js_functions or [], + pydantic_js_annotation_functions=js_annotation_functions or [], + pydantic_js_prefer_positional_arguments=js_prefer_positional_arguments, + pydantic_typed_dict_cls=typed_dict_cls, + ) + metadata = {k: v for k, v in metadata.items() if v is not None} + + if initial_metadata is not None: + metadata = {**initial_metadata, **metadata} + + return metadata diff --git a/env/Lib/site-packages/pydantic/_internal/_core_utils.py b/env/Lib/site-packages/pydantic/_internal/_core_utils.py new file mode 100644 index 0000000..baec706 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_core_utils.py @@ -0,0 +1,568 @@ +from __future__ import annotations + +import os +from collections import defaultdict +from typing import ( + Any, + Callable, + Hashable, + TypeVar, + Union, +) + +from pydantic_core import CoreSchema, core_schema +from pydantic_core import validate_core_schema as _validate_core_schema +from typing_extensions import TypeAliasType, TypeGuard, get_args, get_origin + +from . import _repr +from ._typing_extra import is_generic_alias + +AnyFunctionSchema = Union[ + core_schema.AfterValidatorFunctionSchema, + core_schema.BeforeValidatorFunctionSchema, + core_schema.WrapValidatorFunctionSchema, + core_schema.PlainValidatorFunctionSchema, +] + + +FunctionSchemaWithInnerSchema = Union[ + core_schema.AfterValidatorFunctionSchema, + core_schema.BeforeValidatorFunctionSchema, + core_schema.WrapValidatorFunctionSchema, +] + +CoreSchemaField = Union[ + core_schema.ModelField, core_schema.DataclassField, core_schema.TypedDictField, core_schema.ComputedField +] +CoreSchemaOrField = Union[core_schema.CoreSchema, CoreSchemaField] + +_CORE_SCHEMA_FIELD_TYPES = {'typed-dict-field', 'dataclass-field', 'model-field', 'computed-field'} +_FUNCTION_WITH_INNER_SCHEMA_TYPES = {'function-before', 'function-after', 'function-wrap'} +_LIST_LIKE_SCHEMA_WITH_ITEMS_TYPES = {'list', 'set', 'frozenset'} + +TAGGED_UNION_TAG_KEY = 'pydantic.internal.tagged_union_tag' +""" +Used in a `Tag` schema to specify the tag used for a discriminated union. +""" +HAS_INVALID_SCHEMAS_METADATA_KEY = 'pydantic.internal.invalid' +"""Used to mark a schema that is invalid because it refers to a definition that was not yet defined when the +schema was first encountered. +""" + + +def is_core_schema( + schema: CoreSchemaOrField, +) -> TypeGuard[CoreSchema]: + return schema['type'] not in _CORE_SCHEMA_FIELD_TYPES + + +def is_core_schema_field( + schema: CoreSchemaOrField, +) -> TypeGuard[CoreSchemaField]: + return schema['type'] in _CORE_SCHEMA_FIELD_TYPES + + +def is_function_with_inner_schema( + schema: CoreSchemaOrField, +) -> TypeGuard[FunctionSchemaWithInnerSchema]: + return schema['type'] in _FUNCTION_WITH_INNER_SCHEMA_TYPES + + +def is_list_like_schema_with_items_schema( + schema: CoreSchema, +) -> TypeGuard[core_schema.ListSchema | core_schema.SetSchema | core_schema.FrozenSetSchema]: + return schema['type'] in _LIST_LIKE_SCHEMA_WITH_ITEMS_TYPES + + +def get_type_ref(type_: type[Any], args_override: tuple[type[Any], ...] | None = None) -> str: + """Produces the ref to be used for this type by pydantic_core's core schemas. + + This `args_override` argument was added for the purpose of creating valid recursive references + when creating generic models without needing to create a concrete class. + """ + origin = get_origin(type_) or type_ + + args = get_args(type_) if is_generic_alias(type_) else (args_override or ()) + generic_metadata = getattr(type_, '__pydantic_generic_metadata__', None) + if generic_metadata: + origin = generic_metadata['origin'] or origin + args = generic_metadata['args'] or args + + module_name = getattr(origin, '__module__', '') + if isinstance(origin, TypeAliasType): + type_ref = f'{module_name}.{origin.__name__}:{id(origin)}' + else: + try: + qualname = getattr(origin, '__qualname__', f'') + except Exception: + qualname = getattr(origin, '__qualname__', '') + type_ref = f'{module_name}.{qualname}:{id(origin)}' + + arg_refs: list[str] = [] + for arg in args: + if isinstance(arg, str): + # Handle string literals as a special case; we may be able to remove this special handling if we + # wrap them in a ForwardRef at some point. + arg_ref = f'{arg}:str-{id(arg)}' + else: + arg_ref = f'{_repr.display_as_type(arg)}:{id(arg)}' + arg_refs.append(arg_ref) + if arg_refs: + type_ref = f'{type_ref}[{",".join(arg_refs)}]' + return type_ref + + +def get_ref(s: core_schema.CoreSchema) -> None | str: + """Get the ref from the schema if it has one. + This exists just for type checking to work correctly. + """ + return s.get('ref', None) + + +def collect_definitions(schema: core_schema.CoreSchema) -> dict[str, core_schema.CoreSchema]: + defs: dict[str, CoreSchema] = {} + + def _record_valid_refs(s: core_schema.CoreSchema, recurse: Recurse) -> core_schema.CoreSchema: + ref = get_ref(s) + if ref: + defs[ref] = s + return recurse(s, _record_valid_refs) + + walk_core_schema(schema, _record_valid_refs) + + return defs + + +def define_expected_missing_refs( + schema: core_schema.CoreSchema, allowed_missing_refs: set[str] +) -> core_schema.CoreSchema | None: + if not allowed_missing_refs: + # in this case, there are no missing refs to potentially substitute, so there's no need to walk the schema + # this is a common case (will be hit for all non-generic models), so it's worth optimizing for + return None + + refs = collect_definitions(schema).keys() + + expected_missing_refs = allowed_missing_refs.difference(refs) + if expected_missing_refs: + definitions: list[core_schema.CoreSchema] = [ + # TODO: Replace this with a (new) CoreSchema that, if present at any level, makes validation fail + # Issue: https://github.com/pydantic/pydantic-core/issues/619 + core_schema.none_schema(ref=ref, metadata={HAS_INVALID_SCHEMAS_METADATA_KEY: True}) + for ref in expected_missing_refs + ] + return core_schema.definitions_schema(schema, definitions) + return None + + +def collect_invalid_schemas(schema: core_schema.CoreSchema) -> bool: + invalid = False + + def _is_schema_valid(s: core_schema.CoreSchema, recurse: Recurse) -> core_schema.CoreSchema: + nonlocal invalid + if 'metadata' in s: + metadata = s['metadata'] + if HAS_INVALID_SCHEMAS_METADATA_KEY in metadata: + invalid = metadata[HAS_INVALID_SCHEMAS_METADATA_KEY] + return s + return recurse(s, _is_schema_valid) + + walk_core_schema(schema, _is_schema_valid) + return invalid + + +T = TypeVar('T') + + +Recurse = Callable[[core_schema.CoreSchema, 'Walk'], core_schema.CoreSchema] +Walk = Callable[[core_schema.CoreSchema, Recurse], core_schema.CoreSchema] + +# TODO: Should we move _WalkCoreSchema into pydantic_core proper? +# Issue: https://github.com/pydantic/pydantic-core/issues/615 + + +class _WalkCoreSchema: + def __init__(self): + self._schema_type_to_method = self._build_schema_type_to_method() + + def _build_schema_type_to_method(self) -> dict[core_schema.CoreSchemaType, Recurse]: + mapping: dict[core_schema.CoreSchemaType, Recurse] = {} + key: core_schema.CoreSchemaType + for key in get_args(core_schema.CoreSchemaType): + method_name = f"handle_{key.replace('-', '_')}_schema" + mapping[key] = getattr(self, method_name, self._handle_other_schemas) + return mapping + + def walk(self, schema: core_schema.CoreSchema, f: Walk) -> core_schema.CoreSchema: + return f(schema, self._walk) + + def _walk(self, schema: core_schema.CoreSchema, f: Walk) -> core_schema.CoreSchema: + schema = self._schema_type_to_method[schema['type']](schema.copy(), f) + ser_schema: core_schema.SerSchema | None = schema.get('serialization') # type: ignore + if ser_schema: + schema['serialization'] = self._handle_ser_schemas(ser_schema, f) + return schema + + def _handle_other_schemas(self, schema: core_schema.CoreSchema, f: Walk) -> core_schema.CoreSchema: + sub_schema = schema.get('schema', None) + if sub_schema is not None: + schema['schema'] = self.walk(sub_schema, f) # type: ignore + return schema + + def _handle_ser_schemas(self, ser_schema: core_schema.SerSchema, f: Walk) -> core_schema.SerSchema: + schema: core_schema.CoreSchema | None = ser_schema.get('schema', None) + if schema is not None: + ser_schema['schema'] = self.walk(schema, f) # type: ignore + return_schema: core_schema.CoreSchema | None = ser_schema.get('return_schema', None) + if return_schema is not None: + ser_schema['return_schema'] = self.walk(return_schema, f) # type: ignore + return ser_schema + + def handle_definitions_schema(self, schema: core_schema.DefinitionsSchema, f: Walk) -> core_schema.CoreSchema: + new_definitions: list[core_schema.CoreSchema] = [] + for definition in schema['definitions']: + if 'schema_ref' in definition and 'ref' in definition: + # This indicates a purposely indirect reference + # We want to keep such references around for implications related to JSON schema, etc.: + new_definitions.append(definition) + # However, we still need to walk the referenced definition: + self.walk(definition, f) + continue + + updated_definition = self.walk(definition, f) + if 'ref' in updated_definition: + # If the updated definition schema doesn't have a 'ref', it shouldn't go in the definitions + # This is most likely to happen due to replacing something with a definition reference, in + # which case it should certainly not go in the definitions list + new_definitions.append(updated_definition) + new_inner_schema = self.walk(schema['schema'], f) + + if not new_definitions and len(schema) == 3: + # This means we'd be returning a "trivial" definitions schema that just wrapped the inner schema + return new_inner_schema + + new_schema = schema.copy() + new_schema['schema'] = new_inner_schema + new_schema['definitions'] = new_definitions + return new_schema + + def handle_list_schema(self, schema: core_schema.ListSchema, f: Walk) -> core_schema.CoreSchema: + items_schema = schema.get('items_schema') + if items_schema is not None: + schema['items_schema'] = self.walk(items_schema, f) + return schema + + def handle_set_schema(self, schema: core_schema.SetSchema, f: Walk) -> core_schema.CoreSchema: + items_schema = schema.get('items_schema') + if items_schema is not None: + schema['items_schema'] = self.walk(items_schema, f) + return schema + + def handle_frozenset_schema(self, schema: core_schema.FrozenSetSchema, f: Walk) -> core_schema.CoreSchema: + items_schema = schema.get('items_schema') + if items_schema is not None: + schema['items_schema'] = self.walk(items_schema, f) + return schema + + def handle_generator_schema(self, schema: core_schema.GeneratorSchema, f: Walk) -> core_schema.CoreSchema: + items_schema = schema.get('items_schema') + if items_schema is not None: + schema['items_schema'] = self.walk(items_schema, f) + return schema + + def handle_tuple_schema(self, schema: core_schema.TupleSchema, f: Walk) -> core_schema.CoreSchema: + schema['items_schema'] = [self.walk(v, f) for v in schema['items_schema']] + return schema + + def handle_dict_schema(self, schema: core_schema.DictSchema, f: Walk) -> core_schema.CoreSchema: + keys_schema = schema.get('keys_schema') + if keys_schema is not None: + schema['keys_schema'] = self.walk(keys_schema, f) + values_schema = schema.get('values_schema') + if values_schema: + schema['values_schema'] = self.walk(values_schema, f) + return schema + + def handle_function_schema(self, schema: AnyFunctionSchema, f: Walk) -> core_schema.CoreSchema: + if not is_function_with_inner_schema(schema): + return schema + schema['schema'] = self.walk(schema['schema'], f) + return schema + + def handle_union_schema(self, schema: core_schema.UnionSchema, f: Walk) -> core_schema.CoreSchema: + new_choices: list[CoreSchema | tuple[CoreSchema, str]] = [] + for v in schema['choices']: + if isinstance(v, tuple): + new_choices.append((self.walk(v[0], f), v[1])) + else: + new_choices.append(self.walk(v, f)) + schema['choices'] = new_choices + return schema + + def handle_tagged_union_schema(self, schema: core_schema.TaggedUnionSchema, f: Walk) -> core_schema.CoreSchema: + new_choices: dict[Hashable, core_schema.CoreSchema] = {} + for k, v in schema['choices'].items(): + new_choices[k] = v if isinstance(v, (str, int)) else self.walk(v, f) + schema['choices'] = new_choices + return schema + + def handle_chain_schema(self, schema: core_schema.ChainSchema, f: Walk) -> core_schema.CoreSchema: + schema['steps'] = [self.walk(v, f) for v in schema['steps']] + return schema + + def handle_lax_or_strict_schema(self, schema: core_schema.LaxOrStrictSchema, f: Walk) -> core_schema.CoreSchema: + schema['lax_schema'] = self.walk(schema['lax_schema'], f) + schema['strict_schema'] = self.walk(schema['strict_schema'], f) + return schema + + def handle_json_or_python_schema(self, schema: core_schema.JsonOrPythonSchema, f: Walk) -> core_schema.CoreSchema: + schema['json_schema'] = self.walk(schema['json_schema'], f) + schema['python_schema'] = self.walk(schema['python_schema'], f) + return schema + + def handle_model_fields_schema(self, schema: core_schema.ModelFieldsSchema, f: Walk) -> core_schema.CoreSchema: + extras_schema = schema.get('extras_schema') + if extras_schema is not None: + schema['extras_schema'] = self.walk(extras_schema, f) + replaced_fields: dict[str, core_schema.ModelField] = {} + replaced_computed_fields: list[core_schema.ComputedField] = [] + for computed_field in schema.get('computed_fields', ()): + replaced_field = computed_field.copy() + replaced_field['return_schema'] = self.walk(computed_field['return_schema'], f) + replaced_computed_fields.append(replaced_field) + if replaced_computed_fields: + schema['computed_fields'] = replaced_computed_fields + for k, v in schema['fields'].items(): + replaced_field = v.copy() + replaced_field['schema'] = self.walk(v['schema'], f) + replaced_fields[k] = replaced_field + schema['fields'] = replaced_fields + return schema + + def handle_typed_dict_schema(self, schema: core_schema.TypedDictSchema, f: Walk) -> core_schema.CoreSchema: + extras_schema = schema.get('extras_schema') + if extras_schema is not None: + schema['extras_schema'] = self.walk(extras_schema, f) + replaced_computed_fields: list[core_schema.ComputedField] = [] + for computed_field in schema.get('computed_fields', ()): + replaced_field = computed_field.copy() + replaced_field['return_schema'] = self.walk(computed_field['return_schema'], f) + replaced_computed_fields.append(replaced_field) + if replaced_computed_fields: + schema['computed_fields'] = replaced_computed_fields + replaced_fields: dict[str, core_schema.TypedDictField] = {} + for k, v in schema['fields'].items(): + replaced_field = v.copy() + replaced_field['schema'] = self.walk(v['schema'], f) + replaced_fields[k] = replaced_field + schema['fields'] = replaced_fields + return schema + + def handle_dataclass_args_schema(self, schema: core_schema.DataclassArgsSchema, f: Walk) -> core_schema.CoreSchema: + replaced_fields: list[core_schema.DataclassField] = [] + replaced_computed_fields: list[core_schema.ComputedField] = [] + for computed_field in schema.get('computed_fields', ()): + replaced_field = computed_field.copy() + replaced_field['return_schema'] = self.walk(computed_field['return_schema'], f) + replaced_computed_fields.append(replaced_field) + if replaced_computed_fields: + schema['computed_fields'] = replaced_computed_fields + for field in schema['fields']: + replaced_field = field.copy() + replaced_field['schema'] = self.walk(field['schema'], f) + replaced_fields.append(replaced_field) + schema['fields'] = replaced_fields + return schema + + def handle_arguments_schema(self, schema: core_schema.ArgumentsSchema, f: Walk) -> core_schema.CoreSchema: + replaced_arguments_schema: list[core_schema.ArgumentsParameter] = [] + for param in schema['arguments_schema']: + replaced_param = param.copy() + replaced_param['schema'] = self.walk(param['schema'], f) + replaced_arguments_schema.append(replaced_param) + schema['arguments_schema'] = replaced_arguments_schema + if 'var_args_schema' in schema: + schema['var_args_schema'] = self.walk(schema['var_args_schema'], f) + if 'var_kwargs_schema' in schema: + schema['var_kwargs_schema'] = self.walk(schema['var_kwargs_schema'], f) + return schema + + def handle_call_schema(self, schema: core_schema.CallSchema, f: Walk) -> core_schema.CoreSchema: + schema['arguments_schema'] = self.walk(schema['arguments_schema'], f) + if 'return_schema' in schema: + schema['return_schema'] = self.walk(schema['return_schema'], f) + return schema + + +_dispatch = _WalkCoreSchema().walk + + +def walk_core_schema(schema: core_schema.CoreSchema, f: Walk) -> core_schema.CoreSchema: + """Recursively traverse a CoreSchema. + + Args: + schema (core_schema.CoreSchema): The CoreSchema to process, it will not be modified. + f (Walk): A function to apply. This function takes two arguments: + 1. The current CoreSchema that is being processed + (not the same one you passed into this function, one level down). + 2. The "next" `f` to call. This lets you for example use `f=functools.partial(some_method, some_context)` + to pass data down the recursive calls without using globals or other mutable state. + + Returns: + core_schema.CoreSchema: A processed CoreSchema. + """ + return f(schema.copy(), _dispatch) + + +def simplify_schema_references(schema: core_schema.CoreSchema) -> core_schema.CoreSchema: # noqa: C901 + definitions: dict[str, core_schema.CoreSchema] = {} + ref_counts: dict[str, int] = defaultdict(int) + involved_in_recursion: dict[str, bool] = {} + current_recursion_ref_count: dict[str, int] = defaultdict(int) + + def collect_refs(s: core_schema.CoreSchema, recurse: Recurse) -> core_schema.CoreSchema: + if s['type'] == 'definitions': + for definition in s['definitions']: + ref = get_ref(definition) + assert ref is not None + if ref not in definitions: + definitions[ref] = definition + recurse(definition, collect_refs) + return recurse(s['schema'], collect_refs) + else: + ref = get_ref(s) + if ref is not None: + new = recurse(s, collect_refs) + new_ref = get_ref(new) + if new_ref: + definitions[new_ref] = new + return core_schema.definition_reference_schema(schema_ref=ref) + else: + return recurse(s, collect_refs) + + schema = walk_core_schema(schema, collect_refs) + + def count_refs(s: core_schema.CoreSchema, recurse: Recurse) -> core_schema.CoreSchema: + if s['type'] != 'definition-ref': + return recurse(s, count_refs) + ref = s['schema_ref'] + ref_counts[ref] += 1 + + if ref_counts[ref] >= 2: + # If this model is involved in a recursion this should be detected + # on its second encounter, we can safely stop the walk here. + if current_recursion_ref_count[ref] != 0: + involved_in_recursion[ref] = True + return s + + current_recursion_ref_count[ref] += 1 + recurse(definitions[ref], count_refs) + current_recursion_ref_count[ref] -= 1 + return s + + schema = walk_core_schema(schema, count_refs) + + assert all(c == 0 for c in current_recursion_ref_count.values()), 'this is a bug! please report it' + + def can_be_inlined(s: core_schema.DefinitionReferenceSchema, ref: str) -> bool: + if ref_counts[ref] > 1: + return False + if involved_in_recursion.get(ref, False): + return False + if 'serialization' in s: + return False + if 'metadata' in s: + metadata = s['metadata'] + for k in ( + 'pydantic_js_functions', + 'pydantic_js_annotation_functions', + 'pydantic.internal.union_discriminator', + ): + if k in metadata: + # we need to keep this as a ref + return False + return True + + def inline_refs(s: core_schema.CoreSchema, recurse: Recurse) -> core_schema.CoreSchema: + if s['type'] == 'definition-ref': + ref = s['schema_ref'] + # Check if the reference is only used once, not involved in recursion and does not have + # any extra keys (like 'serialization') + if can_be_inlined(s, ref): + # Inline the reference by replacing the reference with the actual schema + new = definitions.pop(ref) + ref_counts[ref] -= 1 # because we just replaced it! + # put all other keys that were on the def-ref schema into the inlined version + # in particular this is needed for `serialization` + if 'serialization' in s: + new['serialization'] = s['serialization'] + s = recurse(new, inline_refs) + return s + else: + return recurse(s, inline_refs) + else: + return recurse(s, inline_refs) + + schema = walk_core_schema(schema, inline_refs) + + def_values = [v for v in definitions.values() if ref_counts[v['ref']] > 0] # type: ignore + + if def_values: + schema = core_schema.definitions_schema(schema=schema, definitions=def_values) + return schema + + +def _strip_metadata(schema: CoreSchema) -> CoreSchema: + def strip_metadata(s: CoreSchema, recurse: Recurse) -> CoreSchema: + s = s.copy() + s.pop('metadata', None) + if s['type'] == 'model-fields': + s = s.copy() + s['fields'] = {k: v.copy() for k, v in s['fields'].items()} + for field_name, field_schema in s['fields'].items(): + field_schema.pop('metadata', None) + s['fields'][field_name] = field_schema + computed_fields = s.get('computed_fields', None) + if computed_fields: + s['computed_fields'] = [cf.copy() for cf in computed_fields] + for cf in computed_fields: + cf.pop('metadata', None) + else: + s.pop('computed_fields', None) + elif s['type'] == 'model': + # remove some defaults + if s.get('custom_init', True) is False: + s.pop('custom_init') + if s.get('root_model', True) is False: + s.pop('root_model') + if {'title'}.issuperset(s.get('config', {}).keys()): + s.pop('config', None) + + return recurse(s, strip_metadata) + + return walk_core_schema(schema, strip_metadata) + + +def pretty_print_core_schema( + schema: CoreSchema, + include_metadata: bool = False, +) -> None: + """Pretty print a CoreSchema using rich. + This is intended for debugging purposes. + + Args: + schema: The CoreSchema to print. + include_metadata: Whether to include metadata in the output. Defaults to `False`. + """ + from rich import print # type: ignore # install it manually in your dev env + + if not include_metadata: + schema = _strip_metadata(schema) + + return print(schema) + + +def validate_core_schema(schema: CoreSchema) -> CoreSchema: + if 'PYDANTIC_SKIP_VALIDATING_CORE_SCHEMAS' in os.environ: + return schema + return _validate_core_schema(schema) diff --git a/env/Lib/site-packages/pydantic/_internal/_dataclasses.py b/env/Lib/site-packages/pydantic/_internal/_dataclasses.py new file mode 100644 index 0000000..7327292 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_dataclasses.py @@ -0,0 +1,231 @@ +"""Private logic for creating pydantic dataclasses.""" + +from __future__ import annotations as _annotations + +import dataclasses +import typing +import warnings +from functools import partial, wraps +from typing import Any, Callable, ClassVar + +from pydantic_core import ( + ArgsKwargs, + SchemaSerializer, + SchemaValidator, + core_schema, +) +from typing_extensions import TypeGuard + +from ..errors import PydanticUndefinedAnnotation +from ..fields import FieldInfo +from ..plugin._schema_validator import PluggableSchemaValidator, create_schema_validator +from ..warnings import PydanticDeprecatedSince20 +from . import _config, _decorators, _typing_extra +from ._fields import collect_dataclass_fields +from ._generate_schema import GenerateSchema +from ._generics import get_standard_typevars_map +from ._mock_val_ser import set_dataclass_mocks +from ._schema_generation_shared import CallbackGetCoreSchemaHandler +from ._signature import generate_pydantic_signature + +if typing.TYPE_CHECKING: + from ..config import ConfigDict + + class StandardDataclass(typing.Protocol): + __dataclass_fields__: ClassVar[dict[str, Any]] + __dataclass_params__: ClassVar[Any] # in reality `dataclasses._DataclassParams` + __post_init__: ClassVar[Callable[..., None]] + + def __init__(self, *args: object, **kwargs: object) -> None: + pass + + class PydanticDataclass(StandardDataclass, typing.Protocol): + """A protocol containing attributes only available once a class has been decorated as a Pydantic dataclass. + + Attributes: + __pydantic_config__: Pydantic-specific configuration settings for the dataclass. + __pydantic_complete__: Whether dataclass building is completed, or if there are still undefined fields. + __pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer. + __pydantic_decorators__: Metadata containing the decorators defined on the dataclass. + __pydantic_fields__: Metadata about the fields defined on the dataclass. + __pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the dataclass. + __pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the dataclass. + """ + + __pydantic_config__: ClassVar[ConfigDict] + __pydantic_complete__: ClassVar[bool] + __pydantic_core_schema__: ClassVar[core_schema.CoreSchema] + __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] + __pydantic_fields__: ClassVar[dict[str, FieldInfo]] + __pydantic_serializer__: ClassVar[SchemaSerializer] + __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator] + +else: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + + +def set_dataclass_fields( + cls: type[StandardDataclass], + types_namespace: dict[str, Any] | None = None, + config_wrapper: _config.ConfigWrapper | None = None, +) -> None: + """Collect and set `cls.__pydantic_fields__`. + + Args: + cls: The class. + types_namespace: The types namespace, defaults to `None`. + config_wrapper: The config wrapper instance, defaults to `None`. + """ + typevars_map = get_standard_typevars_map(cls) + fields = collect_dataclass_fields(cls, types_namespace, typevars_map=typevars_map, config_wrapper=config_wrapper) + + cls.__pydantic_fields__ = fields # type: ignore + + +def complete_dataclass( + cls: type[Any], + config_wrapper: _config.ConfigWrapper, + *, + raise_errors: bool = True, + types_namespace: dict[str, Any] | None, +) -> bool: + """Finish building a pydantic dataclass. + + This logic is called on a class which has already been wrapped in `dataclasses.dataclass()`. + + This is somewhat analogous to `pydantic._internal._model_construction.complete_model_class`. + + Args: + cls: The class. + config_wrapper: The config wrapper instance. + raise_errors: Whether to raise errors, defaults to `True`. + types_namespace: The types namespace. + + Returns: + `True` if building a pydantic dataclass is successfully completed, `False` otherwise. + + Raises: + PydanticUndefinedAnnotation: If `raise_error` is `True` and there is an undefined annotations. + """ + if hasattr(cls, '__post_init_post_parse__'): + warnings.warn( + 'Support for `__post_init_post_parse__` has been dropped, the method will not be called', DeprecationWarning + ) + + if types_namespace is None: + types_namespace = _typing_extra.get_cls_types_namespace(cls) + + set_dataclass_fields(cls, types_namespace, config_wrapper=config_wrapper) + + typevars_map = get_standard_typevars_map(cls) + gen_schema = GenerateSchema( + config_wrapper, + types_namespace, + typevars_map, + ) + + # This needs to be called before we change the __init__ + sig = generate_pydantic_signature( + init=cls.__init__, + fields=cls.__pydantic_fields__, # type: ignore + config_wrapper=config_wrapper, + is_dataclass=True, + ) + + # dataclass.__init__ must be defined here so its `__qualname__` can be changed since functions can't be copied. + def __init__(__dataclass_self__: PydanticDataclass, *args: Any, **kwargs: Any) -> None: + __tracebackhide__ = True + s = __dataclass_self__ + s.__pydantic_validator__.validate_python(ArgsKwargs(args, kwargs), self_instance=s) + + __init__.__qualname__ = f'{cls.__qualname__}.__init__' + + cls.__init__ = __init__ # type: ignore + cls.__pydantic_config__ = config_wrapper.config_dict # type: ignore + cls.__signature__ = sig # type: ignore + get_core_schema = getattr(cls, '__get_pydantic_core_schema__', None) + try: + if get_core_schema: + schema = get_core_schema( + cls, + CallbackGetCoreSchemaHandler( + partial(gen_schema.generate_schema, from_dunder_get_core_schema=False), + gen_schema, + ref_mode='unpack', + ), + ) + else: + schema = gen_schema.generate_schema(cls, from_dunder_get_core_schema=False) + except PydanticUndefinedAnnotation as e: + if raise_errors: + raise + set_dataclass_mocks(cls, cls.__name__, f'`{e.name}`') + return False + + core_config = config_wrapper.core_config(cls) + + try: + schema = gen_schema.clean_schema(schema) + except gen_schema.CollectedInvalid: + set_dataclass_mocks(cls, cls.__name__, 'all referenced types') + return False + + # We are about to set all the remaining required properties expected for this cast; + # __pydantic_decorators__ and __pydantic_fields__ should already be set + cls = typing.cast('type[PydanticDataclass]', cls) + # debug(schema) + + cls.__pydantic_core_schema__ = schema + cls.__pydantic_validator__ = validator = create_schema_validator( + schema, cls, cls.__module__, cls.__qualname__, 'dataclass', core_config, config_wrapper.plugin_settings + ) + cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config) + + if config_wrapper.validate_assignment: + + @wraps(cls.__setattr__) + def validated_setattr(instance: Any, field: str, value: str, /) -> None: + validator.validate_assignment(instance, field, value) + + cls.__setattr__ = validated_setattr.__get__(None, cls) # type: ignore + + return True + + +def is_builtin_dataclass(_cls: type[Any]) -> TypeGuard[type[StandardDataclass]]: + """Returns True if a class is a stdlib dataclass and *not* a pydantic dataclass. + + We check that + - `_cls` is a dataclass + - `_cls` does not inherit from a processed pydantic dataclass (and thus have a `__pydantic_validator__`) + - `_cls` does not have any annotations that are not dataclass fields + e.g. + ```py + import dataclasses + + import pydantic.dataclasses + + @dataclasses.dataclass + class A: + x: int + + @pydantic.dataclasses.dataclass + class B(A): + y: int + ``` + In this case, when we first check `B`, we make an extra check and look at the annotations ('y'), + which won't be a superset of all the dataclass fields (only the stdlib fields i.e. 'x') + + Args: + cls: The class. + + Returns: + `True` if the class is a stdlib dataclass, `False` otherwise. + """ + return ( + dataclasses.is_dataclass(_cls) + and not hasattr(_cls, '__pydantic_validator__') + and set(_cls.__dataclass_fields__).issuperset(set(getattr(_cls, '__annotations__', {}))) + ) diff --git a/env/Lib/site-packages/pydantic/_internal/_decorators.py b/env/Lib/site-packages/pydantic/_internal/_decorators.py new file mode 100644 index 0000000..66db218 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_decorators.py @@ -0,0 +1,817 @@ +"""Logic related to validators applied to models etc. via the `@field_validator` and `@model_validator` decorators.""" + +from __future__ import annotations as _annotations + +from collections import deque +from dataclasses import dataclass, field +from functools import cached_property, partial, partialmethod +from inspect import Parameter, Signature, isdatadescriptor, ismethoddescriptor, signature +from itertools import islice +from typing import TYPE_CHECKING, Any, Callable, ClassVar, Generic, Iterable, TypeVar, Union + +from pydantic_core import PydanticUndefined, core_schema +from typing_extensions import Literal, TypeAlias, is_typeddict + +from ..errors import PydanticUserError +from ._core_utils import get_type_ref +from ._internal_dataclass import slots_true +from ._typing_extra import get_function_type_hints + +if TYPE_CHECKING: + from ..fields import ComputedFieldInfo + from ..functional_validators import FieldValidatorModes + + +@dataclass(**slots_true) +class ValidatorDecoratorInfo: + """A container for data from `@validator` so that we can access it + while building the pydantic-core schema. + + Attributes: + decorator_repr: A class variable representing the decorator string, '@validator'. + fields: A tuple of field names the validator should be called on. + mode: The proposed validator mode. + each_item: For complex objects (sets, lists etc.) whether to validate individual + elements rather than the whole object. + always: Whether this method and other validators should be called even if the value is missing. + check_fields: Whether to check that the fields actually exist on the model. + """ + + decorator_repr: ClassVar[str] = '@validator' + + fields: tuple[str, ...] + mode: Literal['before', 'after'] + each_item: bool + always: bool + check_fields: bool | None + + +@dataclass(**slots_true) +class FieldValidatorDecoratorInfo: + """A container for data from `@field_validator` so that we can access it + while building the pydantic-core schema. + + Attributes: + decorator_repr: A class variable representing the decorator string, '@field_validator'. + fields: A tuple of field names the validator should be called on. + mode: The proposed validator mode. + check_fields: Whether to check that the fields actually exist on the model. + """ + + decorator_repr: ClassVar[str] = '@field_validator' + + fields: tuple[str, ...] + mode: FieldValidatorModes + check_fields: bool | None + + +@dataclass(**slots_true) +class RootValidatorDecoratorInfo: + """A container for data from `@root_validator` so that we can access it + while building the pydantic-core schema. + + Attributes: + decorator_repr: A class variable representing the decorator string, '@root_validator'. + mode: The proposed validator mode. + """ + + decorator_repr: ClassVar[str] = '@root_validator' + mode: Literal['before', 'after'] + + +@dataclass(**slots_true) +class FieldSerializerDecoratorInfo: + """A container for data from `@field_serializer` so that we can access it + while building the pydantic-core schema. + + Attributes: + decorator_repr: A class variable representing the decorator string, '@field_serializer'. + fields: A tuple of field names the serializer should be called on. + mode: The proposed serializer mode. + return_type: The type of the serializer's return value. + when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, + and `'json-unless-none'`. + check_fields: Whether to check that the fields actually exist on the model. + """ + + decorator_repr: ClassVar[str] = '@field_serializer' + fields: tuple[str, ...] + mode: Literal['plain', 'wrap'] + return_type: Any + when_used: core_schema.WhenUsed + check_fields: bool | None + + +@dataclass(**slots_true) +class ModelSerializerDecoratorInfo: + """A container for data from `@model_serializer` so that we can access it + while building the pydantic-core schema. + + Attributes: + decorator_repr: A class variable representing the decorator string, '@model_serializer'. + mode: The proposed serializer mode. + return_type: The type of the serializer's return value. + when_used: The serialization condition. Accepts a string with values `'always'`, `'unless-none'`, `'json'`, + and `'json-unless-none'`. + """ + + decorator_repr: ClassVar[str] = '@model_serializer' + mode: Literal['plain', 'wrap'] + return_type: Any + when_used: core_schema.WhenUsed + + +@dataclass(**slots_true) +class ModelValidatorDecoratorInfo: + """A container for data from `@model_validator` so that we can access it + while building the pydantic-core schema. + + Attributes: + decorator_repr: A class variable representing the decorator string, '@model_serializer'. + mode: The proposed serializer mode. + """ + + decorator_repr: ClassVar[str] = '@model_validator' + mode: Literal['wrap', 'before', 'after'] + + +DecoratorInfo: TypeAlias = """Union[ + ValidatorDecoratorInfo, + FieldValidatorDecoratorInfo, + RootValidatorDecoratorInfo, + FieldSerializerDecoratorInfo, + ModelSerializerDecoratorInfo, + ModelValidatorDecoratorInfo, + ComputedFieldInfo, +]""" + +ReturnType = TypeVar('ReturnType') +DecoratedType: TypeAlias = ( + 'Union[classmethod[Any, Any, ReturnType], staticmethod[Any, ReturnType], Callable[..., ReturnType], property]' +) + + +@dataclass # can't use slots here since we set attributes on `__post_init__` +class PydanticDescriptorProxy(Generic[ReturnType]): + """Wrap a classmethod, staticmethod, property or unbound function + and act as a descriptor that allows us to detect decorated items + from the class' attributes. + + This class' __get__ returns the wrapped item's __get__ result, + which makes it transparent for classmethods and staticmethods. + + Attributes: + wrapped: The decorator that has to be wrapped. + decorator_info: The decorator info. + shim: A wrapper function to wrap V1 style function. + """ + + wrapped: DecoratedType[ReturnType] + decorator_info: DecoratorInfo + shim: Callable[[Callable[..., Any]], Callable[..., Any]] | None = None + + def __post_init__(self): + for attr in 'setter', 'deleter': + if hasattr(self.wrapped, attr): + f = partial(self._call_wrapped_attr, name=attr) + setattr(self, attr, f) + + def _call_wrapped_attr(self, func: Callable[[Any], None], *, name: str) -> PydanticDescriptorProxy[ReturnType]: + self.wrapped = getattr(self.wrapped, name)(func) + return self + + def __get__(self, obj: object | None, obj_type: type[object] | None = None) -> PydanticDescriptorProxy[ReturnType]: + try: + return self.wrapped.__get__(obj, obj_type) + except AttributeError: + # not a descriptor, e.g. a partial object + return self.wrapped # type: ignore[return-value] + + def __set_name__(self, instance: Any, name: str) -> None: + if hasattr(self.wrapped, '__set_name__'): + self.wrapped.__set_name__(instance, name) # pyright: ignore[reportFunctionMemberAccess] + + def __getattr__(self, __name: str) -> Any: + """Forward checks for __isabstractmethod__ and such.""" + return getattr(self.wrapped, __name) + + +DecoratorInfoType = TypeVar('DecoratorInfoType', bound=DecoratorInfo) + + +@dataclass(**slots_true) +class Decorator(Generic[DecoratorInfoType]): + """A generic container class to join together the decorator metadata + (metadata from decorator itself, which we have when the + decorator is called but not when we are building the core-schema) + and the bound function (which we have after the class itself is created). + + Attributes: + cls_ref: The class ref. + cls_var_name: The decorated function name. + func: The decorated function. + shim: A wrapper function to wrap V1 style function. + info: The decorator info. + """ + + cls_ref: str + cls_var_name: str + func: Callable[..., Any] + shim: Callable[[Any], Any] | None + info: DecoratorInfoType + + @staticmethod + def build( + cls_: Any, + *, + cls_var_name: str, + shim: Callable[[Any], Any] | None, + info: DecoratorInfoType, + ) -> Decorator[DecoratorInfoType]: + """Build a new decorator. + + Args: + cls_: The class. + cls_var_name: The decorated function name. + shim: A wrapper function to wrap V1 style function. + info: The decorator info. + + Returns: + The new decorator instance. + """ + func = get_attribute_from_bases(cls_, cls_var_name) + if shim is not None: + func = shim(func) + func = unwrap_wrapped_function(func, unwrap_partial=False) + if not callable(func): + # This branch will get hit for classmethod properties + attribute = get_attribute_from_base_dicts(cls_, cls_var_name) # prevents the binding call to `__get__` + if isinstance(attribute, PydanticDescriptorProxy): + func = unwrap_wrapped_function(attribute.wrapped) + return Decorator( + cls_ref=get_type_ref(cls_), + cls_var_name=cls_var_name, + func=func, + shim=shim, + info=info, + ) + + def bind_to_cls(self, cls: Any) -> Decorator[DecoratorInfoType]: + """Bind the decorator to a class. + + Args: + cls: the class. + + Returns: + The new decorator instance. + """ + return self.build( + cls, + cls_var_name=self.cls_var_name, + shim=self.shim, + info=self.info, + ) + + +def get_bases(tp: type[Any]) -> tuple[type[Any], ...]: + """Get the base classes of a class or typeddict. + + Args: + tp: The type or class to get the bases. + + Returns: + The base classes. + """ + if is_typeddict(tp): + return tp.__orig_bases__ # type: ignore + try: + return tp.__bases__ + except AttributeError: + return () + + +def mro(tp: type[Any]) -> tuple[type[Any], ...]: + """Calculate the Method Resolution Order of bases using the C3 algorithm. + + See https://www.python.org/download/releases/2.3/mro/ + """ + # try to use the existing mro, for performance mainly + # but also because it helps verify the implementation below + if not is_typeddict(tp): + try: + return tp.__mro__ + except AttributeError: + # GenericAlias and some other cases + pass + + bases = get_bases(tp) + return (tp,) + mro_for_bases(bases) + + +def mro_for_bases(bases: tuple[type[Any], ...]) -> tuple[type[Any], ...]: + def merge_seqs(seqs: list[deque[type[Any]]]) -> Iterable[type[Any]]: + while True: + non_empty = [seq for seq in seqs if seq] + if not non_empty: + # Nothing left to process, we're done. + return + candidate: type[Any] | None = None + for seq in non_empty: # Find merge candidates among seq heads. + candidate = seq[0] + not_head = [s for s in non_empty if candidate in islice(s, 1, None)] + if not_head: + # Reject the candidate. + candidate = None + else: + break + if not candidate: + raise TypeError('Inconsistent hierarchy, no C3 MRO is possible') + yield candidate + for seq in non_empty: + # Remove candidate. + if seq[0] == candidate: + seq.popleft() + + seqs = [deque(mro(base)) for base in bases] + [deque(bases)] + return tuple(merge_seqs(seqs)) + + +_sentinel = object() + + +def get_attribute_from_bases(tp: type[Any] | tuple[type[Any], ...], name: str) -> Any: + """Get the attribute from the next class in the MRO that has it, + aiming to simulate calling the method on the actual class. + + The reason for iterating over the mro instead of just getting + the attribute (which would do that for us) is to support TypedDict, + which lacks a real __mro__, but can have a virtual one constructed + from its bases (as done here). + + Args: + tp: The type or class to search for the attribute. If a tuple, this is treated as a set of base classes. + name: The name of the attribute to retrieve. + + Returns: + Any: The attribute value, if found. + + Raises: + AttributeError: If the attribute is not found in any class in the MRO. + """ + if isinstance(tp, tuple): + for base in mro_for_bases(tp): + attribute = base.__dict__.get(name, _sentinel) + if attribute is not _sentinel: + attribute_get = getattr(attribute, '__get__', None) + if attribute_get is not None: + return attribute_get(None, tp) + return attribute + raise AttributeError(f'{name} not found in {tp}') + else: + try: + return getattr(tp, name) + except AttributeError: + return get_attribute_from_bases(mro(tp), name) + + +def get_attribute_from_base_dicts(tp: type[Any], name: str) -> Any: + """Get an attribute out of the `__dict__` following the MRO. + This prevents the call to `__get__` on the descriptor, and allows + us to get the original function for classmethod properties. + + Args: + tp: The type or class to search for the attribute. + name: The name of the attribute to retrieve. + + Returns: + Any: The attribute value, if found. + + Raises: + KeyError: If the attribute is not found in any class's `__dict__` in the MRO. + """ + for base in reversed(mro(tp)): + if name in base.__dict__: + return base.__dict__[name] + return tp.__dict__[name] # raise the error + + +@dataclass(**slots_true) +class DecoratorInfos: + """Mapping of name in the class namespace to decorator info. + + note that the name in the class namespace is the function or attribute name + not the field name! + """ + + validators: dict[str, Decorator[ValidatorDecoratorInfo]] = field(default_factory=dict) + field_validators: dict[str, Decorator[FieldValidatorDecoratorInfo]] = field(default_factory=dict) + root_validators: dict[str, Decorator[RootValidatorDecoratorInfo]] = field(default_factory=dict) + field_serializers: dict[str, Decorator[FieldSerializerDecoratorInfo]] = field(default_factory=dict) + model_serializers: dict[str, Decorator[ModelSerializerDecoratorInfo]] = field(default_factory=dict) + model_validators: dict[str, Decorator[ModelValidatorDecoratorInfo]] = field(default_factory=dict) + computed_fields: dict[str, Decorator[ComputedFieldInfo]] = field(default_factory=dict) + + @staticmethod + def build(model_dc: type[Any]) -> DecoratorInfos: # noqa: C901 (ignore complexity) + """We want to collect all DecFunc instances that exist as + attributes in the namespace of the class (a BaseModel or dataclass) + that called us + But we want to collect these in the order of the bases + So instead of getting them all from the leaf class (the class that called us), + we traverse the bases from root (the oldest ancestor class) to leaf + and collect all of the instances as we go, taking care to replace + any duplicate ones with the last one we see to mimic how function overriding + works with inheritance. + If we do replace any functions we put the replacement into the position + the replaced function was in; that is, we maintain the order. + """ + # reminder: dicts are ordered and replacement does not alter the order + res = DecoratorInfos() + for base in reversed(mro(model_dc)[1:]): + existing: DecoratorInfos | None = base.__dict__.get('__pydantic_decorators__') + if existing is None: + existing = DecoratorInfos.build(base) + res.validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.validators.items()}) + res.field_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.field_validators.items()}) + res.root_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.root_validators.items()}) + res.field_serializers.update({k: v.bind_to_cls(model_dc) for k, v in existing.field_serializers.items()}) + res.model_serializers.update({k: v.bind_to_cls(model_dc) for k, v in existing.model_serializers.items()}) + res.model_validators.update({k: v.bind_to_cls(model_dc) for k, v in existing.model_validators.items()}) + res.computed_fields.update({k: v.bind_to_cls(model_dc) for k, v in existing.computed_fields.items()}) + + to_replace: list[tuple[str, Any]] = [] + + for var_name, var_value in vars(model_dc).items(): + if isinstance(var_value, PydanticDescriptorProxy): + info = var_value.decorator_info + if isinstance(info, ValidatorDecoratorInfo): + res.validators[var_name] = Decorator.build( + model_dc, cls_var_name=var_name, shim=var_value.shim, info=info + ) + elif isinstance(info, FieldValidatorDecoratorInfo): + res.field_validators[var_name] = Decorator.build( + model_dc, cls_var_name=var_name, shim=var_value.shim, info=info + ) + elif isinstance(info, RootValidatorDecoratorInfo): + res.root_validators[var_name] = Decorator.build( + model_dc, cls_var_name=var_name, shim=var_value.shim, info=info + ) + elif isinstance(info, FieldSerializerDecoratorInfo): + # check whether a serializer function is already registered for fields + for field_serializer_decorator in res.field_serializers.values(): + # check that each field has at most one serializer function. + # serializer functions for the same field in subclasses are allowed, + # and are treated as overrides + if field_serializer_decorator.cls_var_name == var_name: + continue + for f in info.fields: + if f in field_serializer_decorator.info.fields: + raise PydanticUserError( + 'Multiple field serializer functions were defined ' + f'for field {f!r}, this is not allowed.', + code='multiple-field-serializers', + ) + res.field_serializers[var_name] = Decorator.build( + model_dc, cls_var_name=var_name, shim=var_value.shim, info=info + ) + elif isinstance(info, ModelValidatorDecoratorInfo): + res.model_validators[var_name] = Decorator.build( + model_dc, cls_var_name=var_name, shim=var_value.shim, info=info + ) + elif isinstance(info, ModelSerializerDecoratorInfo): + res.model_serializers[var_name] = Decorator.build( + model_dc, cls_var_name=var_name, shim=var_value.shim, info=info + ) + else: + from ..fields import ComputedFieldInfo + + isinstance(var_value, ComputedFieldInfo) + res.computed_fields[var_name] = Decorator.build( + model_dc, cls_var_name=var_name, shim=None, info=info + ) + to_replace.append((var_name, var_value.wrapped)) + if to_replace: + # If we can save `__pydantic_decorators__` on the class we'll be able to check for it above + # so then we don't need to re-process the type, which means we can discard our descriptor wrappers + # and replace them with the thing they are wrapping (see the other setattr call below) + # which allows validator class methods to also function as regular class methods + setattr(model_dc, '__pydantic_decorators__', res) + for name, value in to_replace: + setattr(model_dc, name, value) + return res + + +def inspect_validator(validator: Callable[..., Any], mode: FieldValidatorModes) -> bool: + """Look at a field or model validator function and determine whether it takes an info argument. + + An error is raised if the function has an invalid signature. + + Args: + validator: The validator function to inspect. + mode: The proposed validator mode. + + Returns: + Whether the validator takes an info argument. + """ + try: + sig = signature(validator) + except (ValueError, TypeError): + # `inspect.signature` might not be able to infer a signature, e.g. with C objects. + # In this case, we assume no info argument is present: + return False + n_positional = count_positional_required_params(sig) + if mode == 'wrap': + if n_positional == 3: + return True + elif n_positional == 2: + return False + else: + assert mode in {'before', 'after', 'plain'}, f"invalid mode: {mode!r}, expected 'before', 'after' or 'plain" + if n_positional == 2: + return True + elif n_positional == 1: + return False + + raise PydanticUserError( + f'Unrecognized field_validator function signature for {validator} with `mode={mode}`:{sig}', + code='validator-signature', + ) + + +def inspect_field_serializer( + serializer: Callable[..., Any], mode: Literal['plain', 'wrap'], computed_field: bool = False +) -> tuple[bool, bool]: + """Look at a field serializer function and determine if it is a field serializer, + and whether it takes an info argument. + + An error is raised if the function has an invalid signature. + + Args: + serializer: The serializer function to inspect. + mode: The serializer mode, either 'plain' or 'wrap'. + computed_field: When serializer is applied on computed_field. It doesn't require + info signature. + + Returns: + Tuple of (is_field_serializer, info_arg). + """ + try: + sig = signature(serializer) + except (ValueError, TypeError): + # `inspect.signature` might not be able to infer a signature, e.g. with C objects. + # In this case, we assume no info argument is present and this is not a method: + return (False, False) + + first = next(iter(sig.parameters.values()), None) + is_field_serializer = first is not None and first.name == 'self' + + n_positional = count_positional_required_params(sig) + if is_field_serializer: + # -1 to correct for self parameter + info_arg = _serializer_info_arg(mode, n_positional - 1) + else: + info_arg = _serializer_info_arg(mode, n_positional) + + if info_arg is None: + raise PydanticUserError( + f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}', + code='field-serializer-signature', + ) + if info_arg and computed_field: + raise PydanticUserError( + 'field_serializer on computed_field does not use info signature', code='field-serializer-signature' + ) + + else: + return is_field_serializer, info_arg + + +def inspect_annotated_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool: + """Look at a serializer function used via `Annotated` and determine whether it takes an info argument. + + An error is raised if the function has an invalid signature. + + Args: + serializer: The serializer function to check. + mode: The serializer mode, either 'plain' or 'wrap'. + + Returns: + info_arg + """ + try: + sig = signature(serializer) + except (ValueError, TypeError): + # `inspect.signature` might not be able to infer a signature, e.g. with C objects. + # In this case, we assume no info argument is present: + return False + info_arg = _serializer_info_arg(mode, count_positional_required_params(sig)) + if info_arg is None: + raise PydanticUserError( + f'Unrecognized field_serializer function signature for {serializer} with `mode={mode}`:{sig}', + code='field-serializer-signature', + ) + else: + return info_arg + + +def inspect_model_serializer(serializer: Callable[..., Any], mode: Literal['plain', 'wrap']) -> bool: + """Look at a model serializer function and determine whether it takes an info argument. + + An error is raised if the function has an invalid signature. + + Args: + serializer: The serializer function to check. + mode: The serializer mode, either 'plain' or 'wrap'. + + Returns: + `info_arg` - whether the function expects an info argument. + """ + if isinstance(serializer, (staticmethod, classmethod)) or not is_instance_method_from_sig(serializer): + raise PydanticUserError( + '`@model_serializer` must be applied to instance methods', code='model-serializer-instance-method' + ) + + sig = signature(serializer) + info_arg = _serializer_info_arg(mode, count_positional_required_params(sig)) + if info_arg is None: + raise PydanticUserError( + f'Unrecognized model_serializer function signature for {serializer} with `mode={mode}`:{sig}', + code='model-serializer-signature', + ) + else: + return info_arg + + +def _serializer_info_arg(mode: Literal['plain', 'wrap'], n_positional: int) -> bool | None: + if mode == 'plain': + if n_positional == 1: + # (input_value: Any, /) -> Any + return False + elif n_positional == 2: + # (model: Any, input_value: Any, /) -> Any + return True + else: + assert mode == 'wrap', f"invalid mode: {mode!r}, expected 'plain' or 'wrap'" + if n_positional == 2: + # (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any + return False + elif n_positional == 3: + # (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any + return True + + return None + + +AnyDecoratorCallable: TypeAlias = ( + 'Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any], Callable[..., Any]]' +) + + +def is_instance_method_from_sig(function: AnyDecoratorCallable) -> bool: + """Whether the function is an instance method. + + It will consider a function as instance method if the first parameter of + function is `self`. + + Args: + function: The function to check. + + Returns: + `True` if the function is an instance method, `False` otherwise. + """ + sig = signature(unwrap_wrapped_function(function)) + first = next(iter(sig.parameters.values()), None) + if first and first.name == 'self': + return True + return False + + +def ensure_classmethod_based_on_signature(function: AnyDecoratorCallable) -> Any: + """Apply the `@classmethod` decorator on the function. + + Args: + function: The function to apply the decorator on. + + Return: + The `@classmethod` decorator applied function. + """ + if not isinstance( + unwrap_wrapped_function(function, unwrap_class_static_method=False), classmethod + ) and _is_classmethod_from_sig(function): + return classmethod(function) # type: ignore[arg-type] + return function + + +def _is_classmethod_from_sig(function: AnyDecoratorCallable) -> bool: + sig = signature(unwrap_wrapped_function(function)) + first = next(iter(sig.parameters.values()), None) + if first and first.name == 'cls': + return True + return False + + +def unwrap_wrapped_function( + func: Any, + *, + unwrap_partial: bool = True, + unwrap_class_static_method: bool = True, +) -> Any: + """Recursively unwraps a wrapped function until the underlying function is reached. + This handles property, functools.partial, functools.partialmethod, staticmethod, and classmethod. + + Args: + func: The function to unwrap. + unwrap_partial: If True (default), unwrap partial and partialmethod decorators. + unwrap_class_static_method: If True (default), also unwrap classmethod and staticmethod + decorators. If False, only unwrap partial and partialmethod decorators. + + Returns: + The underlying function of the wrapped function. + """ + # Define the types we want to check against as a single tuple. + unwrap_types = ( + (property, cached_property) + + ((partial, partialmethod) if unwrap_partial else ()) + + ((staticmethod, classmethod) if unwrap_class_static_method else ()) + ) + + while isinstance(func, unwrap_types): + if unwrap_class_static_method and isinstance(func, (classmethod, staticmethod)): + func = func.__func__ + elif isinstance(func, (partial, partialmethod)): + func = func.func + elif isinstance(func, property): + func = func.fget # arbitrary choice, convenient for computed fields + else: + # Make coverage happy as it can only get here in the last possible case + assert isinstance(func, cached_property) + func = func.func # type: ignore + + return func + + +def get_function_return_type( + func: Any, explicit_return_type: Any, types_namespace: dict[str, Any] | None = None +) -> Any: + """Get the function return type. + + It gets the return type from the type annotation if `explicit_return_type` is `None`. + Otherwise, it returns `explicit_return_type`. + + Args: + func: The function to get its return type. + explicit_return_type: The explicit return type. + types_namespace: The types namespace, defaults to `None`. + + Returns: + The function return type. + """ + if explicit_return_type is PydanticUndefined: + # try to get it from the type annotation + hints = get_function_type_hints( + unwrap_wrapped_function(func), include_keys={'return'}, types_namespace=types_namespace + ) + return hints.get('return', PydanticUndefined) + else: + return explicit_return_type + + +def count_positional_required_params(sig: Signature) -> int: + """Get the number of positional (required) arguments of a signature. + + This function should only be used to inspect signatures of validation and serialization functions. + The first argument (the value being serialized or validated) is counted as a required argument + even if a default value exists. + + Returns: + The number of positional arguments of a signature. + """ + parameters = list(sig.parameters.values()) + return sum( + 1 + for param in parameters + if can_be_positional(param) + # First argument is the value being validated/serialized, and can have a default value + # (e.g. `float`, which has signature `(x=0, /)`). We assume other parameters (the info arg + # for instance) should be required, and thus without any default value. + and (param.default is Parameter.empty or param == parameters[0]) + ) + + +def can_be_positional(param: Parameter) -> bool: + return param.kind in (Parameter.POSITIONAL_ONLY, Parameter.POSITIONAL_OR_KEYWORD) + + +def ensure_property(f: Any) -> Any: + """Ensure that a function is a `property` or `cached_property`, or is a valid descriptor. + + Args: + f: The function to check. + + Returns: + The function, or a `property` or `cached_property` instance wrapping the function. + """ + if ismethoddescriptor(f) or isdatadescriptor(f): + return f + else: + return property(f) diff --git a/env/Lib/site-packages/pydantic/_internal/_decorators_v1.py b/env/Lib/site-packages/pydantic/_internal/_decorators_v1.py new file mode 100644 index 0000000..0957e01 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_decorators_v1.py @@ -0,0 +1,174 @@ +"""Logic for V1 validators, e.g. `@validator` and `@root_validator`.""" + +from __future__ import annotations as _annotations + +from inspect import Parameter, signature +from typing import Any, Dict, Tuple, Union, cast + +from pydantic_core import core_schema +from typing_extensions import Protocol + +from ..errors import PydanticUserError +from ._decorators import can_be_positional + + +class V1OnlyValueValidator(Protocol): + """A simple validator, supported for V1 validators and V2 validators.""" + + def __call__(self, __value: Any) -> Any: ... + + +class V1ValidatorWithValues(Protocol): + """A validator with `values` argument, supported for V1 validators and V2 validators.""" + + def __call__(self, __value: Any, values: dict[str, Any]) -> Any: ... + + +class V1ValidatorWithValuesKwOnly(Protocol): + """A validator with keyword only `values` argument, supported for V1 validators and V2 validators.""" + + def __call__(self, __value: Any, *, values: dict[str, Any]) -> Any: ... + + +class V1ValidatorWithKwargs(Protocol): + """A validator with `kwargs` argument, supported for V1 validators and V2 validators.""" + + def __call__(self, __value: Any, **kwargs: Any) -> Any: ... + + +class V1ValidatorWithValuesAndKwargs(Protocol): + """A validator with `values` and `kwargs` arguments, supported for V1 validators and V2 validators.""" + + def __call__(self, __value: Any, values: dict[str, Any], **kwargs: Any) -> Any: ... + + +V1Validator = Union[ + V1ValidatorWithValues, V1ValidatorWithValuesKwOnly, V1ValidatorWithKwargs, V1ValidatorWithValuesAndKwargs +] + + +def can_be_keyword(param: Parameter) -> bool: + return param.kind in (Parameter.POSITIONAL_OR_KEYWORD, Parameter.KEYWORD_ONLY) + + +def make_generic_v1_field_validator(validator: V1Validator) -> core_schema.WithInfoValidatorFunction: + """Wrap a V1 style field validator for V2 compatibility. + + Args: + validator: The V1 style field validator. + + Returns: + A wrapped V2 style field validator. + + Raises: + PydanticUserError: If the signature is not supported or the parameters are + not available in Pydantic V2. + """ + sig = signature(validator) + + needs_values_kw = False + + for param_num, (param_name, parameter) in enumerate(sig.parameters.items()): + if can_be_keyword(parameter) and param_name in ('field', 'config'): + raise PydanticUserError( + 'The `field` and `config` parameters are not available in Pydantic V2, ' + 'please use the `info` parameter instead.', + code='validator-field-config-info', + ) + if parameter.kind is Parameter.VAR_KEYWORD: + needs_values_kw = True + elif can_be_keyword(parameter) and param_name == 'values': + needs_values_kw = True + elif can_be_positional(parameter) and param_num == 0: + # value + continue + elif parameter.default is Parameter.empty: # ignore params with defaults e.g. bound by functools.partial + raise PydanticUserError( + f'Unsupported signature for V1 style validator {validator}: {sig} is not supported.', + code='validator-v1-signature', + ) + + if needs_values_kw: + # (v, **kwargs), (v, values, **kwargs), (v, *, values, **kwargs) or (v, *, values) + val1 = cast(V1ValidatorWithValues, validator) + + def wrapper1(value: Any, info: core_schema.ValidationInfo) -> Any: + return val1(value, values=info.data) + + return wrapper1 + else: + val2 = cast(V1OnlyValueValidator, validator) + + def wrapper2(value: Any, _: core_schema.ValidationInfo) -> Any: + return val2(value) + + return wrapper2 + + +RootValidatorValues = Dict[str, Any] +# technically tuple[model_dict, model_extra, fields_set] | tuple[dataclass_dict, init_vars] +RootValidatorFieldsTuple = Tuple[Any, ...] + + +class V1RootValidatorFunction(Protocol): + """A simple root validator, supported for V1 validators and V2 validators.""" + + def __call__(self, __values: RootValidatorValues) -> RootValidatorValues: ... + + +class V2CoreBeforeRootValidator(Protocol): + """V2 validator with mode='before'.""" + + def __call__(self, __values: RootValidatorValues, __info: core_schema.ValidationInfo) -> RootValidatorValues: ... + + +class V2CoreAfterRootValidator(Protocol): + """V2 validator with mode='after'.""" + + def __call__( + self, __fields_tuple: RootValidatorFieldsTuple, __info: core_schema.ValidationInfo + ) -> RootValidatorFieldsTuple: ... + + +def make_v1_generic_root_validator( + validator: V1RootValidatorFunction, pre: bool +) -> V2CoreBeforeRootValidator | V2CoreAfterRootValidator: + """Wrap a V1 style root validator for V2 compatibility. + + Args: + validator: The V1 style field validator. + pre: Whether the validator is a pre validator. + + Returns: + A wrapped V2 style validator. + """ + if pre is True: + # mode='before' for pydantic-core + def _wrapper1(values: RootValidatorValues, _: core_schema.ValidationInfo) -> RootValidatorValues: + return validator(values) + + return _wrapper1 + + # mode='after' for pydantic-core + def _wrapper2(fields_tuple: RootValidatorFieldsTuple, _: core_schema.ValidationInfo) -> RootValidatorFieldsTuple: + if len(fields_tuple) == 2: + # dataclass, this is easy + values, init_vars = fields_tuple + values = validator(values) + return values, init_vars + else: + # ugly hack: to match v1 behaviour, we merge values and model_extra, then split them up based on fields + # afterwards + model_dict, model_extra, fields_set = fields_tuple + if model_extra: + fields = set(model_dict.keys()) + model_dict.update(model_extra) + model_dict_new = validator(model_dict) + for k in list(model_dict_new.keys()): + if k not in fields: + model_extra[k] = model_dict_new.pop(k) + else: + model_dict_new = validator(model_dict) + return model_dict_new, model_extra, fields_set + + return _wrapper2 diff --git a/env/Lib/site-packages/pydantic/_internal/_discriminated_union.py b/env/Lib/site-packages/pydantic/_internal/_discriminated_union.py new file mode 100644 index 0000000..a090c36 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_discriminated_union.py @@ -0,0 +1,503 @@ +from __future__ import annotations as _annotations + +from typing import TYPE_CHECKING, Any, Hashable, Sequence + +from pydantic_core import CoreSchema, core_schema + +from ..errors import PydanticUserError +from . import _core_utils +from ._core_utils import ( + CoreSchemaField, + collect_definitions, +) + +if TYPE_CHECKING: + from ..types import Discriminator + +CORE_SCHEMA_METADATA_DISCRIMINATOR_PLACEHOLDER_KEY = 'pydantic.internal.union_discriminator' + + +class MissingDefinitionForUnionRef(Exception): + """Raised when applying a discriminated union discriminator to a schema + requires a definition that is not yet defined + """ + + def __init__(self, ref: str) -> None: + self.ref = ref + super().__init__(f'Missing definition for ref {self.ref!r}') + + +def set_discriminator_in_metadata(schema: CoreSchema, discriminator: Any) -> None: + schema.setdefault('metadata', {}) + metadata = schema.get('metadata') + assert metadata is not None + metadata[CORE_SCHEMA_METADATA_DISCRIMINATOR_PLACEHOLDER_KEY] = discriminator + + +def apply_discriminators(schema: core_schema.CoreSchema) -> core_schema.CoreSchema: + # We recursively walk through the `schema` passed to `apply_discriminators`, applying discriminators + # where necessary at each level. During this recursion, we allow references to be resolved from the definitions + # that are originally present on the original, outermost `schema`. Before `apply_discriminators` is called, + # `simplify_schema_references` is called on the schema (in the `clean_schema` function), + # which often puts the definitions in the outermost schema. + global_definitions: dict[str, CoreSchema] = collect_definitions(schema) + + def inner(s: core_schema.CoreSchema, recurse: _core_utils.Recurse) -> core_schema.CoreSchema: + nonlocal global_definitions + + s = recurse(s, inner) + if s['type'] == 'tagged-union': + return s + + metadata = s.get('metadata', {}) + discriminator = metadata.pop(CORE_SCHEMA_METADATA_DISCRIMINATOR_PLACEHOLDER_KEY, None) + if discriminator is not None: + s = apply_discriminator(s, discriminator, global_definitions) + return s + + return _core_utils.walk_core_schema(schema, inner) + + +def apply_discriminator( + schema: core_schema.CoreSchema, + discriminator: str | Discriminator, + definitions: dict[str, core_schema.CoreSchema] | None = None, +) -> core_schema.CoreSchema: + """Applies the discriminator and returns a new core schema. + + Args: + schema: The input schema. + discriminator: The name of the field which will serve as the discriminator. + definitions: A mapping of schema ref to schema. + + Returns: + The new core schema. + + Raises: + TypeError: + - If `discriminator` is used with invalid union variant. + - If `discriminator` is used with `Union` type with one variant. + - If `discriminator` value mapped to multiple choices. + MissingDefinitionForUnionRef: + If the definition for ref is missing. + PydanticUserError: + - If a model in union doesn't have a discriminator field. + - If discriminator field has a non-string alias. + - If discriminator fields have different aliases. + - If discriminator field not of type `Literal`. + """ + from ..types import Discriminator + + if isinstance(discriminator, Discriminator): + if isinstance(discriminator.discriminator, str): + discriminator = discriminator.discriminator + else: + return discriminator._convert_schema(schema) + + return _ApplyInferredDiscriminator(discriminator, definitions or {}).apply(schema) + + +class _ApplyInferredDiscriminator: + """This class is used to convert an input schema containing a union schema into one where that union is + replaced with a tagged-union, with all the associated debugging and performance benefits. + + This is done by: + * Validating that the input schema is compatible with the provided discriminator + * Introspecting the schema to determine which discriminator values should map to which union choices + * Handling various edge cases such as 'definitions', 'default', 'nullable' schemas, and more + + I have chosen to implement the conversion algorithm in this class, rather than a function, + to make it easier to maintain state while recursively walking the provided CoreSchema. + """ + + def __init__(self, discriminator: str, definitions: dict[str, core_schema.CoreSchema]): + # `discriminator` should be the name of the field which will serve as the discriminator. + # It must be the python name of the field, and *not* the field's alias. Note that as of now, + # all members of a discriminated union _must_ use a field with the same name as the discriminator. + # This may change if/when we expose a way to manually specify the TaggedUnionSchema's choices. + self.discriminator = discriminator + + # `definitions` should contain a mapping of schema ref to schema for all schemas which might + # be referenced by some choice + self.definitions = definitions + + # `_discriminator_alias` will hold the value, if present, of the alias for the discriminator + # + # Note: following the v1 implementation, we currently disallow the use of different aliases + # for different choices. This is not a limitation of pydantic_core, but if we try to handle + # this, the inference logic gets complicated very quickly, and could result in confusing + # debugging challenges for users making subtle mistakes. + # + # Rather than trying to do the most powerful inference possible, I think we should eventually + # expose a way to more-manually control the way the TaggedUnionSchema is constructed through + # the use of a new type which would be placed as an Annotation on the Union type. This would + # provide the full flexibility/power of pydantic_core's TaggedUnionSchema where necessary for + # more complex cases, without over-complicating the inference logic for the common cases. + self._discriminator_alias: str | None = None + + # `_should_be_nullable` indicates whether the converted union has `None` as an allowed value. + # If `None` is an acceptable value of the (possibly-wrapped) union, we ignore it while + # constructing the TaggedUnionSchema, but set the `_should_be_nullable` attribute to True. + # Once we have constructed the TaggedUnionSchema, if `_should_be_nullable` is True, we ensure + # that the final schema gets wrapped as a NullableSchema. This has the same semantics on the + # python side, but resolves the issue that `None` cannot correspond to any discriminator values. + self._should_be_nullable = False + + # `_is_nullable` is used to track if the final produced schema will definitely be nullable; + # we set it to True if the input schema is wrapped in a nullable schema that we know will be preserved + # as an indication that, even if None is discovered as one of the union choices, we will not need to wrap + # the final value in another nullable schema. + # + # This is more complicated than just checking for the final outermost schema having type 'nullable' thanks + # to the possible presence of other wrapper schemas such as DefinitionsSchema, WithDefaultSchema, etc. + self._is_nullable = False + + # `_choices_to_handle` serves as a stack of choices to add to the tagged union. Initially, choices + # from the union in the wrapped schema will be appended to this list, and the recursive choice-handling + # algorithm may add more choices to this stack as (nested) unions are encountered. + self._choices_to_handle: list[core_schema.CoreSchema] = [] + + # `_tagged_union_choices` is built during the call to `apply`, and will hold the choices to be included + # in the output TaggedUnionSchema that will replace the union from the input schema + self._tagged_union_choices: dict[Hashable, core_schema.CoreSchema] = {} + + # `_used` is changed to True after applying the discriminator to prevent accidental re-use + self._used = False + + def apply(self, schema: core_schema.CoreSchema) -> core_schema.CoreSchema: + """Return a new CoreSchema based on `schema` that uses a tagged-union with the discriminator provided + to this class. + + Args: + schema: The input schema. + + Returns: + The new core schema. + + Raises: + TypeError: + - If `discriminator` is used with invalid union variant. + - If `discriminator` is used with `Union` type with one variant. + - If `discriminator` value mapped to multiple choices. + ValueError: + If the definition for ref is missing. + PydanticUserError: + - If a model in union doesn't have a discriminator field. + - If discriminator field has a non-string alias. + - If discriminator fields have different aliases. + - If discriminator field not of type `Literal`. + """ + assert not self._used + schema = self._apply_to_root(schema) + if self._should_be_nullable and not self._is_nullable: + schema = core_schema.nullable_schema(schema) + self._used = True + return schema + + def _apply_to_root(self, schema: core_schema.CoreSchema) -> core_schema.CoreSchema: + """This method handles the outer-most stage of recursion over the input schema: + unwrapping nullable or definitions schemas, and calling the `_handle_choice` + method iteratively on the choices extracted (recursively) from the possibly-wrapped union. + """ + if schema['type'] == 'nullable': + self._is_nullable = True + wrapped = self._apply_to_root(schema['schema']) + nullable_wrapper = schema.copy() + nullable_wrapper['schema'] = wrapped + return nullable_wrapper + + if schema['type'] == 'definitions': + wrapped = self._apply_to_root(schema['schema']) + definitions_wrapper = schema.copy() + definitions_wrapper['schema'] = wrapped + return definitions_wrapper + + if schema['type'] != 'union': + # If the schema is not a union, it probably means it just had a single member and + # was flattened by pydantic_core. + # However, it still may make sense to apply the discriminator to this schema, + # as a way to get discriminated-union-style error messages, so we allow this here. + schema = core_schema.union_schema([schema]) + + # Reverse the choices list before extending the stack so that they get handled in the order they occur + choices_schemas = [v[0] if isinstance(v, tuple) else v for v in schema['choices'][::-1]] + self._choices_to_handle.extend(choices_schemas) + while self._choices_to_handle: + choice = self._choices_to_handle.pop() + self._handle_choice(choice) + + if self._discriminator_alias is not None and self._discriminator_alias != self.discriminator: + # * We need to annotate `discriminator` as a union here to handle both branches of this conditional + # * We need to annotate `discriminator` as list[list[str | int]] and not list[list[str]] due to the + # invariance of list, and because list[list[str | int]] is the type of the discriminator argument + # to tagged_union_schema below + # * See the docstring of pydantic_core.core_schema.tagged_union_schema for more details about how to + # interpret the value of the discriminator argument to tagged_union_schema. (The list[list[str]] here + # is the appropriate way to provide a list of fallback attributes to check for a discriminator value.) + discriminator: str | list[list[str | int]] = [[self.discriminator], [self._discriminator_alias]] + else: + discriminator = self.discriminator + return core_schema.tagged_union_schema( + choices=self._tagged_union_choices, + discriminator=discriminator, + custom_error_type=schema.get('custom_error_type'), + custom_error_message=schema.get('custom_error_message'), + custom_error_context=schema.get('custom_error_context'), + strict=False, + from_attributes=True, + ref=schema.get('ref'), + metadata=schema.get('metadata'), + serialization=schema.get('serialization'), + ) + + def _handle_choice(self, choice: core_schema.CoreSchema) -> None: + """This method handles the "middle" stage of recursion over the input schema. + Specifically, it is responsible for handling each choice of the outermost union + (and any "coalesced" choices obtained from inner unions). + + Here, "handling" entails: + * Coalescing nested unions and compatible tagged-unions + * Tracking the presence of 'none' and 'nullable' schemas occurring as choices + * Validating that each allowed discriminator value maps to a unique choice + * Updating the _tagged_union_choices mapping that will ultimately be used to build the TaggedUnionSchema. + """ + if choice['type'] == 'definition-ref': + if choice['schema_ref'] not in self.definitions: + raise MissingDefinitionForUnionRef(choice['schema_ref']) + + if choice['type'] == 'none': + self._should_be_nullable = True + elif choice['type'] == 'definitions': + self._handle_choice(choice['schema']) + elif choice['type'] == 'nullable': + self._should_be_nullable = True + self._handle_choice(choice['schema']) # unwrap the nullable schema + elif choice['type'] == 'union': + # Reverse the choices list before extending the stack so that they get handled in the order they occur + choices_schemas = [v[0] if isinstance(v, tuple) else v for v in choice['choices'][::-1]] + self._choices_to_handle.extend(choices_schemas) + elif choice['type'] not in { + 'model', + 'typed-dict', + 'tagged-union', + 'lax-or-strict', + 'dataclass', + 'dataclass-args', + 'definition-ref', + } and not _core_utils.is_function_with_inner_schema(choice): + # We should eventually handle 'definition-ref' as well + raise TypeError( + f'{choice["type"]!r} is not a valid discriminated union variant;' + ' should be a `BaseModel` or `dataclass`' + ) + else: + if choice['type'] == 'tagged-union' and self._is_discriminator_shared(choice): + # In this case, this inner tagged-union is compatible with the outer tagged-union, + # and its choices can be coalesced into the outer TaggedUnionSchema. + subchoices = [x for x in choice['choices'].values() if not isinstance(x, (str, int))] + # Reverse the choices list before extending the stack so that they get handled in the order they occur + self._choices_to_handle.extend(subchoices[::-1]) + return + + inferred_discriminator_values = self._infer_discriminator_values_for_choice(choice, source_name=None) + self._set_unique_choice_for_values(choice, inferred_discriminator_values) + + def _is_discriminator_shared(self, choice: core_schema.TaggedUnionSchema) -> bool: + """This method returns a boolean indicating whether the discriminator for the `choice` + is the same as that being used for the outermost tagged union. This is used to + determine whether this TaggedUnionSchema choice should be "coalesced" into the top level, + or whether it should be treated as a separate (nested) choice. + """ + inner_discriminator = choice['discriminator'] + return inner_discriminator == self.discriminator or ( + isinstance(inner_discriminator, list) + and (self.discriminator in inner_discriminator or [self.discriminator] in inner_discriminator) + ) + + def _infer_discriminator_values_for_choice( # noqa C901 + self, choice: core_schema.CoreSchema, source_name: str | None + ) -> list[str | int]: + """This function recurses over `choice`, extracting all discriminator values that should map to this choice. + + `model_name` is accepted for the purpose of producing useful error messages. + """ + if choice['type'] == 'definitions': + return self._infer_discriminator_values_for_choice(choice['schema'], source_name=source_name) + elif choice['type'] == 'function-plain': + raise TypeError( + f'{choice["type"]!r} is not a valid discriminated union variant;' + ' should be a `BaseModel` or `dataclass`' + ) + elif _core_utils.is_function_with_inner_schema(choice): + return self._infer_discriminator_values_for_choice(choice['schema'], source_name=source_name) + elif choice['type'] == 'lax-or-strict': + return sorted( + set( + self._infer_discriminator_values_for_choice(choice['lax_schema'], source_name=None) + + self._infer_discriminator_values_for_choice(choice['strict_schema'], source_name=None) + ) + ) + + elif choice['type'] == 'tagged-union': + values: list[str | int] = [] + # Ignore str/int "choices" since these are just references to other choices + subchoices = [x for x in choice['choices'].values() if not isinstance(x, (str, int))] + for subchoice in subchoices: + subchoice_values = self._infer_discriminator_values_for_choice(subchoice, source_name=None) + values.extend(subchoice_values) + return values + + elif choice['type'] == 'union': + values = [] + for subchoice in choice['choices']: + subchoice_schema = subchoice[0] if isinstance(subchoice, tuple) else subchoice + subchoice_values = self._infer_discriminator_values_for_choice(subchoice_schema, source_name=None) + values.extend(subchoice_values) + return values + + elif choice['type'] == 'nullable': + self._should_be_nullable = True + return self._infer_discriminator_values_for_choice(choice['schema'], source_name=None) + + elif choice['type'] == 'model': + return self._infer_discriminator_values_for_choice(choice['schema'], source_name=choice['cls'].__name__) + + elif choice['type'] == 'dataclass': + return self._infer_discriminator_values_for_choice(choice['schema'], source_name=choice['cls'].__name__) + + elif choice['type'] == 'model-fields': + return self._infer_discriminator_values_for_model_choice(choice, source_name=source_name) + + elif choice['type'] == 'dataclass-args': + return self._infer_discriminator_values_for_dataclass_choice(choice, source_name=source_name) + + elif choice['type'] == 'typed-dict': + return self._infer_discriminator_values_for_typed_dict_choice(choice, source_name=source_name) + + elif choice['type'] == 'definition-ref': + schema_ref = choice['schema_ref'] + if schema_ref not in self.definitions: + raise MissingDefinitionForUnionRef(schema_ref) + return self._infer_discriminator_values_for_choice(self.definitions[schema_ref], source_name=source_name) + else: + raise TypeError( + f'{choice["type"]!r} is not a valid discriminated union variant;' + ' should be a `BaseModel` or `dataclass`' + ) + + def _infer_discriminator_values_for_typed_dict_choice( + self, choice: core_schema.TypedDictSchema, source_name: str | None = None + ) -> list[str | int]: + """This method just extracts the _infer_discriminator_values_for_choice logic specific to TypedDictSchema + for the sake of readability. + """ + source = 'TypedDict' if source_name is None else f'TypedDict {source_name!r}' + field = choice['fields'].get(self.discriminator) + if field is None: + raise PydanticUserError( + f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field' + ) + return self._infer_discriminator_values_for_field(field, source) + + def _infer_discriminator_values_for_model_choice( + self, choice: core_schema.ModelFieldsSchema, source_name: str | None = None + ) -> list[str | int]: + source = 'ModelFields' if source_name is None else f'Model {source_name!r}' + field = choice['fields'].get(self.discriminator) + if field is None: + raise PydanticUserError( + f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field' + ) + return self._infer_discriminator_values_for_field(field, source) + + def _infer_discriminator_values_for_dataclass_choice( + self, choice: core_schema.DataclassArgsSchema, source_name: str | None = None + ) -> list[str | int]: + source = 'DataclassArgs' if source_name is None else f'Dataclass {source_name!r}' + for field in choice['fields']: + if field['name'] == self.discriminator: + break + else: + raise PydanticUserError( + f'{source} needs a discriminator field for key {self.discriminator!r}', code='discriminator-no-field' + ) + return self._infer_discriminator_values_for_field(field, source) + + def _infer_discriminator_values_for_field(self, field: CoreSchemaField, source: str) -> list[str | int]: + if field['type'] == 'computed-field': + # This should never occur as a discriminator, as it is only relevant to serialization + return [] + alias = field.get('validation_alias', self.discriminator) + if not isinstance(alias, str): + raise PydanticUserError( + f'Alias {alias!r} is not supported in a discriminated union', code='discriminator-alias-type' + ) + if self._discriminator_alias is None: + self._discriminator_alias = alias + elif self._discriminator_alias != alias: + raise PydanticUserError( + f'Aliases for discriminator {self.discriminator!r} must be the same ' + f'(got {alias}, {self._discriminator_alias})', + code='discriminator-alias', + ) + return self._infer_discriminator_values_for_inner_schema(field['schema'], source) + + def _infer_discriminator_values_for_inner_schema( + self, schema: core_schema.CoreSchema, source: str + ) -> list[str | int]: + """When inferring discriminator values for a field, we typically extract the expected values from a literal + schema. This function does that, but also handles nested unions and defaults. + """ + if schema['type'] == 'literal': + return schema['expected'] + + elif schema['type'] == 'union': + # Generally when multiple values are allowed they should be placed in a single `Literal`, but + # we add this case to handle the situation where a field is annotated as a `Union` of `Literal`s. + # For example, this lets us handle `Union[Literal['key'], Union[Literal['Key'], Literal['KEY']]]` + values: list[Any] = [] + for choice in schema['choices']: + choice_schema = choice[0] if isinstance(choice, tuple) else choice + choice_values = self._infer_discriminator_values_for_inner_schema(choice_schema, source) + values.extend(choice_values) + return values + + elif schema['type'] == 'default': + # This will happen if the field has a default value; we ignore it while extracting the discriminator values + return self._infer_discriminator_values_for_inner_schema(schema['schema'], source) + + elif schema['type'] == 'function-after': + # After validators don't affect the discriminator values + return self._infer_discriminator_values_for_inner_schema(schema['schema'], source) + + elif schema['type'] in {'function-before', 'function-wrap', 'function-plain'}: + validator_type = repr(schema['type'].split('-')[1]) + raise PydanticUserError( + f'Cannot use a mode={validator_type} validator in the' + f' discriminator field {self.discriminator!r} of {source}', + code='discriminator-validator', + ) + + else: + raise PydanticUserError( + f'{source} needs field {self.discriminator!r} to be of type `Literal`', + code='discriminator-needs-literal', + ) + + def _set_unique_choice_for_values(self, choice: core_schema.CoreSchema, values: Sequence[str | int]) -> None: + """This method updates `self.tagged_union_choices` so that all provided (discriminator) `values` map to the + provided `choice`, validating that none of these values already map to another (different) choice. + """ + for discriminator_value in values: + if discriminator_value in self._tagged_union_choices: + # It is okay if `value` is already in tagged_union_choices as long as it maps to the same value. + # Because tagged_union_choices may map values to other values, we need to walk the choices dict + # until we get to a "real" choice, and confirm that is equal to the one assigned. + existing_choice = self._tagged_union_choices[discriminator_value] + if existing_choice != choice: + raise TypeError( + f'Value {discriminator_value!r} for discriminator ' + f'{self.discriminator!r} mapped to multiple choices' + ) + else: + self._tagged_union_choices[discriminator_value] = choice diff --git a/env/Lib/site-packages/pydantic/_internal/_docs_extraction.py b/env/Lib/site-packages/pydantic/_internal/_docs_extraction.py new file mode 100644 index 0000000..685a6d0 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_docs_extraction.py @@ -0,0 +1,108 @@ +"""Utilities related to attribute docstring extraction.""" + +from __future__ import annotations + +import ast +import inspect +import textwrap +from typing import Any + + +class DocstringVisitor(ast.NodeVisitor): + def __init__(self) -> None: + super().__init__() + + self.target: str | None = None + self.attrs: dict[str, str] = {} + self.previous_node_type: type[ast.AST] | None = None + + def visit(self, node: ast.AST) -> Any: + node_result = super().visit(node) + self.previous_node_type = type(node) + return node_result + + def visit_AnnAssign(self, node: ast.AnnAssign) -> Any: + if isinstance(node.target, ast.Name): + self.target = node.target.id + + def visit_Expr(self, node: ast.Expr) -> Any: + if ( + isinstance(node.value, ast.Constant) + and isinstance(node.value.value, str) + and self.previous_node_type is ast.AnnAssign + ): + docstring = inspect.cleandoc(node.value.value) + if self.target: + self.attrs[self.target] = docstring + self.target = None + + +def _dedent_source_lines(source: list[str]) -> str: + # Required for nested class definitions, e.g. in a function block + dedent_source = textwrap.dedent(''.join(source)) + if dedent_source.startswith((' ', '\t')): + # We are in the case where there's a dedented (usually multiline) string + # at a lower indentation level than the class itself. We wrap our class + # in a function as a workaround. + dedent_source = f'def dedent_workaround():\n{dedent_source}' + return dedent_source + + +def _extract_source_from_frame(cls: type[Any]) -> list[str] | None: + frame = inspect.currentframe() + + while frame: + if inspect.getmodule(frame) is inspect.getmodule(cls): + lnum = frame.f_lineno + try: + lines, _ = inspect.findsource(frame) + except OSError: + # Source can't be retrieved (maybe because running in an interactive terminal), + # we don't want to error here. + pass + else: + block_lines = inspect.getblock(lines[lnum - 1 :]) + dedent_source = _dedent_source_lines(block_lines) + try: + block_tree = ast.parse(dedent_source) + except SyntaxError: + pass + else: + stmt = block_tree.body[0] + if isinstance(stmt, ast.FunctionDef) and stmt.name == 'dedent_workaround': + # `_dedent_source_lines` wrapped the class around the workaround function + stmt = stmt.body[0] + if isinstance(stmt, ast.ClassDef) and stmt.name == cls.__name__: + return block_lines + + frame = frame.f_back + + +def extract_docstrings_from_cls(cls: type[Any], use_inspect: bool = False) -> dict[str, str]: + """Map model attributes and their corresponding docstring. + + Args: + cls: The class of the Pydantic model to inspect. + use_inspect: Whether to skip usage of frames to find the object and use + the `inspect` module instead. + + Returns: + A mapping containing attribute names and their corresponding docstring. + """ + if use_inspect: + # Might not work as expected if two classes have the same name in the same source file. + try: + source, _ = inspect.getsourcelines(cls) + except OSError: + return {} + else: + source = _extract_source_from_frame(cls) + + if not source: + return {} + + dedent_source = _dedent_source_lines(source) + + visitor = DocstringVisitor() + visitor.visit(ast.parse(dedent_source)) + return visitor.attrs diff --git a/env/Lib/site-packages/pydantic/_internal/_fields.py b/env/Lib/site-packages/pydantic/_internal/_fields.py new file mode 100644 index 0000000..52cd08b --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_fields.py @@ -0,0 +1,361 @@ +"""Private logic related to fields (the `Field()` function and `FieldInfo` class), and arguments to `Annotated`.""" + +from __future__ import annotations as _annotations + +import dataclasses +import sys +import warnings +from copy import copy +from functools import lru_cache +from typing import TYPE_CHECKING, Any + +from pydantic_core import PydanticUndefined + +from pydantic.errors import PydanticUserError + +from . import _typing_extra +from ._config import ConfigWrapper +from ._docs_extraction import extract_docstrings_from_cls +from ._repr import Representation +from ._typing_extra import get_cls_type_hints_lenient, get_type_hints, is_classvar, is_finalvar + +if TYPE_CHECKING: + from annotated_types import BaseMetadata + + from ..fields import FieldInfo + from ..main import BaseModel + from ._dataclasses import StandardDataclass + from ._decorators import DecoratorInfos + + +def get_type_hints_infer_globalns( + obj: Any, + localns: dict[str, Any] | None = None, + include_extras: bool = False, +) -> dict[str, Any]: + """Gets type hints for an object by inferring the global namespace. + + It uses the `typing.get_type_hints`, The only thing that we do here is fetching + global namespace from `obj.__module__` if it is not `None`. + + Args: + obj: The object to get its type hints. + localns: The local namespaces. + include_extras: Whether to recursively include annotation metadata. + + Returns: + The object type hints. + """ + module_name = getattr(obj, '__module__', None) + globalns: dict[str, Any] | None = None + if module_name: + try: + globalns = sys.modules[module_name].__dict__ + except KeyError: + # happens occasionally, see https://github.com/pydantic/pydantic/issues/2363 + pass + return get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras) + + +class PydanticMetadata(Representation): + """Base class for annotation markers like `Strict`.""" + + __slots__ = () + + +def pydantic_general_metadata(**metadata: Any) -> BaseMetadata: + """Create a new `_PydanticGeneralMetadata` class with the given metadata. + + Args: + **metadata: The metadata to add. + + Returns: + The new `_PydanticGeneralMetadata` class. + """ + return _general_metadata_cls()(metadata) # type: ignore + + +@lru_cache(maxsize=None) +def _general_metadata_cls() -> type[BaseMetadata]: + """Do it this way to avoid importing `annotated_types` at import time.""" + from annotated_types import BaseMetadata + + class _PydanticGeneralMetadata(PydanticMetadata, BaseMetadata): + """Pydantic general metadata like `max_digits`.""" + + def __init__(self, metadata: Any): + self.__dict__ = metadata + + return _PydanticGeneralMetadata # type: ignore + + +def _update_fields_from_docstrings(cls: type[Any], fields: dict[str, FieldInfo], config_wrapper: ConfigWrapper) -> None: + if config_wrapper.use_attribute_docstrings: + fields_docs = extract_docstrings_from_cls(cls) + for ann_name, field_info in fields.items(): + if field_info.description is None and ann_name in fields_docs: + field_info.description = fields_docs[ann_name] + + +def collect_model_fields( # noqa: C901 + cls: type[BaseModel], + bases: tuple[type[Any], ...], + config_wrapper: ConfigWrapper, + types_namespace: dict[str, Any] | None, + *, + typevars_map: dict[Any, Any] | None = None, +) -> tuple[dict[str, FieldInfo], set[str]]: + """Collect the fields of a nascent pydantic model. + + Also collect the names of any ClassVars present in the type hints. + + The returned value is a tuple of two items: the fields dict, and the set of ClassVar names. + + Args: + cls: BaseModel or dataclass. + bases: Parents of the class, generally `cls.__bases__`. + config_wrapper: The config wrapper instance. + types_namespace: Optional extra namespace to look for types in. + typevars_map: A dictionary mapping type variables to their concrete types. + + Returns: + A tuple contains fields and class variables. + + Raises: + NameError: + - If there is a conflict between a field name and protected namespaces. + - If there is a field other than `root` in `RootModel`. + - If a field shadows an attribute in the parent model. + """ + from ..fields import FieldInfo + + type_hints = get_cls_type_hints_lenient(cls, types_namespace) + + # https://docs.python.org/3/howto/annotations.html#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older + # annotations is only used for finding fields in parent classes + annotations = cls.__dict__.get('__annotations__', {}) + fields: dict[str, FieldInfo] = {} + + class_vars: set[str] = set() + for ann_name, ann_type in type_hints.items(): + if ann_name == 'model_config': + # We never want to treat `model_config` as a field + # Note: we may need to change this logic if/when we introduce a `BareModel` class with no + # protected namespaces (where `model_config` might be allowed as a field name) + continue + for protected_namespace in config_wrapper.protected_namespaces: + if ann_name.startswith(protected_namespace): + for b in bases: + if hasattr(b, ann_name): + from ..main import BaseModel + + if not (issubclass(b, BaseModel) and ann_name in b.model_fields): + raise NameError( + f'Field "{ann_name}" conflicts with member {getattr(b, ann_name)}' + f' of protected namespace "{protected_namespace}".' + ) + else: + valid_namespaces = tuple( + x for x in config_wrapper.protected_namespaces if not ann_name.startswith(x) + ) + warnings.warn( + f'Field "{ann_name}" has conflict with protected namespace "{protected_namespace}".' + '\n\nYou may be able to resolve this warning by setting' + f" `model_config['protected_namespaces'] = {valid_namespaces}`.", + UserWarning, + ) + if is_classvar(ann_type): + class_vars.add(ann_name) + continue + if _is_finalvar_with_default_val(ann_type, getattr(cls, ann_name, PydanticUndefined)): + class_vars.add(ann_name) + continue + if not is_valid_field_name(ann_name): + continue + if cls.__pydantic_root_model__ and ann_name != 'root': + raise NameError( + f"Unexpected field with name {ann_name!r}; only 'root' is allowed as a field of a `RootModel`" + ) + + # when building a generic model with `MyModel[int]`, the generic_origin check makes sure we don't get + # "... shadows an attribute" warnings + generic_origin = getattr(cls, '__pydantic_generic_metadata__', {}).get('origin') + for base in bases: + dataclass_fields = { + field.name for field in (dataclasses.fields(base) if dataclasses.is_dataclass(base) else ()) + } + if hasattr(base, ann_name): + if base is generic_origin: + # Don't warn when "shadowing" of attributes in parametrized generics + continue + + if ann_name in dataclass_fields: + # Don't warn when inheriting stdlib dataclasses whose fields are "shadowed" by defaults being set + # on the class instance. + continue + + if ann_name not in annotations: + # Don't warn when a field exists in a parent class but has not been defined in the current class + continue + + warnings.warn( + f'Field name "{ann_name}" in "{cls.__qualname__}" shadows an attribute in parent ' + f'"{base.__qualname__}"', + UserWarning, + ) + + try: + default = getattr(cls, ann_name, PydanticUndefined) + if default is PydanticUndefined: + raise AttributeError + except AttributeError: + if ann_name in annotations: + field_info = FieldInfo.from_annotation(ann_type) + else: + # if field has no default value and is not in __annotations__ this means that it is + # defined in a base class and we can take it from there + model_fields_lookup: dict[str, FieldInfo] = {} + for x in cls.__bases__[::-1]: + model_fields_lookup.update(getattr(x, 'model_fields', {})) + if ann_name in model_fields_lookup: + # The field was present on one of the (possibly multiple) base classes + # copy the field to make sure typevar substitutions don't cause issues with the base classes + field_info = copy(model_fields_lookup[ann_name]) + else: + # The field was not found on any base classes; this seems to be caused by fields not getting + # generated thanks to models not being fully defined while initializing recursive models. + # Nothing stops us from just creating a new FieldInfo for this type hint, so we do this. + field_info = FieldInfo.from_annotation(ann_type) + else: + _warn_on_nested_alias_in_annotation(ann_type, ann_name) + field_info = FieldInfo.from_annotated_attribute(ann_type, default) + # attributes which are fields are removed from the class namespace: + # 1. To match the behaviour of annotation-only fields + # 2. To avoid false positives in the NameError check above + try: + delattr(cls, ann_name) + except AttributeError: + pass # indicates the attribute was on a parent class + + # Use cls.__dict__['__pydantic_decorators__'] instead of cls.__pydantic_decorators__ + # to make sure the decorators have already been built for this exact class + decorators: DecoratorInfos = cls.__dict__['__pydantic_decorators__'] + if ann_name in decorators.computed_fields: + raise ValueError("you can't override a field with a computed field") + fields[ann_name] = field_info + + if typevars_map: + for field in fields.values(): + field.apply_typevars_map(typevars_map, types_namespace) + + _update_fields_from_docstrings(cls, fields, config_wrapper) + + return fields, class_vars + + +def _warn_on_nested_alias_in_annotation(ann_type: type[Any], ann_name: str): + from ..fields import FieldInfo + + if hasattr(ann_type, '__args__'): + for anno_arg in ann_type.__args__: + if _typing_extra.is_annotated(anno_arg): + for anno_type_arg in _typing_extra.get_args(anno_arg): + if isinstance(anno_type_arg, FieldInfo) and anno_type_arg.alias is not None: + warnings.warn( + f'`alias` specification on field "{ann_name}" must be set on outermost annotation to take effect.', + UserWarning, + ) + break + + +def _is_finalvar_with_default_val(type_: type[Any], val: Any) -> bool: + from ..fields import FieldInfo + + if not is_finalvar(type_): + return False + elif val is PydanticUndefined: + return False + elif isinstance(val, FieldInfo) and (val.default is PydanticUndefined and val.default_factory is None): + return False + else: + return True + + +def collect_dataclass_fields( + cls: type[StandardDataclass], + types_namespace: dict[str, Any] | None, + *, + typevars_map: dict[Any, Any] | None = None, + config_wrapper: ConfigWrapper | None = None, +) -> dict[str, FieldInfo]: + """Collect the fields of a dataclass. + + Args: + cls: dataclass. + types_namespace: Optional extra namespace to look for types in. + typevars_map: A dictionary mapping type variables to their concrete types. + config_wrapper: The config wrapper instance. + + Returns: + The dataclass fields. + """ + from ..fields import FieldInfo + + fields: dict[str, FieldInfo] = {} + dataclass_fields: dict[str, dataclasses.Field] = cls.__dataclass_fields__ + cls_localns = dict(vars(cls)) # this matches get_cls_type_hints_lenient, but all tests pass with `= None` instead + + source_module = sys.modules.get(cls.__module__) + if source_module is not None: + types_namespace = {**source_module.__dict__, **(types_namespace or {})} + + for ann_name, dataclass_field in dataclass_fields.items(): + ann_type = _typing_extra.eval_type_lenient(dataclass_field.type, types_namespace, cls_localns) + if is_classvar(ann_type): + continue + + if ( + not dataclass_field.init + and dataclass_field.default == dataclasses.MISSING + and dataclass_field.default_factory == dataclasses.MISSING + ): + # TODO: We should probably do something with this so that validate_assignment behaves properly + # Issue: https://github.com/pydantic/pydantic/issues/5470 + continue + + if isinstance(dataclass_field.default, FieldInfo): + if dataclass_field.default.init_var: + if dataclass_field.default.init is False: + raise PydanticUserError( + f'Dataclass field {ann_name} has init=False and init_var=True, but these are mutually exclusive.', + code='clashing-init-and-init-var', + ) + + # TODO: same note as above re validate_assignment + continue + field_info = FieldInfo.from_annotated_attribute(ann_type, dataclass_field.default) + else: + field_info = FieldInfo.from_annotated_attribute(ann_type, dataclass_field) + + fields[ann_name] = field_info + + if field_info.default is not PydanticUndefined and isinstance(getattr(cls, ann_name, field_info), FieldInfo): + # We need this to fix the default when the "default" from __dataclass_fields__ is a pydantic.FieldInfo + setattr(cls, ann_name, field_info.default) + + if typevars_map: + for field in fields.values(): + field.apply_typevars_map(typevars_map, types_namespace) + + if config_wrapper is not None: + _update_fields_from_docstrings(cls, fields, config_wrapper) + + return fields + + +def is_valid_field_name(name: str) -> bool: + return not name.startswith('_') + + +def is_valid_privateattr_name(name: str) -> bool: + return name.startswith('_') and not name.startswith('__') diff --git a/env/Lib/site-packages/pydantic/_internal/_forward_ref.py b/env/Lib/site-packages/pydantic/_internal/_forward_ref.py new file mode 100644 index 0000000..231f81d --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_forward_ref.py @@ -0,0 +1,23 @@ +from __future__ import annotations as _annotations + +from dataclasses import dataclass +from typing import Union + + +@dataclass +class PydanticRecursiveRef: + type_ref: str + + __name__ = 'PydanticRecursiveRef' + __hash__ = object.__hash__ + + def __call__(self) -> None: + """Defining __call__ is necessary for the `typing` module to let you use an instance of + this class as the result of resolving a standard ForwardRef. + """ + + def __or__(self, other): + return Union[self, other] # type: ignore + + def __ror__(self, other): + return Union[other, self] # type: ignore diff --git a/env/Lib/site-packages/pydantic/_internal/_generate_schema.py b/env/Lib/site-packages/pydantic/_internal/_generate_schema.py new file mode 100644 index 0000000..edd8e72 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_generate_schema.py @@ -0,0 +1,2376 @@ +"""Convert python types to pydantic-core schema.""" + +from __future__ import annotations as _annotations + +import collections.abc +import dataclasses +import inspect +import re +import sys +import typing +import warnings +from contextlib import ExitStack, contextmanager +from copy import copy, deepcopy +from enum import Enum +from functools import partial +from inspect import Parameter, _ParameterKind, signature +from itertools import chain +from operator import attrgetter +from types import FunctionType, LambdaType, MethodType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Final, + ForwardRef, + Iterable, + Iterator, + Mapping, + Type, + TypeVar, + Union, + cast, + overload, +) +from warnings import warn + +from pydantic_core import CoreSchema, PydanticUndefined, core_schema, to_jsonable_python +from typing_extensions import Annotated, Literal, TypeAliasType, TypedDict, get_args, get_origin, is_typeddict + +from ..aliases import AliasGenerator +from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler +from ..config import ConfigDict, JsonDict, JsonEncoder +from ..errors import PydanticSchemaGenerationError, PydanticUndefinedAnnotation, PydanticUserError +from ..json_schema import JsonSchemaValue +from ..version import version_short +from ..warnings import PydanticDeprecatedSince20 +from . import _core_utils, _decorators, _discriminated_union, _known_annotated_metadata, _typing_extra +from ._config import ConfigWrapper, ConfigWrapperStack +from ._core_metadata import CoreMetadataHandler, build_metadata_dict +from ._core_utils import ( + CoreSchemaOrField, + collect_invalid_schemas, + define_expected_missing_refs, + get_ref, + get_type_ref, + is_function_with_inner_schema, + is_list_like_schema_with_items_schema, + simplify_schema_references, + validate_core_schema, +) +from ._decorators import ( + Decorator, + DecoratorInfos, + FieldSerializerDecoratorInfo, + FieldValidatorDecoratorInfo, + ModelSerializerDecoratorInfo, + ModelValidatorDecoratorInfo, + RootValidatorDecoratorInfo, + ValidatorDecoratorInfo, + get_attribute_from_bases, + inspect_field_serializer, + inspect_model_serializer, + inspect_validator, +) +from ._docs_extraction import extract_docstrings_from_cls +from ._fields import collect_dataclass_fields, get_type_hints_infer_globalns +from ._forward_ref import PydanticRecursiveRef +from ._generics import get_standard_typevars_map, has_instance_in_type, recursively_defined_type_refs, replace_types +from ._mock_val_ser import MockCoreSchema +from ._schema_generation_shared import CallbackGetCoreSchemaHandler +from ._typing_extra import is_finalvar, is_self_type +from ._utils import lenient_issubclass + +if TYPE_CHECKING: + from ..fields import ComputedFieldInfo, FieldInfo + from ..main import BaseModel + from ..types import Discriminator + from ..validators import FieldValidatorModes + from ._dataclasses import StandardDataclass + from ._schema_generation_shared import GetJsonSchemaFunction + +_SUPPORTS_TYPEDDICT = sys.version_info >= (3, 12) +_AnnotatedType = type(Annotated[int, 123]) + +FieldDecoratorInfo = Union[ValidatorDecoratorInfo, FieldValidatorDecoratorInfo, FieldSerializerDecoratorInfo] +FieldDecoratorInfoType = TypeVar('FieldDecoratorInfoType', bound=FieldDecoratorInfo) +AnyFieldDecorator = Union[ + Decorator[ValidatorDecoratorInfo], + Decorator[FieldValidatorDecoratorInfo], + Decorator[FieldSerializerDecoratorInfo], +] + +ModifyCoreSchemaWrapHandler = GetCoreSchemaHandler +GetCoreSchemaFunction = Callable[[Any, ModifyCoreSchemaWrapHandler], core_schema.CoreSchema] + +TUPLE_TYPES: list[type] = [tuple, typing.Tuple] +LIST_TYPES: list[type] = [list, typing.List, collections.abc.MutableSequence] +SET_TYPES: list[type] = [set, typing.Set, collections.abc.MutableSet] +FROZEN_SET_TYPES: list[type] = [frozenset, typing.FrozenSet, collections.abc.Set] +DICT_TYPES: list[type] = [dict, typing.Dict, collections.abc.MutableMapping, collections.abc.Mapping] + + +def check_validator_fields_against_field_name( + info: FieldDecoratorInfo, + field: str, +) -> bool: + """Check if field name is in validator fields. + + Args: + info: The field info. + field: The field name to check. + + Returns: + `True` if field name is in validator fields, `False` otherwise. + """ + if '*' in info.fields: + return True + for v_field_name in info.fields: + if v_field_name == field: + return True + return False + + +def check_decorator_fields_exist(decorators: Iterable[AnyFieldDecorator], fields: Iterable[str]) -> None: + """Check if the defined fields in decorators exist in `fields` param. + + It ignores the check for a decorator if the decorator has `*` as field or `check_fields=False`. + + Args: + decorators: An iterable of decorators. + fields: An iterable of fields name. + + Raises: + PydanticUserError: If one of the field names does not exist in `fields` param. + """ + fields = set(fields) + for dec in decorators: + if '*' in dec.info.fields: + continue + if dec.info.check_fields is False: + continue + for field in dec.info.fields: + if field not in fields: + raise PydanticUserError( + f'Decorators defined with incorrect fields: {dec.cls_ref}.{dec.cls_var_name}' + " (use check_fields=False if you're inheriting from the model and intended this)", + code='decorator-missing-field', + ) + + +def filter_field_decorator_info_by_field( + validator_functions: Iterable[Decorator[FieldDecoratorInfoType]], field: str +) -> list[Decorator[FieldDecoratorInfoType]]: + return [dec for dec in validator_functions if check_validator_fields_against_field_name(dec.info, field)] + + +def apply_each_item_validators( + schema: core_schema.CoreSchema, + each_item_validators: list[Decorator[ValidatorDecoratorInfo]], + field_name: str | None, +) -> core_schema.CoreSchema: + # This V1 compatibility shim should eventually be removed + + # push down any `each_item=True` validators + # note that this won't work for any Annotated types that get wrapped by a function validator + # but that's okay because that didn't exist in V1 + if schema['type'] == 'nullable': + schema['schema'] = apply_each_item_validators(schema['schema'], each_item_validators, field_name) + return schema + elif schema['type'] == 'tuple': + if (variadic_item_index := schema.get('variadic_item_index')) is not None: + schema['items_schema'][variadic_item_index] = apply_validators( + schema['items_schema'][variadic_item_index], each_item_validators, field_name + ) + elif is_list_like_schema_with_items_schema(schema): + inner_schema = schema.get('items_schema', None) + if inner_schema is None: + inner_schema = core_schema.any_schema() + schema['items_schema'] = apply_validators(inner_schema, each_item_validators, field_name) + elif schema['type'] == 'dict': + # push down any `each_item=True` validators onto dict _values_ + # this is super arbitrary but it's the V1 behavior + inner_schema = schema.get('values_schema', None) + if inner_schema is None: + inner_schema = core_schema.any_schema() + schema['values_schema'] = apply_validators(inner_schema, each_item_validators, field_name) + elif each_item_validators: + raise TypeError( + f"`@validator(..., each_item=True)` cannot be applied to fields with a schema of {schema['type']}" + ) + return schema + + +def modify_model_json_schema( + schema_or_field: CoreSchemaOrField, + handler: GetJsonSchemaHandler, + *, + cls: Any, + title: str | None = None, +) -> JsonSchemaValue: + """Add title and description for model-like classes' JSON schema. + + Args: + schema_or_field: The schema data to generate a JSON schema from. + handler: The `GetCoreSchemaHandler` instance. + cls: The model-like class. + title: The title to set for the model's schema, defaults to the model's name + + Returns: + JsonSchemaValue: The updated JSON schema. + """ + from ..dataclasses import is_pydantic_dataclass + from ..main import BaseModel + from ..root_model import RootModel + from ._dataclasses import is_builtin_dataclass + + json_schema = handler(schema_or_field) + original_schema = handler.resolve_ref_schema(json_schema) + # Preserve the fact that definitions schemas should never have sibling keys: + if '$ref' in original_schema: + ref = original_schema['$ref'] + original_schema.clear() + original_schema['allOf'] = [{'$ref': ref}] + if title is not None: + original_schema['title'] = title + elif 'title' not in original_schema: + original_schema['title'] = cls.__name__ + # BaseModel + Dataclass; don't use cls.__doc__ as it will contain the verbose class signature by default + docstring = None if cls is BaseModel or is_builtin_dataclass(cls) or is_pydantic_dataclass(cls) else cls.__doc__ + if docstring and 'description' not in original_schema: + original_schema['description'] = inspect.cleandoc(docstring) + elif issubclass(cls, RootModel) and cls.model_fields['root'].description: + original_schema['description'] = cls.model_fields['root'].description + return json_schema + + +JsonEncoders = Dict[Type[Any], JsonEncoder] + + +def _add_custom_serialization_from_json_encoders( + json_encoders: JsonEncoders | None, tp: Any, schema: CoreSchema +) -> CoreSchema: + """Iterate over the json_encoders and add the first matching encoder to the schema. + + Args: + json_encoders: A dictionary of types and their encoder functions. + tp: The type to check for a matching encoder. + schema: The schema to add the encoder to. + """ + if not json_encoders: + return schema + if 'serialization' in schema: + return schema + # Check the class type and its superclasses for a matching encoder + # Decimal.__class__.__mro__ (and probably other cases) doesn't include Decimal itself + # if the type is a GenericAlias (e.g. from list[int]) we need to use __class__ instead of .__mro__ + for base in (tp, *getattr(tp, '__mro__', tp.__class__.__mro__)[:-1]): + encoder = json_encoders.get(base) + if encoder is None: + continue + + warnings.warn( + f'`json_encoders` is deprecated. See https://docs.pydantic.dev/{version_short()}/concepts/serialization/#custom-serializers for alternatives', + PydanticDeprecatedSince20, + ) + + # TODO: in theory we should check that the schema accepts a serialization key + schema['serialization'] = core_schema.plain_serializer_function_ser_schema(encoder, when_used='json') + return schema + + return schema + + +TypesNamespace = Union[Dict[str, Any], None] + + +class TypesNamespaceStack: + """A stack of types namespaces.""" + + def __init__(self, types_namespace: TypesNamespace): + self._types_namespace_stack: list[TypesNamespace] = [types_namespace] + + @property + def tail(self) -> TypesNamespace: + return self._types_namespace_stack[-1] + + @contextmanager + def push(self, for_type: type[Any]): + types_namespace = {**_typing_extra.get_cls_types_namespace(for_type), **(self.tail or {})} + self._types_namespace_stack.append(types_namespace) + try: + yield + finally: + self._types_namespace_stack.pop() + + +def _get_first_non_null(a: Any, b: Any) -> Any: + """Return the first argument if it is not None, otherwise return the second argument. + + Use case: serialization_alias (argument a) and alias (argument b) are both defined, and serialization_alias is ''. + This function will return serialization_alias, which is the first argument, even though it is an empty string. + """ + return a if a is not None else b + + +class GenerateSchema: + """Generate core schema for a Pydantic model, dataclass and types like `str`, `datetime`, ... .""" + + __slots__ = ( + '_config_wrapper_stack', + '_types_namespace_stack', + '_typevars_map', + 'field_name_stack', + 'model_type_stack', + 'defs', + ) + + def __init__( + self, + config_wrapper: ConfigWrapper, + types_namespace: dict[str, Any] | None, + typevars_map: dict[Any, Any] | None = None, + ) -> None: + # we need a stack for recursing into child models + self._config_wrapper_stack = ConfigWrapperStack(config_wrapper) + self._types_namespace_stack = TypesNamespaceStack(types_namespace) + self._typevars_map = typevars_map + self.field_name_stack = _FieldNameStack() + self.model_type_stack = _ModelTypeStack() + self.defs = _Definitions() + + @classmethod + def __from_parent( + cls, + config_wrapper_stack: ConfigWrapperStack, + types_namespace_stack: TypesNamespaceStack, + model_type_stack: _ModelTypeStack, + typevars_map: dict[Any, Any] | None, + defs: _Definitions, + ) -> GenerateSchema: + obj = cls.__new__(cls) + obj._config_wrapper_stack = config_wrapper_stack + obj._types_namespace_stack = types_namespace_stack + obj.model_type_stack = model_type_stack + obj._typevars_map = typevars_map + obj.field_name_stack = _FieldNameStack() + obj.defs = defs + return obj + + @property + def _config_wrapper(self) -> ConfigWrapper: + return self._config_wrapper_stack.tail + + @property + def _types_namespace(self) -> dict[str, Any] | None: + return self._types_namespace_stack.tail + + @property + def _current_generate_schema(self) -> GenerateSchema: + cls = self._config_wrapper.schema_generator or GenerateSchema + return cls.__from_parent( + self._config_wrapper_stack, + self._types_namespace_stack, + self.model_type_stack, + self._typevars_map, + self.defs, + ) + + @property + def _arbitrary_types(self) -> bool: + return self._config_wrapper.arbitrary_types_allowed + + def str_schema(self) -> CoreSchema: + """Generate a CoreSchema for `str`""" + return core_schema.str_schema() + + # the following methods can be overridden but should be considered + # unstable / private APIs + def _list_schema(self, tp: Any, items_type: Any) -> CoreSchema: + return core_schema.list_schema(self.generate_schema(items_type)) + + def _dict_schema(self, tp: Any, keys_type: Any, values_type: Any) -> CoreSchema: + return core_schema.dict_schema(self.generate_schema(keys_type), self.generate_schema(values_type)) + + def _set_schema(self, tp: Any, items_type: Any) -> CoreSchema: + return core_schema.set_schema(self.generate_schema(items_type)) + + def _frozenset_schema(self, tp: Any, items_type: Any) -> CoreSchema: + return core_schema.frozenset_schema(self.generate_schema(items_type)) + + def _arbitrary_type_schema(self, tp: Any) -> CoreSchema: + if not isinstance(tp, type): + warn( + f'{tp!r} is not a Python type (it may be an instance of an object),' + ' Pydantic will allow any object with no validation since we cannot even' + ' enforce that the input is an instance of the given type.' + ' To get rid of this error wrap the type with `pydantic.SkipValidation`.', + UserWarning, + ) + return core_schema.any_schema() + return core_schema.is_instance_schema(tp) + + def _unknown_type_schema(self, obj: Any) -> CoreSchema: + raise PydanticSchemaGenerationError( + f'Unable to generate pydantic-core schema for {obj!r}. ' + 'Set `arbitrary_types_allowed=True` in the model_config to ignore this error' + ' or implement `__get_pydantic_core_schema__` on your type to fully support it.' + '\n\nIf you got this error by calling handler() within' + ' `__get_pydantic_core_schema__` then you likely need to call' + ' `handler.generate_schema()` since we do not call' + ' `__get_pydantic_core_schema__` on `` otherwise to avoid infinite recursion.' + ) + + def _apply_discriminator_to_union( + self, schema: CoreSchema, discriminator: str | Discriminator | None + ) -> CoreSchema: + if discriminator is None: + return schema + try: + return _discriminated_union.apply_discriminator( + schema, + discriminator, + ) + except _discriminated_union.MissingDefinitionForUnionRef: + # defer until defs are resolved + _discriminated_union.set_discriminator_in_metadata( + schema, + discriminator, + ) + return schema + + class CollectedInvalid(Exception): + pass + + def clean_schema(self, schema: CoreSchema) -> CoreSchema: + schema = self.collect_definitions(schema) + schema = simplify_schema_references(schema) + if collect_invalid_schemas(schema): + raise self.CollectedInvalid() + schema = _discriminated_union.apply_discriminators(schema) + schema = validate_core_schema(schema) + return schema + + def collect_definitions(self, schema: CoreSchema) -> CoreSchema: + ref = cast('str | None', schema.get('ref', None)) + if ref: + self.defs.definitions[ref] = schema + if 'ref' in schema: + schema = core_schema.definition_reference_schema(schema['ref']) + return core_schema.definitions_schema( + schema, + list(self.defs.definitions.values()), + ) + + def _add_js_function(self, metadata_schema: CoreSchema, js_function: Callable[..., Any]) -> None: + metadata = CoreMetadataHandler(metadata_schema).metadata + pydantic_js_functions = metadata.setdefault('pydantic_js_functions', []) + # because of how we generate core schemas for nested generic models + # we can end up adding `BaseModel.__get_pydantic_json_schema__` multiple times + # this check may fail to catch duplicates if the function is a `functools.partial` + # or something like that + # but if it does it'll fail by inserting the duplicate + if js_function not in pydantic_js_functions: + pydantic_js_functions.append(js_function) + + def generate_schema( + self, + obj: Any, + from_dunder_get_core_schema: bool = True, + ) -> core_schema.CoreSchema: + """Generate core schema. + + Args: + obj: The object to generate core schema for. + from_dunder_get_core_schema: Whether to generate schema from either the + `__get_pydantic_core_schema__` function or `__pydantic_core_schema__` property. + + Returns: + The generated core schema. + + Raises: + PydanticUndefinedAnnotation: + If it is not possible to evaluate forward reference. + PydanticSchemaGenerationError: + If it is not possible to generate pydantic-core schema. + TypeError: + - If `alias_generator` returns a disallowed type (must be str, AliasPath or AliasChoices). + - If V1 style validator with `each_item=True` applied on a wrong field. + PydanticUserError: + - If `typing.TypedDict` is used instead of `typing_extensions.TypedDict` on Python < 3.12. + - If `__modify_schema__` method is used instead of `__get_pydantic_json_schema__`. + """ + schema: CoreSchema | None = None + + if from_dunder_get_core_schema: + from_property = self._generate_schema_from_property(obj, obj) + if from_property is not None: + schema = from_property + + if schema is None: + schema = self._generate_schema_inner(obj) + + metadata_js_function = _extract_get_pydantic_json_schema(obj, schema) + if metadata_js_function is not None: + metadata_schema = resolve_original_schema(schema, self.defs.definitions) + if metadata_schema: + self._add_js_function(metadata_schema, metadata_js_function) + + schema = _add_custom_serialization_from_json_encoders(self._config_wrapper.json_encoders, obj, schema) + + return schema + + def _model_schema(self, cls: type[BaseModel]) -> core_schema.CoreSchema: + """Generate schema for a Pydantic model.""" + with self.defs.get_schema_or_ref(cls) as (model_ref, maybe_schema): + if maybe_schema is not None: + return maybe_schema + + fields = cls.model_fields + decorators = cls.__pydantic_decorators__ + computed_fields = decorators.computed_fields + check_decorator_fields_exist( + chain( + decorators.field_validators.values(), + decorators.field_serializers.values(), + decorators.validators.values(), + ), + {*fields.keys(), *computed_fields.keys()}, + ) + config_wrapper = ConfigWrapper(cls.model_config, check=False) + core_config = config_wrapper.core_config(cls) + title = self._get_model_title_from_config(cls, config_wrapper) + metadata = build_metadata_dict(js_functions=[partial(modify_model_json_schema, cls=cls, title=title)]) + + model_validators = decorators.model_validators.values() + + extras_schema = None + if core_config.get('extra_fields_behavior') == 'allow': + assert cls.__mro__[0] is cls + assert cls.__mro__[-1] is object + for candidate_cls in cls.__mro__[:-1]: + extras_annotation = getattr(candidate_cls, '__annotations__', {}).get('__pydantic_extra__', None) + if extras_annotation is not None: + if isinstance(extras_annotation, str): + extras_annotation = _typing_extra.eval_type_backport( + _typing_extra._make_forward_ref(extras_annotation, is_argument=False, is_class=True), + self._types_namespace, + ) + tp = get_origin(extras_annotation) + if tp not in (Dict, dict): + raise PydanticSchemaGenerationError( + 'The type annotation for `__pydantic_extra__` must be `Dict[str, ...]`' + ) + extra_items_type = self._get_args_resolving_forward_refs( + extras_annotation, + required=True, + )[1] + if extra_items_type is not Any: + extras_schema = self.generate_schema(extra_items_type) + break + + with self._config_wrapper_stack.push(config_wrapper), self._types_namespace_stack.push(cls): + self = self._current_generate_schema + if cls.__pydantic_root_model__: + root_field = self._common_field_schema('root', fields['root'], decorators) + inner_schema = root_field['schema'] + inner_schema = apply_model_validators(inner_schema, model_validators, 'inner') + model_schema = core_schema.model_schema( + cls, + inner_schema, + custom_init=getattr(cls, '__pydantic_custom_init__', None), + root_model=True, + post_init=getattr(cls, '__pydantic_post_init__', None), + config=core_config, + ref=model_ref, + metadata=metadata, + ) + else: + fields_schema: core_schema.CoreSchema = core_schema.model_fields_schema( + {k: self._generate_md_field_schema(k, v, decorators) for k, v in fields.items()}, + computed_fields=[ + self._computed_field_schema(d, decorators.field_serializers) + for d in computed_fields.values() + ], + extras_schema=extras_schema, + model_name=cls.__name__, + ) + inner_schema = apply_validators(fields_schema, decorators.root_validators.values(), None) + new_inner_schema = define_expected_missing_refs(inner_schema, recursively_defined_type_refs()) + if new_inner_schema is not None: + inner_schema = new_inner_schema + inner_schema = apply_model_validators(inner_schema, model_validators, 'inner') + + model_schema = core_schema.model_schema( + cls, + inner_schema, + custom_init=getattr(cls, '__pydantic_custom_init__', None), + root_model=False, + post_init=getattr(cls, '__pydantic_post_init__', None), + config=core_config, + ref=model_ref, + metadata=metadata, + ) + + schema = self._apply_model_serializers(model_schema, decorators.model_serializers.values()) + schema = apply_model_validators(schema, model_validators, 'outer') + self.defs.definitions[model_ref] = schema + return core_schema.definition_reference_schema(model_ref) + + @staticmethod + def _get_model_title_from_config( + model: type[BaseModel | StandardDataclass], config_wrapper: ConfigWrapper | None = None + ) -> str | None: + """Get the title of a model if `model_title_generator` or `title` are set in the config, else return None""" + if config_wrapper is None: + return None + + if config_wrapper.title: + return config_wrapper.title + + model_title_generator = config_wrapper.model_title_generator + if model_title_generator: + title = model_title_generator(model) + if not isinstance(title, str): + raise TypeError(f'model_title_generator {model_title_generator} must return str, not {title.__class__}') + return title + + return None + + def _unpack_refs_defs(self, schema: CoreSchema) -> CoreSchema: + """Unpack all 'definitions' schemas into `GenerateSchema.defs.definitions` + and return the inner schema. + """ + + def get_ref(s: CoreSchema) -> str: + return s['ref'] # type: ignore + + if schema['type'] == 'definitions': + self.defs.definitions.update({get_ref(s): s for s in schema['definitions']}) + schema = schema['schema'] + return schema + + def _generate_schema_from_property(self, obj: Any, source: Any) -> core_schema.CoreSchema | None: + """Try to generate schema from either the `__get_pydantic_core_schema__` function or + `__pydantic_core_schema__` property. + + Note: `__get_pydantic_core_schema__` takes priority so it can + decide whether to use a `__pydantic_core_schema__` attribute, or generate a fresh schema. + """ + # avoid calling `__get_pydantic_core_schema__` if we've already visited this object + if is_self_type(obj): + obj = self.model_type_stack.get() + with self.defs.get_schema_or_ref(obj) as (_, maybe_schema): + if maybe_schema is not None: + return maybe_schema + if obj is source: + ref_mode = 'unpack' + else: + ref_mode = 'to-def' + + schema: CoreSchema + + if (get_schema := getattr(obj, '__get_pydantic_core_schema__', None)) is not None: + if len(inspect.signature(get_schema).parameters) == 1: + # (source) -> CoreSchema + schema = get_schema(source) + else: + schema = get_schema( + source, CallbackGetCoreSchemaHandler(self._generate_schema_inner, self, ref_mode=ref_mode) + ) + # fmt: off + elif ( + (existing_schema := getattr(obj, '__pydantic_core_schema__', None)) is not None + and not isinstance(existing_schema, MockCoreSchema) + and existing_schema.get('cls', None) == obj + ): + schema = existing_schema + # fmt: on + elif (validators := getattr(obj, '__get_validators__', None)) is not None: + warn( + '`__get_validators__` is deprecated and will be removed, use `__get_pydantic_core_schema__` instead.', + PydanticDeprecatedSince20, + ) + schema = core_schema.chain_schema([core_schema.with_info_plain_validator_function(v) for v in validators()]) + else: + # we have no existing schema information on the property, exit early so that we can go generate a schema + return None + + schema = self._unpack_refs_defs(schema) + + if is_function_with_inner_schema(schema): + ref = schema['schema'].pop('ref', None) # pyright: ignore[reportCallIssue, reportArgumentType] + if ref: + schema['ref'] = ref + else: + ref = get_ref(schema) + + if ref: + self.defs.definitions[ref] = schema + return core_schema.definition_reference_schema(ref) + + return schema + + def _resolve_forward_ref(self, obj: Any) -> Any: + # we assume that types_namespace has the target of forward references in its scope, + # but this could fail, for example, if calling Validator on an imported type which contains + # forward references to other types only defined in the module from which it was imported + # `Validator(SomeImportedTypeAliasWithAForwardReference)` + # or the equivalent for BaseModel + # class Model(BaseModel): + # x: SomeImportedTypeAliasWithAForwardReference + try: + obj = _typing_extra.eval_type_backport(obj, globalns=self._types_namespace) + except NameError as e: + raise PydanticUndefinedAnnotation.from_name_error(e) from e + + # if obj is still a ForwardRef, it means we can't evaluate it, raise PydanticUndefinedAnnotation + if isinstance(obj, ForwardRef): + raise PydanticUndefinedAnnotation(obj.__forward_arg__, f'Unable to evaluate forward reference {obj}') + + if self._typevars_map: + obj = replace_types(obj, self._typevars_map) + + return obj + + @overload + def _get_args_resolving_forward_refs(self, obj: Any, required: Literal[True]) -> tuple[Any, ...]: ... + + @overload + def _get_args_resolving_forward_refs(self, obj: Any) -> tuple[Any, ...] | None: ... + + def _get_args_resolving_forward_refs(self, obj: Any, required: bool = False) -> tuple[Any, ...] | None: + args = get_args(obj) + if args: + args = tuple([self._resolve_forward_ref(a) if isinstance(a, ForwardRef) else a for a in args]) + elif required: # pragma: no cover + raise TypeError(f'Expected {obj} to have generic parameters but it had none') + return args + + def _get_first_arg_or_any(self, obj: Any) -> Any: + args = self._get_args_resolving_forward_refs(obj) + if not args: + return Any + return args[0] + + def _get_first_two_args_or_any(self, obj: Any) -> tuple[Any, Any]: + args = self._get_args_resolving_forward_refs(obj) + if not args: + return (Any, Any) + if len(args) < 2: + origin = get_origin(obj) + raise TypeError(f'Expected two type arguments for {origin}, got 1') + return args[0], args[1] + + def _generate_schema_inner(self, obj: Any) -> core_schema.CoreSchema: + if isinstance(obj, _AnnotatedType): + return self._annotated_schema(obj) + + if isinstance(obj, dict): + # we assume this is already a valid schema + return obj # type: ignore[return-value] + + if isinstance(obj, str): + obj = ForwardRef(obj) + + if isinstance(obj, ForwardRef): + return self.generate_schema(self._resolve_forward_ref(obj)) + + from ..main import BaseModel + + if lenient_issubclass(obj, BaseModel): + with self.model_type_stack.push(obj): + return self._model_schema(obj) + + if isinstance(obj, PydanticRecursiveRef): + return core_schema.definition_reference_schema(schema_ref=obj.type_ref) + + return self.match_type(obj) + + def match_type(self, obj: Any) -> core_schema.CoreSchema: # noqa: C901 + """Main mapping of types to schemas. + + The general structure is a series of if statements starting with the simple cases + (non-generic primitive types) and then handling generics and other more complex cases. + + Each case either generates a schema directly, calls into a public user-overridable method + (like `GenerateSchema.tuple_variable_schema`) or calls into a private method that handles some + boilerplate before calling into the user-facing method (e.g. `GenerateSchema._tuple_schema`). + + The idea is that we'll evolve this into adding more and more user facing methods over time + as they get requested and we figure out what the right API for them is. + """ + if obj is str: + return self.str_schema() + elif obj is bytes: + return core_schema.bytes_schema() + elif obj is int: + return core_schema.int_schema() + elif obj is float: + return core_schema.float_schema() + elif obj is bool: + return core_schema.bool_schema() + elif obj is Any or obj is object: + return core_schema.any_schema() + elif obj is None or obj is _typing_extra.NoneType: + return core_schema.none_schema() + elif obj in TUPLE_TYPES: + return self._tuple_schema(obj) + elif obj in LIST_TYPES: + return self._list_schema(obj, self._get_first_arg_or_any(obj)) + elif obj in SET_TYPES: + return self._set_schema(obj, self._get_first_arg_or_any(obj)) + elif obj in FROZEN_SET_TYPES: + return self._frozenset_schema(obj, self._get_first_arg_or_any(obj)) + elif obj in DICT_TYPES: + return self._dict_schema(obj, *self._get_first_two_args_or_any(obj)) + elif isinstance(obj, TypeAliasType): + return self._type_alias_type_schema(obj) + elif obj is type: + return self._type_schema() + elif _typing_extra.is_callable_type(obj): + return core_schema.callable_schema() + elif _typing_extra.is_literal_type(obj): + return self._literal_schema(obj) + elif is_typeddict(obj): + return self._typed_dict_schema(obj, None) + elif _typing_extra.is_namedtuple(obj): + return self._namedtuple_schema(obj, None) + elif _typing_extra.is_new_type(obj): + # NewType, can't use isinstance because it fails <3.10 + return self.generate_schema(obj.__supertype__) + elif obj == re.Pattern: + return self._pattern_schema(obj) + elif obj is collections.abc.Hashable or obj is typing.Hashable: + return self._hashable_schema() + elif isinstance(obj, typing.TypeVar): + return self._unsubstituted_typevar_schema(obj) + elif is_finalvar(obj): + if obj is Final: + return core_schema.any_schema() + return self.generate_schema( + self._get_first_arg_or_any(obj), + ) + elif isinstance(obj, (FunctionType, LambdaType, MethodType, partial)): + return self._callable_schema(obj) + elif inspect.isclass(obj) and issubclass(obj, Enum): + from ._std_types_schema import get_enum_core_schema + + return get_enum_core_schema(obj, self._config_wrapper.config_dict) + + if _typing_extra.is_dataclass(obj): + return self._dataclass_schema(obj, None) + res = self._get_prepare_pydantic_annotations_for_known_type(obj, ()) + if res is not None: + source_type, annotations = res + return self._apply_annotations(source_type, annotations) + + origin = get_origin(obj) + if origin is not None: + return self._match_generic_type(obj, origin) + + if self._arbitrary_types: + return self._arbitrary_type_schema(obj) + return self._unknown_type_schema(obj) + + def _match_generic_type(self, obj: Any, origin: Any) -> CoreSchema: # noqa: C901 + if isinstance(origin, TypeAliasType): + return self._type_alias_type_schema(obj) + + # Need to handle generic dataclasses before looking for the schema properties because attribute accesses + # on _GenericAlias delegate to the origin type, so lose the information about the concrete parametrization + # As a result, currently, there is no way to cache the schema for generic dataclasses. This may be possible + # to resolve by modifying the value returned by `Generic.__class_getitem__`, but that is a dangerous game. + if _typing_extra.is_dataclass(origin): + return self._dataclass_schema(obj, origin) + if _typing_extra.is_namedtuple(origin): + return self._namedtuple_schema(obj, origin) + + from_property = self._generate_schema_from_property(origin, obj) + if from_property is not None: + return from_property + + if _typing_extra.origin_is_union(origin): + return self._union_schema(obj) + elif origin in TUPLE_TYPES: + return self._tuple_schema(obj) + elif origin in LIST_TYPES: + return self._list_schema(obj, self._get_first_arg_or_any(obj)) + elif origin in SET_TYPES: + return self._set_schema(obj, self._get_first_arg_or_any(obj)) + elif origin in FROZEN_SET_TYPES: + return self._frozenset_schema(obj, self._get_first_arg_or_any(obj)) + elif origin in DICT_TYPES: + return self._dict_schema(obj, *self._get_first_two_args_or_any(obj)) + elif is_typeddict(origin): + return self._typed_dict_schema(obj, origin) + elif origin in (typing.Type, type): + return self._subclass_schema(obj) + elif origin in {typing.Sequence, collections.abc.Sequence}: + return self._sequence_schema(obj) + elif origin in {typing.Iterable, collections.abc.Iterable, typing.Generator, collections.abc.Generator}: + return self._iterable_schema(obj) + elif origin in (re.Pattern, typing.Pattern): + return self._pattern_schema(obj) + + if self._arbitrary_types: + return self._arbitrary_type_schema(origin) + return self._unknown_type_schema(obj) + + def _generate_td_field_schema( + self, + name: str, + field_info: FieldInfo, + decorators: DecoratorInfos, + *, + required: bool = True, + ) -> core_schema.TypedDictField: + """Prepare a TypedDictField to represent a model or typeddict field.""" + common_field = self._common_field_schema(name, field_info, decorators) + return core_schema.typed_dict_field( + common_field['schema'], + required=False if not field_info.is_required() else required, + serialization_exclude=common_field['serialization_exclude'], + validation_alias=common_field['validation_alias'], + serialization_alias=common_field['serialization_alias'], + metadata=common_field['metadata'], + ) + + def _generate_md_field_schema( + self, + name: str, + field_info: FieldInfo, + decorators: DecoratorInfos, + ) -> core_schema.ModelField: + """Prepare a ModelField to represent a model field.""" + common_field = self._common_field_schema(name, field_info, decorators) + return core_schema.model_field( + common_field['schema'], + serialization_exclude=common_field['serialization_exclude'], + validation_alias=common_field['validation_alias'], + serialization_alias=common_field['serialization_alias'], + frozen=common_field['frozen'], + metadata=common_field['metadata'], + ) + + def _generate_dc_field_schema( + self, + name: str, + field_info: FieldInfo, + decorators: DecoratorInfos, + ) -> core_schema.DataclassField: + """Prepare a DataclassField to represent the parameter/field, of a dataclass.""" + common_field = self._common_field_schema(name, field_info, decorators) + return core_schema.dataclass_field( + name, + common_field['schema'], + init=field_info.init, + init_only=field_info.init_var or None, + kw_only=None if field_info.kw_only else False, + serialization_exclude=common_field['serialization_exclude'], + validation_alias=common_field['validation_alias'], + serialization_alias=common_field['serialization_alias'], + frozen=common_field['frozen'], + metadata=common_field['metadata'], + ) + + @staticmethod + def _apply_alias_generator_to_field_info( + alias_generator: Callable[[str], str] | AliasGenerator, field_info: FieldInfo, field_name: str + ) -> None: + """Apply an alias_generator to aliases on a FieldInfo instance if appropriate. + + Args: + alias_generator: A callable that takes a string and returns a string, or an AliasGenerator instance. + field_info: The FieldInfo instance to which the alias_generator is (maybe) applied. + field_name: The name of the field from which to generate the alias. + """ + # Apply an alias_generator if + # 1. An alias is not specified + # 2. An alias is specified, but the priority is <= 1 + if ( + field_info.alias_priority is None + or field_info.alias_priority <= 1 + or field_info.alias is None + or field_info.validation_alias is None + or field_info.serialization_alias is None + ): + alias, validation_alias, serialization_alias = None, None, None + + if isinstance(alias_generator, AliasGenerator): + alias, validation_alias, serialization_alias = alias_generator.generate_aliases(field_name) + elif isinstance(alias_generator, Callable): + alias = alias_generator(field_name) + if not isinstance(alias, str): + raise TypeError(f'alias_generator {alias_generator} must return str, not {alias.__class__}') + + # if priority is not set, we set to 1 + # which supports the case where the alias_generator from a child class is used + # to generate an alias for a field in a parent class + if field_info.alias_priority is None or field_info.alias_priority <= 1: + field_info.alias_priority = 1 + + # if the priority is 1, then we set the aliases to the generated alias + if field_info.alias_priority == 1: + field_info.serialization_alias = _get_first_non_null(serialization_alias, alias) + field_info.validation_alias = _get_first_non_null(validation_alias, alias) + field_info.alias = alias + + # if any of the aliases are not set, then we set them to the corresponding generated alias + if field_info.alias is None: + field_info.alias = alias + if field_info.serialization_alias is None: + field_info.serialization_alias = _get_first_non_null(serialization_alias, alias) + if field_info.validation_alias is None: + field_info.validation_alias = _get_first_non_null(validation_alias, alias) + + @staticmethod + def _apply_alias_generator_to_computed_field_info( + alias_generator: Callable[[str], str] | AliasGenerator, + computed_field_info: ComputedFieldInfo, + computed_field_name: str, + ): + """Apply an alias_generator to alias on a ComputedFieldInfo instance if appropriate. + + Args: + alias_generator: A callable that takes a string and returns a string, or an AliasGenerator instance. + computed_field_info: The ComputedFieldInfo instance to which the alias_generator is (maybe) applied. + computed_field_name: The name of the computed field from which to generate the alias. + """ + # Apply an alias_generator if + # 1. An alias is not specified + # 2. An alias is specified, but the priority is <= 1 + + if ( + computed_field_info.alias_priority is None + or computed_field_info.alias_priority <= 1 + or computed_field_info.alias is None + ): + alias, validation_alias, serialization_alias = None, None, None + + if isinstance(alias_generator, AliasGenerator): + alias, validation_alias, serialization_alias = alias_generator.generate_aliases(computed_field_name) + elif isinstance(alias_generator, Callable): + alias = alias_generator(computed_field_name) + if not isinstance(alias, str): + raise TypeError(f'alias_generator {alias_generator} must return str, not {alias.__class__}') + + # if priority is not set, we set to 1 + # which supports the case where the alias_generator from a child class is used + # to generate an alias for a field in a parent class + if computed_field_info.alias_priority is None or computed_field_info.alias_priority <= 1: + computed_field_info.alias_priority = 1 + + # if the priority is 1, then we set the aliases to the generated alias + # note that we use the serialization_alias with priority over alias, as computed_field + # aliases are used for serialization only (not validation) + if computed_field_info.alias_priority == 1: + computed_field_info.alias = _get_first_non_null(serialization_alias, alias) + + @staticmethod + def _apply_field_title_generator_to_field_info( + config_wrapper: ConfigWrapper, field_info: FieldInfo | ComputedFieldInfo, field_name: str + ) -> None: + """Apply a field_title_generator on a FieldInfo or ComputedFieldInfo instance if appropriate + Args: + config_wrapper: The config of the model + field_info: The FieldInfo or ComputedField instance to which the title_generator is (maybe) applied. + field_name: The name of the field from which to generate the title. + """ + field_title_generator = field_info.field_title_generator or config_wrapper.field_title_generator + + if field_title_generator is None: + return + + if field_info.title is None: + title = field_title_generator(field_name, field_info) # type: ignore + if not isinstance(title, str): + raise TypeError(f'field_title_generator {field_title_generator} must return str, not {title.__class__}') + + field_info.title = title + + def _common_field_schema( # C901 + self, name: str, field_info: FieldInfo, decorators: DecoratorInfos + ) -> _CommonField: + # Update FieldInfo annotation if appropriate: + from .. import AliasChoices, AliasPath + from ..fields import FieldInfo + + if has_instance_in_type(field_info.annotation, (ForwardRef, str)): + types_namespace = self._types_namespace + if self._typevars_map: + types_namespace = (types_namespace or {}).copy() + # Ensure that typevars get mapped to their concrete types: + types_namespace.update({k.__name__: v for k, v in self._typevars_map.items()}) + + evaluated = _typing_extra.eval_type_lenient(field_info.annotation, types_namespace) + if evaluated is not field_info.annotation and not has_instance_in_type(evaluated, PydanticRecursiveRef): + new_field_info = FieldInfo.from_annotation(evaluated) + field_info.annotation = new_field_info.annotation + + # Handle any field info attributes that may have been obtained from now-resolved annotations + for k, v in new_field_info._attributes_set.items(): + # If an attribute is already set, it means it was set by assigning to a call to Field (or just a + # default value), and that should take the highest priority. So don't overwrite existing attributes. + # We skip over "attributes" that are present in the metadata_lookup dict because these won't + # actually end up as attributes of the `FieldInfo` instance. + if k not in field_info._attributes_set and k not in field_info.metadata_lookup: + setattr(field_info, k, v) + + # Finally, ensure the field info also reflects all the `_attributes_set` that are actually metadata. + field_info.metadata = [*new_field_info.metadata, *field_info.metadata] + + source_type, annotations = field_info.annotation, field_info.metadata + + def set_discriminator(schema: CoreSchema) -> CoreSchema: + schema = self._apply_discriminator_to_union(schema, field_info.discriminator) + return schema + + with self.field_name_stack.push(name): + if field_info.discriminator is not None: + schema = self._apply_annotations(source_type, annotations, transform_inner_schema=set_discriminator) + else: + schema = self._apply_annotations( + source_type, + annotations, + ) + + # This V1 compatibility shim should eventually be removed + # push down any `each_item=True` validators + # note that this won't work for any Annotated types that get wrapped by a function validator + # but that's okay because that didn't exist in V1 + this_field_validators = filter_field_decorator_info_by_field(decorators.validators.values(), name) + if _validators_require_validate_default(this_field_validators): + field_info.validate_default = True + each_item_validators = [v for v in this_field_validators if v.info.each_item is True] + this_field_validators = [v for v in this_field_validators if v not in each_item_validators] + schema = apply_each_item_validators(schema, each_item_validators, name) + + schema = apply_validators(schema, filter_field_decorator_info_by_field(this_field_validators, name), name) + schema = apply_validators( + schema, filter_field_decorator_info_by_field(decorators.field_validators.values(), name), name + ) + + # the default validator needs to go outside of any other validators + # so that it is the topmost validator for the field validator + # which uses it to check if the field has a default value or not + if not field_info.is_required(): + schema = wrap_default(field_info, schema) + + schema = self._apply_field_serializers( + schema, filter_field_decorator_info_by_field(decorators.field_serializers.values(), name) + ) + self._apply_field_title_generator_to_field_info(self._config_wrapper, field_info, name) + + json_schema_updates = { + 'title': field_info.title, + 'description': field_info.description, + 'deprecated': bool(field_info.deprecated) or field_info.deprecated == '' or None, + 'examples': to_jsonable_python(field_info.examples), + } + json_schema_updates = {k: v for k, v in json_schema_updates.items() if v is not None} + + json_schema_extra = field_info.json_schema_extra + + metadata = build_metadata_dict( + js_annotation_functions=[get_json_schema_update_func(json_schema_updates, json_schema_extra)] + ) + + alias_generator = self._config_wrapper.alias_generator + if alias_generator is not None: + self._apply_alias_generator_to_field_info(alias_generator, field_info, name) + + if isinstance(field_info.validation_alias, (AliasChoices, AliasPath)): + validation_alias = field_info.validation_alias.convert_to_aliases() + else: + validation_alias = field_info.validation_alias + + return _common_field( + schema, + serialization_exclude=True if field_info.exclude else None, + validation_alias=validation_alias, + serialization_alias=field_info.serialization_alias, + frozen=field_info.frozen, + metadata=metadata, + ) + + def _union_schema(self, union_type: Any) -> core_schema.CoreSchema: + """Generate schema for a Union.""" + args = self._get_args_resolving_forward_refs(union_type, required=True) + choices: list[CoreSchema] = [] + nullable = False + for arg in args: + if arg is None or arg is _typing_extra.NoneType: + nullable = True + else: + choices.append(self.generate_schema(arg)) + + if len(choices) == 1: + s = choices[0] + else: + choices_with_tags: list[CoreSchema | tuple[CoreSchema, str]] = [] + for choice in choices: + tag = choice.get('metadata', {}).get(_core_utils.TAGGED_UNION_TAG_KEY) + if tag is not None: + choices_with_tags.append((choice, tag)) + else: + choices_with_tags.append(choice) + s = core_schema.union_schema(choices_with_tags) + + if nullable: + s = core_schema.nullable_schema(s) + return s + + def _type_alias_type_schema( + self, + obj: Any, # TypeAliasType + ) -> CoreSchema: + with self.defs.get_schema_or_ref(obj) as (ref, maybe_schema): + if maybe_schema is not None: + return maybe_schema + + origin = get_origin(obj) or obj + + annotation = origin.__value__ + typevars_map = get_standard_typevars_map(obj) + + with self._types_namespace_stack.push(origin): + annotation = _typing_extra.eval_type_lenient(annotation, self._types_namespace) + annotation = replace_types(annotation, typevars_map) + schema = self.generate_schema(annotation) + assert schema['type'] != 'definitions' + schema['ref'] = ref # type: ignore + self.defs.definitions[ref] = schema + return core_schema.definition_reference_schema(ref) + + def _literal_schema(self, literal_type: Any) -> CoreSchema: + """Generate schema for a Literal.""" + expected = _typing_extra.all_literal_values(literal_type) + assert expected, f'literal "expected" cannot be empty, obj={literal_type}' + return core_schema.literal_schema(expected) + + def _typed_dict_schema(self, typed_dict_cls: Any, origin: Any) -> core_schema.CoreSchema: + """Generate schema for a TypedDict. + + It is not possible to track required/optional keys in TypedDict without __required_keys__ + since TypedDict.__new__ erases the base classes (it replaces them with just `dict`) + and thus we can track usage of total=True/False + __required_keys__ was added in Python 3.9 + (https://github.com/miss-islington/cpython/blob/1e9939657dd1f8eb9f596f77c1084d2d351172fc/Doc/library/typing.rst?plain=1#L1546-L1548) + however it is buggy + (https://github.com/python/typing_extensions/blob/ac52ac5f2cb0e00e7988bae1e2a1b8257ac88d6d/src/typing_extensions.py#L657-L666). + + On 3.11 but < 3.12 TypedDict does not preserve inheritance information. + + Hence to avoid creating validators that do not do what users expect we only + support typing.TypedDict on Python >= 3.12 or typing_extension.TypedDict on all versions + """ + from ..fields import FieldInfo + + with self.model_type_stack.push(typed_dict_cls), self.defs.get_schema_or_ref(typed_dict_cls) as ( + typed_dict_ref, + maybe_schema, + ): + if maybe_schema is not None: + return maybe_schema + + typevars_map = get_standard_typevars_map(typed_dict_cls) + if origin is not None: + typed_dict_cls = origin + + if not _SUPPORTS_TYPEDDICT and type(typed_dict_cls).__module__ == 'typing': + raise PydanticUserError( + 'Please use `typing_extensions.TypedDict` instead of `typing.TypedDict` on Python < 3.12.', + code='typed-dict-version', + ) + + try: + config: ConfigDict | None = get_attribute_from_bases(typed_dict_cls, '__pydantic_config__') + except AttributeError: + config = None + + with self._config_wrapper_stack.push(config), self._types_namespace_stack.push(typed_dict_cls): + core_config = self._config_wrapper.core_config(typed_dict_cls) + + self = self._current_generate_schema + + required_keys: frozenset[str] = typed_dict_cls.__required_keys__ + + fields: dict[str, core_schema.TypedDictField] = {} + + decorators = DecoratorInfos.build(typed_dict_cls) + + if self._config_wrapper.use_attribute_docstrings: + field_docstrings = extract_docstrings_from_cls(typed_dict_cls, use_inspect=True) + else: + field_docstrings = None + + for field_name, annotation in get_type_hints_infer_globalns( + typed_dict_cls, localns=self._types_namespace, include_extras=True + ).items(): + annotation = replace_types(annotation, typevars_map) + required = field_name in required_keys + + if get_origin(annotation) == _typing_extra.Required: + required = True + annotation = self._get_args_resolving_forward_refs( + annotation, + required=True, + )[0] + elif get_origin(annotation) == _typing_extra.NotRequired: + required = False + annotation = self._get_args_resolving_forward_refs( + annotation, + required=True, + )[0] + + field_info = FieldInfo.from_annotation(annotation) + if ( + field_docstrings is not None + and field_info.description is None + and field_name in field_docstrings + ): + field_info.description = field_docstrings[field_name] + self._apply_field_title_generator_to_field_info(self._config_wrapper, field_info, field_name) + fields[field_name] = self._generate_td_field_schema( + field_name, field_info, decorators, required=required + ) + + title = self._get_model_title_from_config(typed_dict_cls, ConfigWrapper(config)) + metadata = build_metadata_dict( + js_functions=[partial(modify_model_json_schema, cls=typed_dict_cls, title=title)], + typed_dict_cls=typed_dict_cls, + ) + td_schema = core_schema.typed_dict_schema( + fields, + computed_fields=[ + self._computed_field_schema(d, decorators.field_serializers) + for d in decorators.computed_fields.values() + ], + ref=typed_dict_ref, + metadata=metadata, + config=core_config, + ) + + schema = self._apply_model_serializers(td_schema, decorators.model_serializers.values()) + schema = apply_model_validators(schema, decorators.model_validators.values(), 'all') + self.defs.definitions[typed_dict_ref] = schema + return core_schema.definition_reference_schema(typed_dict_ref) + + def _namedtuple_schema(self, namedtuple_cls: Any, origin: Any) -> core_schema.CoreSchema: + """Generate schema for a NamedTuple.""" + with self.model_type_stack.push(namedtuple_cls), self.defs.get_schema_or_ref(namedtuple_cls) as ( + namedtuple_ref, + maybe_schema, + ): + if maybe_schema is not None: + return maybe_schema + typevars_map = get_standard_typevars_map(namedtuple_cls) + if origin is not None: + namedtuple_cls = origin + + annotations: dict[str, Any] = get_type_hints_infer_globalns( + namedtuple_cls, include_extras=True, localns=self._types_namespace + ) + if not annotations: + # annotations is empty, happens if namedtuple_cls defined via collections.namedtuple(...) + annotations = {k: Any for k in namedtuple_cls._fields} + + if typevars_map: + annotations = { + field_name: replace_types(annotation, typevars_map) + for field_name, annotation in annotations.items() + } + + arguments_schema = core_schema.arguments_schema( + [ + self._generate_parameter_schema( + field_name, annotation, default=namedtuple_cls._field_defaults.get(field_name, Parameter.empty) + ) + for field_name, annotation in annotations.items() + ], + metadata=build_metadata_dict(js_prefer_positional_arguments=True), + ) + return core_schema.call_schema(arguments_schema, namedtuple_cls, ref=namedtuple_ref) + + def _generate_parameter_schema( + self, + name: str, + annotation: type[Any], + default: Any = Parameter.empty, + mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None, + ) -> core_schema.ArgumentsParameter: + """Prepare a ArgumentsParameter to represent a field in a namedtuple or function signature.""" + from ..fields import FieldInfo + + if default is Parameter.empty: + field = FieldInfo.from_annotation(annotation) + else: + field = FieldInfo.from_annotated_attribute(annotation, default) + assert field.annotation is not None, 'field.annotation should not be None when generating a schema' + source_type, annotations = field.annotation, field.metadata + with self.field_name_stack.push(name): + schema = self._apply_annotations(source_type, annotations) + + if not field.is_required(): + schema = wrap_default(field, schema) + + parameter_schema = core_schema.arguments_parameter(name, schema) + if mode is not None: + parameter_schema['mode'] = mode + if field.alias is not None: + parameter_schema['alias'] = field.alias + else: + alias_generator = self._config_wrapper.alias_generator + if isinstance(alias_generator, AliasGenerator) and alias_generator.alias is not None: + parameter_schema['alias'] = alias_generator.alias(name) + elif isinstance(alias_generator, Callable): + parameter_schema['alias'] = alias_generator(name) + return parameter_schema + + def _tuple_schema(self, tuple_type: Any) -> core_schema.CoreSchema: + """Generate schema for a Tuple, e.g. `tuple[int, str]` or `tuple[int, ...]`.""" + # TODO: do we really need to resolve type vars here? + typevars_map = get_standard_typevars_map(tuple_type) + params = self._get_args_resolving_forward_refs(tuple_type) + + if typevars_map and params: + params = tuple(replace_types(param, typevars_map) for param in params) + + # NOTE: subtle difference: `tuple[()]` gives `params=()`, whereas `typing.Tuple[()]` gives `params=((),)` + # This is only true for <3.11, on Python 3.11+ `typing.Tuple[()]` gives `params=()` + if not params: + if tuple_type in TUPLE_TYPES: + return core_schema.tuple_schema([core_schema.any_schema()], variadic_item_index=0) + else: + # special case for `tuple[()]` which means `tuple[]` - an empty tuple + return core_schema.tuple_schema([]) + elif params[-1] is Ellipsis: + if len(params) == 2: + return core_schema.tuple_schema([self.generate_schema(params[0])], variadic_item_index=0) + else: + # TODO: something like https://github.com/pydantic/pydantic/issues/5952 + raise ValueError('Variable tuples can only have one type') + elif len(params) == 1 and params[0] == (): + # special case for `Tuple[()]` which means `Tuple[]` - an empty tuple + # NOTE: This conditional can be removed when we drop support for Python 3.10. + return core_schema.tuple_schema([]) + else: + return core_schema.tuple_schema([self.generate_schema(param) for param in params]) + + def _type_schema(self) -> core_schema.CoreSchema: + return core_schema.custom_error_schema( + core_schema.is_instance_schema(type), + custom_error_type='is_type', + custom_error_message='Input should be a type', + ) + + def _union_is_subclass_schema(self, union_type: Any) -> core_schema.CoreSchema: + """Generate schema for `Type[Union[X, ...]]`.""" + args = self._get_args_resolving_forward_refs(union_type, required=True) + return core_schema.union_schema([self.generate_schema(typing.Type[args]) for args in args]) + + def _subclass_schema(self, type_: Any) -> core_schema.CoreSchema: + """Generate schema for a Type, e.g. `Type[int]`.""" + type_param = self._get_first_arg_or_any(type_) + if type_param == Any: + return self._type_schema() + elif isinstance(type_param, typing.TypeVar): + if type_param.__bound__: + if _typing_extra.origin_is_union(get_origin(type_param.__bound__)): + return self._union_is_subclass_schema(type_param.__bound__) + return core_schema.is_subclass_schema(type_param.__bound__) + elif type_param.__constraints__: + return core_schema.union_schema( + [self.generate_schema(typing.Type[c]) for c in type_param.__constraints__] + ) + else: + return self._type_schema() + elif _typing_extra.origin_is_union(get_origin(type_param)): + return self._union_is_subclass_schema(type_param) + else: + return core_schema.is_subclass_schema(type_param) + + def _sequence_schema(self, sequence_type: Any) -> core_schema.CoreSchema: + """Generate schema for a Sequence, e.g. `Sequence[int]`.""" + from ._std_types_schema import serialize_sequence_via_list + + item_type = self._get_first_arg_or_any(sequence_type) + item_type_schema = self.generate_schema(item_type) + list_schema = core_schema.list_schema(item_type_schema) + + python_schema = core_schema.is_instance_schema(typing.Sequence, cls_repr='Sequence') + if item_type != Any: + from ._validators import sequence_validator + + python_schema = core_schema.chain_schema( + [python_schema, core_schema.no_info_wrap_validator_function(sequence_validator, list_schema)], + ) + + serialization = core_schema.wrap_serializer_function_ser_schema( + serialize_sequence_via_list, schema=item_type_schema, info_arg=True + ) + return core_schema.json_or_python_schema( + json_schema=list_schema, python_schema=python_schema, serialization=serialization + ) + + def _iterable_schema(self, type_: Any) -> core_schema.GeneratorSchema: + """Generate a schema for an `Iterable`.""" + item_type = self._get_first_arg_or_any(type_) + + return core_schema.generator_schema(self.generate_schema(item_type)) + + def _pattern_schema(self, pattern_type: Any) -> core_schema.CoreSchema: + from . import _validators + + metadata = build_metadata_dict(js_functions=[lambda _1, _2: {'type': 'string', 'format': 'regex'}]) + ser = core_schema.plain_serializer_function_ser_schema( + attrgetter('pattern'), when_used='json', return_schema=core_schema.str_schema() + ) + if pattern_type == typing.Pattern or pattern_type == re.Pattern: + # bare type + return core_schema.no_info_plain_validator_function( + _validators.pattern_either_validator, serialization=ser, metadata=metadata + ) + + param = self._get_args_resolving_forward_refs( + pattern_type, + required=True, + )[0] + if param is str: + return core_schema.no_info_plain_validator_function( + _validators.pattern_str_validator, serialization=ser, metadata=metadata + ) + elif param is bytes: + return core_schema.no_info_plain_validator_function( + _validators.pattern_bytes_validator, serialization=ser, metadata=metadata + ) + else: + raise PydanticSchemaGenerationError(f'Unable to generate pydantic-core schema for {pattern_type!r}.') + + def _hashable_schema(self) -> core_schema.CoreSchema: + return core_schema.custom_error_schema( + core_schema.is_instance_schema(collections.abc.Hashable), + custom_error_type='is_hashable', + custom_error_message='Input should be hashable', + ) + + def _dataclass_schema( + self, dataclass: type[StandardDataclass], origin: type[StandardDataclass] | None + ) -> core_schema.CoreSchema: + """Generate schema for a dataclass.""" + with self.model_type_stack.push(dataclass), self.defs.get_schema_or_ref(dataclass) as ( + dataclass_ref, + maybe_schema, + ): + if maybe_schema is not None: + return maybe_schema + + typevars_map = get_standard_typevars_map(dataclass) + if origin is not None: + dataclass = origin + + with ExitStack() as dataclass_bases_stack: + # Pushing a namespace prioritises items already in the stack, so iterate though the MRO forwards + for dataclass_base in dataclass.__mro__: + if dataclasses.is_dataclass(dataclass_base): + dataclass_bases_stack.enter_context(self._types_namespace_stack.push(dataclass_base)) + + # Pushing a config overwrites the previous config, so iterate though the MRO backwards + config = None + for dataclass_base in reversed(dataclass.__mro__): + if dataclasses.is_dataclass(dataclass_base): + config = getattr(dataclass_base, '__pydantic_config__', None) + dataclass_bases_stack.enter_context(self._config_wrapper_stack.push(config)) + + core_config = self._config_wrapper.core_config(dataclass) + + self = self._current_generate_schema + + from ..dataclasses import is_pydantic_dataclass + + if is_pydantic_dataclass(dataclass): + fields = deepcopy(dataclass.__pydantic_fields__) + if typevars_map: + for field in fields.values(): + field.apply_typevars_map(typevars_map, self._types_namespace) + else: + fields = collect_dataclass_fields( + dataclass, + self._types_namespace, + typevars_map=typevars_map, + ) + + # disallow combination of init=False on a dataclass field and extra='allow' on a dataclass + if self._config_wrapper_stack.tail.extra == 'allow': + # disallow combination of init=False on a dataclass field and extra='allow' on a dataclass + for field_name, field in fields.items(): + if field.init is False: + raise PydanticUserError( + f'Field {field_name} has `init=False` and dataclass has config setting `extra="allow"`. ' + f'This combination is not allowed.', + code='dataclass-init-false-extra-allow', + ) + + decorators = dataclass.__dict__.get('__pydantic_decorators__') or DecoratorInfos.build(dataclass) + # Move kw_only=False args to the start of the list, as this is how vanilla dataclasses work. + # Note that when kw_only is missing or None, it is treated as equivalent to kw_only=True + args = sorted( + (self._generate_dc_field_schema(k, v, decorators) for k, v in fields.items()), + key=lambda a: a.get('kw_only') is not False, + ) + has_post_init = hasattr(dataclass, '__post_init__') + has_slots = hasattr(dataclass, '__slots__') + + args_schema = core_schema.dataclass_args_schema( + dataclass.__name__, + args, + computed_fields=[ + self._computed_field_schema(d, decorators.field_serializers) + for d in decorators.computed_fields.values() + ], + collect_init_only=has_post_init, + ) + + inner_schema = apply_validators(args_schema, decorators.root_validators.values(), None) + + model_validators = decorators.model_validators.values() + inner_schema = apply_model_validators(inner_schema, model_validators, 'inner') + + title = self._get_model_title_from_config(dataclass, ConfigWrapper(config)) + metadata = build_metadata_dict( + js_functions=[partial(modify_model_json_schema, cls=dataclass, title=title)] + ) + + dc_schema = core_schema.dataclass_schema( + dataclass, + inner_schema, + post_init=has_post_init, + ref=dataclass_ref, + fields=[field.name for field in dataclasses.fields(dataclass)], + slots=has_slots, + config=core_config, + metadata=metadata, + ) + schema = self._apply_model_serializers(dc_schema, decorators.model_serializers.values()) + schema = apply_model_validators(schema, model_validators, 'outer') + self.defs.definitions[dataclass_ref] = schema + return core_schema.definition_reference_schema(dataclass_ref) + + # Type checkers seem to assume ExitStack may suppress exceptions and therefore + # control flow can exit the `with` block without returning. + assert False, 'Unreachable' + + def _callable_schema(self, function: Callable[..., Any]) -> core_schema.CallSchema: + """Generate schema for a Callable. + + TODO support functional validators once we support them in Config + """ + sig = signature(function) + + type_hints = _typing_extra.get_function_type_hints(function, types_namespace=self._types_namespace) + + mode_lookup: dict[_ParameterKind, Literal['positional_only', 'positional_or_keyword', 'keyword_only']] = { + Parameter.POSITIONAL_ONLY: 'positional_only', + Parameter.POSITIONAL_OR_KEYWORD: 'positional_or_keyword', + Parameter.KEYWORD_ONLY: 'keyword_only', + } + + arguments_list: list[core_schema.ArgumentsParameter] = [] + var_args_schema: core_schema.CoreSchema | None = None + var_kwargs_schema: core_schema.CoreSchema | None = None + + for name, p in sig.parameters.items(): + if p.annotation is sig.empty: + annotation = typing.cast(Any, Any) + else: + annotation = type_hints[name] + + parameter_mode = mode_lookup.get(p.kind) + if parameter_mode is not None: + arg_schema = self._generate_parameter_schema(name, annotation, p.default, parameter_mode) + arguments_list.append(arg_schema) + elif p.kind == Parameter.VAR_POSITIONAL: + var_args_schema = self.generate_schema(annotation) + else: + assert p.kind == Parameter.VAR_KEYWORD, p.kind + var_kwargs_schema = self.generate_schema(annotation) + + return_schema: core_schema.CoreSchema | None = None + config_wrapper = self._config_wrapper + if config_wrapper.validate_return: + return_hint = type_hints.get('return') + if return_hint is not None: + return_schema = self.generate_schema(return_hint) + + return core_schema.call_schema( + core_schema.arguments_schema( + arguments_list, + var_args_schema=var_args_schema, + var_kwargs_schema=var_kwargs_schema, + populate_by_name=config_wrapper.populate_by_name, + ), + function, + return_schema=return_schema, + ) + + def _unsubstituted_typevar_schema(self, typevar: typing.TypeVar) -> core_schema.CoreSchema: + assert isinstance(typevar, typing.TypeVar) + + bound = typevar.__bound__ + constraints = typevar.__constraints__ + + try: + typevar_has_default = typevar.has_default() # type: ignore + except AttributeError: + # could still have a default if it's an old version of typing_extensions.TypeVar + typevar_has_default = getattr(typevar, '__default__', None) is not None + + if (bound is not None) + (len(constraints) != 0) + typevar_has_default > 1: + raise NotImplementedError( + 'Pydantic does not support mixing more than one of TypeVar bounds, constraints and defaults' + ) + + if typevar_has_default: + return self.generate_schema(typevar.__default__) # type: ignore + elif constraints: + return self._union_schema(typing.Union[constraints]) # type: ignore + elif bound: + schema = self.generate_schema(bound) + schema['serialization'] = core_schema.wrap_serializer_function_ser_schema( + lambda x, h: h(x), schema=core_schema.any_schema() + ) + return schema + else: + return core_schema.any_schema() + + def _computed_field_schema( + self, + d: Decorator[ComputedFieldInfo], + field_serializers: dict[str, Decorator[FieldSerializerDecoratorInfo]], + ) -> core_schema.ComputedField: + try: + return_type = _decorators.get_function_return_type(d.func, d.info.return_type, self._types_namespace) + except NameError as e: + raise PydanticUndefinedAnnotation.from_name_error(e) from e + if return_type is PydanticUndefined: + raise PydanticUserError( + 'Computed field is missing return type annotation or specifying `return_type`' + ' to the `@computed_field` decorator (e.g. `@computed_field(return_type=int|str)`)', + code='model-field-missing-annotation', + ) + + return_type = replace_types(return_type, self._typevars_map) + # Create a new ComputedFieldInfo so that different type parametrizations of the same + # generic model's computed field can have different return types. + d.info = dataclasses.replace(d.info, return_type=return_type) + return_type_schema = self.generate_schema(return_type) + # Apply serializers to computed field if there exist + return_type_schema = self._apply_field_serializers( + return_type_schema, + filter_field_decorator_info_by_field(field_serializers.values(), d.cls_var_name), + computed_field=True, + ) + + alias_generator = self._config_wrapper.alias_generator + if alias_generator is not None: + self._apply_alias_generator_to_computed_field_info( + alias_generator=alias_generator, computed_field_info=d.info, computed_field_name=d.cls_var_name + ) + self._apply_field_title_generator_to_field_info(self._config_wrapper, d.info, d.cls_var_name) + + def set_computed_field_metadata(schema: CoreSchemaOrField, handler: GetJsonSchemaHandler) -> JsonSchemaValue: + json_schema = handler(schema) + + json_schema['readOnly'] = True + + title = d.info.title + if title is not None: + json_schema['title'] = title + + description = d.info.description + if description is not None: + json_schema['description'] = description + + if d.info.deprecated or d.info.deprecated == '': + json_schema['deprecated'] = True + + examples = d.info.examples + if examples is not None: + json_schema['examples'] = to_jsonable_python(examples) + + json_schema_extra = d.info.json_schema_extra + if json_schema_extra is not None: + add_json_schema_extra(json_schema, json_schema_extra) + + return json_schema + + metadata = build_metadata_dict(js_annotation_functions=[set_computed_field_metadata]) + return core_schema.computed_field( + d.cls_var_name, return_schema=return_type_schema, alias=d.info.alias, metadata=metadata + ) + + def _annotated_schema(self, annotated_type: Any) -> core_schema.CoreSchema: + """Generate schema for an Annotated type, e.g. `Annotated[int, Field(...)]` or `Annotated[int, Gt(0)]`.""" + from ..fields import FieldInfo + + source_type, *annotations = self._get_args_resolving_forward_refs( + annotated_type, + required=True, + ) + schema = self._apply_annotations(source_type, annotations) + # put the default validator last so that TypeAdapter.get_default_value() works + # even if there are function validators involved + for annotation in annotations: + if isinstance(annotation, FieldInfo): + schema = wrap_default(annotation, schema) + return schema + + def _get_prepare_pydantic_annotations_for_known_type( + self, obj: Any, annotations: tuple[Any, ...] + ) -> tuple[Any, list[Any]] | None: + from ._std_types_schema import PREPARE_METHODS + + # Check for hashability + try: + hash(obj) + except TypeError: + # obj is definitely not a known type if this fails + return None + + for gen in PREPARE_METHODS: + res = gen(obj, annotations, self._config_wrapper.config_dict) + if res is not None: + return res + + return None + + def _apply_annotations( + self, + source_type: Any, + annotations: list[Any], + transform_inner_schema: Callable[[CoreSchema], CoreSchema] = lambda x: x, + ) -> CoreSchema: + """Apply arguments from `Annotated` or from `FieldInfo` to a schema. + + This gets called by `GenerateSchema._annotated_schema` but differs from it in that it does + not expect `source_type` to be an `Annotated` object, it expects it to be the first argument of that + (in other words, `GenerateSchema._annotated_schema` just unpacks `Annotated`, this process it). + """ + annotations = list(_known_annotated_metadata.expand_grouped_metadata(annotations)) + res = self._get_prepare_pydantic_annotations_for_known_type(source_type, tuple(annotations)) + if res is not None: + source_type, annotations = res + + pydantic_js_annotation_functions: list[GetJsonSchemaFunction] = [] + + def inner_handler(obj: Any) -> CoreSchema: + from_property = self._generate_schema_from_property(obj, source_type) + if from_property is None: + schema = self._generate_schema_inner(obj) + else: + schema = from_property + metadata_js_function = _extract_get_pydantic_json_schema(obj, schema) + if metadata_js_function is not None: + metadata_schema = resolve_original_schema(schema, self.defs.definitions) + if metadata_schema is not None: + self._add_js_function(metadata_schema, metadata_js_function) + return transform_inner_schema(schema) + + get_inner_schema = CallbackGetCoreSchemaHandler(inner_handler, self) + + for annotation in annotations: + if annotation is None: + continue + get_inner_schema = self._get_wrapped_inner_schema( + get_inner_schema, annotation, pydantic_js_annotation_functions + ) + + schema = get_inner_schema(source_type) + if pydantic_js_annotation_functions: + metadata = CoreMetadataHandler(schema).metadata + metadata.setdefault('pydantic_js_annotation_functions', []).extend(pydantic_js_annotation_functions) + return _add_custom_serialization_from_json_encoders(self._config_wrapper.json_encoders, source_type, schema) + + def _apply_single_annotation(self, schema: core_schema.CoreSchema, metadata: Any) -> core_schema.CoreSchema: + from ..fields import FieldInfo + + if isinstance(metadata, FieldInfo): + for field_metadata in metadata.metadata: + schema = self._apply_single_annotation(schema, field_metadata) + + if metadata.discriminator is not None: + schema = self._apply_discriminator_to_union(schema, metadata.discriminator) + return schema + + if schema['type'] == 'nullable': + # for nullable schemas, metadata is automatically applied to the inner schema + inner = schema.get('schema', core_schema.any_schema()) + inner = self._apply_single_annotation(inner, metadata) + if inner: + schema['schema'] = inner + return schema + + original_schema = schema + ref = schema.get('ref', None) + if ref is not None: + schema = schema.copy() + new_ref = ref + f'_{repr(metadata)}' + if new_ref in self.defs.definitions: + return self.defs.definitions[new_ref] + schema['ref'] = new_ref # type: ignore + elif schema['type'] == 'definition-ref': + ref = schema['schema_ref'] + if ref in self.defs.definitions: + schema = self.defs.definitions[ref].copy() + new_ref = ref + f'_{repr(metadata)}' + if new_ref in self.defs.definitions: + return self.defs.definitions[new_ref] + schema['ref'] = new_ref # type: ignore + + maybe_updated_schema = _known_annotated_metadata.apply_known_metadata(metadata, schema.copy()) + + if maybe_updated_schema is not None: + return maybe_updated_schema + return original_schema + + def _apply_single_annotation_json_schema( + self, schema: core_schema.CoreSchema, metadata: Any + ) -> core_schema.CoreSchema: + from ..fields import FieldInfo + + if isinstance(metadata, FieldInfo): + for field_metadata in metadata.metadata: + schema = self._apply_single_annotation_json_schema(schema, field_metadata) + json_schema_update: JsonSchemaValue = {} + if metadata.title: + json_schema_update['title'] = metadata.title + if metadata.description: + json_schema_update['description'] = metadata.description + if metadata.examples: + json_schema_update['examples'] = to_jsonable_python(metadata.examples) + + json_schema_extra = metadata.json_schema_extra + if json_schema_update or json_schema_extra: + CoreMetadataHandler(schema).metadata.setdefault('pydantic_js_annotation_functions', []).append( + get_json_schema_update_func(json_schema_update, json_schema_extra) + ) + return schema + + def _get_wrapped_inner_schema( + self, + get_inner_schema: GetCoreSchemaHandler, + annotation: Any, + pydantic_js_annotation_functions: list[GetJsonSchemaFunction], + ) -> CallbackGetCoreSchemaHandler: + metadata_get_schema: GetCoreSchemaFunction = getattr(annotation, '__get_pydantic_core_schema__', None) or ( + lambda source, handler: handler(source) + ) + + def new_handler(source: Any) -> core_schema.CoreSchema: + schema = metadata_get_schema(source, get_inner_schema) + schema = self._apply_single_annotation(schema, annotation) + schema = self._apply_single_annotation_json_schema(schema, annotation) + + metadata_js_function = _extract_get_pydantic_json_schema(annotation, schema) + if metadata_js_function is not None: + pydantic_js_annotation_functions.append(metadata_js_function) + return schema + + return CallbackGetCoreSchemaHandler(new_handler, self) + + def _apply_field_serializers( + self, + schema: core_schema.CoreSchema, + serializers: list[Decorator[FieldSerializerDecoratorInfo]], + computed_field: bool = False, + ) -> core_schema.CoreSchema: + """Apply field serializers to a schema.""" + if serializers: + schema = copy(schema) + if schema['type'] == 'definitions': + inner_schema = schema['schema'] + schema['schema'] = self._apply_field_serializers(inner_schema, serializers) + return schema + else: + ref = typing.cast('str|None', schema.get('ref', None)) + if ref is not None: + schema = core_schema.definition_reference_schema(ref) + + # use the last serializer to make it easy to override a serializer set on a parent model + serializer = serializers[-1] + is_field_serializer, info_arg = inspect_field_serializer( + serializer.func, serializer.info.mode, computed_field=computed_field + ) + + try: + return_type = _decorators.get_function_return_type( + serializer.func, serializer.info.return_type, self._types_namespace + ) + except NameError as e: + raise PydanticUndefinedAnnotation.from_name_error(e) from e + + if return_type is PydanticUndefined: + return_schema = None + else: + return_schema = self.generate_schema(return_type) + + if serializer.info.mode == 'wrap': + schema['serialization'] = core_schema.wrap_serializer_function_ser_schema( + serializer.func, + is_field_serializer=is_field_serializer, + info_arg=info_arg, + return_schema=return_schema, + when_used=serializer.info.when_used, + ) + else: + assert serializer.info.mode == 'plain' + schema['serialization'] = core_schema.plain_serializer_function_ser_schema( + serializer.func, + is_field_serializer=is_field_serializer, + info_arg=info_arg, + return_schema=return_schema, + when_used=serializer.info.when_used, + ) + return schema + + def _apply_model_serializers( + self, schema: core_schema.CoreSchema, serializers: Iterable[Decorator[ModelSerializerDecoratorInfo]] + ) -> core_schema.CoreSchema: + """Apply model serializers to a schema.""" + ref: str | None = schema.pop('ref', None) # type: ignore + if serializers: + serializer = list(serializers)[-1] + info_arg = inspect_model_serializer(serializer.func, serializer.info.mode) + + try: + return_type = _decorators.get_function_return_type( + serializer.func, serializer.info.return_type, self._types_namespace + ) + except NameError as e: + raise PydanticUndefinedAnnotation.from_name_error(e) from e + if return_type is PydanticUndefined: + return_schema = None + else: + return_schema = self.generate_schema(return_type) + + if serializer.info.mode == 'wrap': + ser_schema: core_schema.SerSchema = core_schema.wrap_serializer_function_ser_schema( + serializer.func, + info_arg=info_arg, + return_schema=return_schema, + when_used=serializer.info.when_used, + ) + else: + # plain + ser_schema = core_schema.plain_serializer_function_ser_schema( + serializer.func, + info_arg=info_arg, + return_schema=return_schema, + when_used=serializer.info.when_used, + ) + schema['serialization'] = ser_schema + if ref: + schema['ref'] = ref # type: ignore + return schema + + +_VALIDATOR_F_MATCH: Mapping[ + tuple[FieldValidatorModes, Literal['no-info', 'with-info']], + Callable[[Callable[..., Any], core_schema.CoreSchema, str | None], core_schema.CoreSchema], +] = { + ('before', 'no-info'): lambda f, schema, _: core_schema.no_info_before_validator_function(f, schema), + ('after', 'no-info'): lambda f, schema, _: core_schema.no_info_after_validator_function(f, schema), + ('plain', 'no-info'): lambda f, _1, _2: core_schema.no_info_plain_validator_function(f), + ('wrap', 'no-info'): lambda f, schema, _: core_schema.no_info_wrap_validator_function(f, schema), + ('before', 'with-info'): lambda f, schema, field_name: core_schema.with_info_before_validator_function( + f, schema, field_name=field_name + ), + ('after', 'with-info'): lambda f, schema, field_name: core_schema.with_info_after_validator_function( + f, schema, field_name=field_name + ), + ('plain', 'with-info'): lambda f, _, field_name: core_schema.with_info_plain_validator_function( + f, field_name=field_name + ), + ('wrap', 'with-info'): lambda f, schema, field_name: core_schema.with_info_wrap_validator_function( + f, schema, field_name=field_name + ), +} + + +def apply_validators( + schema: core_schema.CoreSchema, + validators: Iterable[Decorator[RootValidatorDecoratorInfo]] + | Iterable[Decorator[ValidatorDecoratorInfo]] + | Iterable[Decorator[FieldValidatorDecoratorInfo]], + field_name: str | None, +) -> core_schema.CoreSchema: + """Apply validators to a schema. + + Args: + schema: The schema to apply validators on. + validators: An iterable of validators. + field_name: The name of the field if validators are being applied to a model field. + + Returns: + The updated schema. + """ + for validator in validators: + info_arg = inspect_validator(validator.func, validator.info.mode) + val_type = 'with-info' if info_arg else 'no-info' + + schema = _VALIDATOR_F_MATCH[(validator.info.mode, val_type)](validator.func, schema, field_name) + return schema + + +def _validators_require_validate_default(validators: Iterable[Decorator[ValidatorDecoratorInfo]]) -> bool: + """In v1, if any of the validators for a field had `always=True`, the default value would be validated. + + This serves as an auxiliary function for re-implementing that logic, by looping over a provided + collection of (v1-style) ValidatorDecoratorInfo's and checking if any of them have `always=True`. + + We should be able to drop this function and the associated logic calling it once we drop support + for v1-style validator decorators. (Or we can extend it and keep it if we add something equivalent + to the v1-validator `always` kwarg to `field_validator`.) + """ + for validator in validators: + if validator.info.always: + return True + return False + + +def apply_model_validators( + schema: core_schema.CoreSchema, + validators: Iterable[Decorator[ModelValidatorDecoratorInfo]], + mode: Literal['inner', 'outer', 'all'], +) -> core_schema.CoreSchema: + """Apply model validators to a schema. + + If mode == 'inner', only "before" validators are applied + If mode == 'outer', validators other than "before" are applied + If mode == 'all', all validators are applied + + Args: + schema: The schema to apply validators on. + validators: An iterable of validators. + mode: The validator mode. + + Returns: + The updated schema. + """ + ref: str | None = schema.pop('ref', None) # type: ignore + for validator in validators: + if mode == 'inner' and validator.info.mode != 'before': + continue + if mode == 'outer' and validator.info.mode == 'before': + continue + info_arg = inspect_validator(validator.func, validator.info.mode) + if validator.info.mode == 'wrap': + if info_arg: + schema = core_schema.with_info_wrap_validator_function(function=validator.func, schema=schema) + else: + schema = core_schema.no_info_wrap_validator_function(function=validator.func, schema=schema) + elif validator.info.mode == 'before': + if info_arg: + schema = core_schema.with_info_before_validator_function(function=validator.func, schema=schema) + else: + schema = core_schema.no_info_before_validator_function(function=validator.func, schema=schema) + else: + assert validator.info.mode == 'after' + if info_arg: + schema = core_schema.with_info_after_validator_function(function=validator.func, schema=schema) + else: + schema = core_schema.no_info_after_validator_function(function=validator.func, schema=schema) + if ref: + schema['ref'] = ref # type: ignore + return schema + + +def wrap_default(field_info: FieldInfo, schema: core_schema.CoreSchema) -> core_schema.CoreSchema: + """Wrap schema with default schema if default value or `default_factory` are available. + + Args: + field_info: The field info object. + schema: The schema to apply default on. + + Returns: + Updated schema by default value or `default_factory`. + """ + if field_info.default_factory: + return core_schema.with_default_schema( + schema, default_factory=field_info.default_factory, validate_default=field_info.validate_default + ) + elif field_info.default is not PydanticUndefined: + return core_schema.with_default_schema( + schema, default=field_info.default, validate_default=field_info.validate_default + ) + else: + return schema + + +def _extract_get_pydantic_json_schema(tp: Any, schema: CoreSchema) -> GetJsonSchemaFunction | None: + """Extract `__get_pydantic_json_schema__` from a type, handling the deprecated `__modify_schema__`.""" + js_modify_function = getattr(tp, '__get_pydantic_json_schema__', None) + + if hasattr(tp, '__modify_schema__'): + from pydantic import BaseModel # circular reference + + has_custom_v2_modify_js_func = ( + js_modify_function is not None + and BaseModel.__get_pydantic_json_schema__.__func__ # type: ignore + not in (js_modify_function, getattr(js_modify_function, '__func__', None)) + ) + + if not has_custom_v2_modify_js_func: + cls_name = getattr(tp, '__name__', None) + raise PydanticUserError( + f'The `__modify_schema__` method is not supported in Pydantic v2. ' + f'Use `__get_pydantic_json_schema__` instead{f" in class `{cls_name}`" if cls_name else ""}.', + code='custom-json-schema', + ) + + # handle GenericAlias' but ignore Annotated which "lies" about its origin (in this case it would be `int`) + if hasattr(tp, '__origin__') and not isinstance(tp, type(Annotated[int, 'placeholder'])): + return _extract_get_pydantic_json_schema(tp.__origin__, schema) + + if js_modify_function is None: + return None + + return js_modify_function + + +def get_json_schema_update_func( + json_schema_update: JsonSchemaValue, json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None +) -> GetJsonSchemaFunction: + def json_schema_update_func( + core_schema_or_field: CoreSchemaOrField, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + json_schema = {**handler(core_schema_or_field), **json_schema_update} + add_json_schema_extra(json_schema, json_schema_extra) + return json_schema + + return json_schema_update_func + + +def add_json_schema_extra( + json_schema: JsonSchemaValue, json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None +): + if isinstance(json_schema_extra, dict): + json_schema.update(to_jsonable_python(json_schema_extra)) + elif callable(json_schema_extra): + json_schema_extra(json_schema) + + +class _CommonField(TypedDict): + schema: core_schema.CoreSchema + validation_alias: str | list[str | int] | list[list[str | int]] | None + serialization_alias: str | None + serialization_exclude: bool | None + frozen: bool | None + metadata: dict[str, Any] + + +def _common_field( + schema: core_schema.CoreSchema, + *, + validation_alias: str | list[str | int] | list[list[str | int]] | None = None, + serialization_alias: str | None = None, + serialization_exclude: bool | None = None, + frozen: bool | None = None, + metadata: Any = None, +) -> _CommonField: + return { + 'schema': schema, + 'validation_alias': validation_alias, + 'serialization_alias': serialization_alias, + 'serialization_exclude': serialization_exclude, + 'frozen': frozen, + 'metadata': metadata, + } + + +class _Definitions: + """Keeps track of references and definitions.""" + + def __init__(self) -> None: + self.seen: set[str] = set() + self.definitions: dict[str, core_schema.CoreSchema] = {} + + @contextmanager + def get_schema_or_ref(self, tp: Any) -> Iterator[tuple[str, None] | tuple[str, CoreSchema]]: + """Get a definition for `tp` if one exists. + + If a definition exists, a tuple of `(ref_string, CoreSchema)` is returned. + If no definition exists yet, a tuple of `(ref_string, None)` is returned. + + Note that the returned `CoreSchema` will always be a `DefinitionReferenceSchema`, + not the actual definition itself. + + This should be called for any type that can be identified by reference. + This includes any recursive types. + + At present the following types can be named/recursive: + + - BaseModel + - Dataclasses + - TypedDict + - TypeAliasType + """ + ref = get_type_ref(tp) + # return the reference if we're either (1) in a cycle or (2) it was already defined + if ref in self.seen or ref in self.definitions: + yield (ref, core_schema.definition_reference_schema(ref)) + else: + self.seen.add(ref) + try: + yield (ref, None) + finally: + self.seen.discard(ref) + + +def resolve_original_schema(schema: CoreSchema, definitions: dict[str, CoreSchema]) -> CoreSchema | None: + if schema['type'] == 'definition-ref': + return definitions.get(schema['schema_ref'], None) + elif schema['type'] == 'definitions': + return schema['schema'] + else: + return schema + + +class _FieldNameStack: + __slots__ = ('_stack',) + + def __init__(self) -> None: + self._stack: list[str] = [] + + @contextmanager + def push(self, field_name: str) -> Iterator[None]: + self._stack.append(field_name) + yield + self._stack.pop() + + def get(self) -> str | None: + if self._stack: + return self._stack[-1] + else: + return None + + +class _ModelTypeStack: + __slots__ = ('_stack',) + + def __init__(self) -> None: + self._stack: list[type] = [] + + @contextmanager + def push(self, type_obj: type) -> Iterator[None]: + self._stack.append(type_obj) + yield + self._stack.pop() + + def get(self) -> type | None: + if self._stack: + return self._stack[-1] + else: + return None diff --git a/env/Lib/site-packages/pydantic/_internal/_generics.py b/env/Lib/site-packages/pydantic/_internal/_generics.py new file mode 100644 index 0000000..0bd106b --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_generics.py @@ -0,0 +1,516 @@ +from __future__ import annotations + +import sys +import types +import typing +from collections import ChainMap +from contextlib import contextmanager +from contextvars import ContextVar +from types import prepare_class +from typing import TYPE_CHECKING, Any, Iterator, List, Mapping, MutableMapping, Tuple, TypeVar +from weakref import WeakValueDictionary + +import typing_extensions + +from ._core_utils import get_type_ref +from ._forward_ref import PydanticRecursiveRef +from ._typing_extra import TypeVarType, typing_base +from ._utils import all_identical, is_model_class + +if sys.version_info >= (3, 10): + from typing import _UnionGenericAlias # type: ignore[attr-defined] + +if TYPE_CHECKING: + from ..main import BaseModel + +GenericTypesCacheKey = Tuple[Any, Any, Tuple[Any, ...]] + +# Note: We want to remove LimitedDict, but to do this, we'd need to improve the handling of generics caching. +# Right now, to handle recursive generics, we some types must remain cached for brief periods without references. +# By chaining the WeakValuesDict with a LimitedDict, we have a way to retain caching for all types with references, +# while also retaining a limited number of types even without references. This is generally enough to build +# specific recursive generic models without losing required items out of the cache. + +KT = TypeVar('KT') +VT = TypeVar('VT') +_LIMITED_DICT_SIZE = 100 +if TYPE_CHECKING: + + class LimitedDict(dict, MutableMapping[KT, VT]): + def __init__(self, size_limit: int = _LIMITED_DICT_SIZE): ... + +else: + + class LimitedDict(dict): + """Limit the size/length of a dict used for caching to avoid unlimited increase in memory usage. + + Since the dict is ordered, and we always remove elements from the beginning, this is effectively a FIFO cache. + """ + + def __init__(self, size_limit: int = _LIMITED_DICT_SIZE): + self.size_limit = size_limit + super().__init__() + + def __setitem__(self, key: Any, value: Any, /) -> None: + super().__setitem__(key, value) + if len(self) > self.size_limit: + excess = len(self) - self.size_limit + self.size_limit // 10 + to_remove = list(self.keys())[:excess] + for k in to_remove: + del self[k] + + +# weak dictionaries allow the dynamically created parametrized versions of generic models to get collected +# once they are no longer referenced by the caller. +if sys.version_info >= (3, 9): # Typing for weak dictionaries available at 3.9 + GenericTypesCache = WeakValueDictionary[GenericTypesCacheKey, 'type[BaseModel]'] +else: + GenericTypesCache = WeakValueDictionary + +if TYPE_CHECKING: + + class DeepChainMap(ChainMap[KT, VT]): # type: ignore + ... + +else: + + class DeepChainMap(ChainMap): + """Variant of ChainMap that allows direct updates to inner scopes. + + Taken from https://docs.python.org/3/library/collections.html#collections.ChainMap, + with some light modifications for this use case. + """ + + def clear(self) -> None: + for mapping in self.maps: + mapping.clear() + + def __setitem__(self, key: KT, value: VT) -> None: + for mapping in self.maps: + mapping[key] = value + + def __delitem__(self, key: KT) -> None: + hit = False + for mapping in self.maps: + if key in mapping: + del mapping[key] + hit = True + if not hit: + raise KeyError(key) + + +# Despite the fact that LimitedDict _seems_ no longer necessary, I'm very nervous to actually remove it +# and discover later on that we need to re-add all this infrastructure... +# _GENERIC_TYPES_CACHE = DeepChainMap(GenericTypesCache(), LimitedDict()) + +_GENERIC_TYPES_CACHE = GenericTypesCache() + + +class PydanticGenericMetadata(typing_extensions.TypedDict): + origin: type[BaseModel] | None # analogous to typing._GenericAlias.__origin__ + args: tuple[Any, ...] # analogous to typing._GenericAlias.__args__ + parameters: tuple[type[Any], ...] # analogous to typing.Generic.__parameters__ + + +def create_generic_submodel( + model_name: str, origin: type[BaseModel], args: tuple[Any, ...], params: tuple[Any, ...] +) -> type[BaseModel]: + """Dynamically create a submodel of a provided (generic) BaseModel. + + This is used when producing concrete parametrizations of generic models. This function + only *creates* the new subclass; the schema/validators/serialization must be updated to + reflect a concrete parametrization elsewhere. + + Args: + model_name: The name of the newly created model. + origin: The base class for the new model to inherit from. + args: A tuple of generic metadata arguments. + params: A tuple of generic metadata parameters. + + Returns: + The created submodel. + """ + namespace: dict[str, Any] = {'__module__': origin.__module__} + bases = (origin,) + meta, ns, kwds = prepare_class(model_name, bases) + namespace.update(ns) + created_model = meta( + model_name, + bases, + namespace, + __pydantic_generic_metadata__={ + 'origin': origin, + 'args': args, + 'parameters': params, + }, + __pydantic_reset_parent_namespace__=False, + **kwds, + ) + + model_module, called_globally = _get_caller_frame_info(depth=3) + if called_globally: # create global reference and therefore allow pickling + object_by_reference = None + reference_name = model_name + reference_module_globals = sys.modules[created_model.__module__].__dict__ + while object_by_reference is not created_model: + object_by_reference = reference_module_globals.setdefault(reference_name, created_model) + reference_name += '_' + + return created_model + + +def _get_caller_frame_info(depth: int = 2) -> tuple[str | None, bool]: + """Used inside a function to check whether it was called globally. + + Args: + depth: The depth to get the frame. + + Returns: + A tuple contains `module_name` and `called_globally`. + + Raises: + RuntimeError: If the function is not called inside a function. + """ + try: + previous_caller_frame = sys._getframe(depth) + except ValueError as e: + raise RuntimeError('This function must be used inside another function') from e + except AttributeError: # sys module does not have _getframe function, so there's nothing we can do about it + return None, False + frame_globals = previous_caller_frame.f_globals + return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals + + +DictValues: type[Any] = {}.values().__class__ + + +def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]: + """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found. + + This is inspired as an alternative to directly accessing the `__parameters__` attribute of a GenericAlias, + since __parameters__ of (nested) generic BaseModel subclasses won't show up in that list. + """ + if isinstance(v, TypeVar): + yield v + elif is_model_class(v): + yield from v.__pydantic_generic_metadata__['parameters'] + elif isinstance(v, (DictValues, list)): + for var in v: + yield from iter_contained_typevars(var) + else: + args = get_args(v) + for arg in args: + yield from iter_contained_typevars(arg) + + +def get_args(v: Any) -> Any: + pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None) + if pydantic_generic_metadata: + return pydantic_generic_metadata.get('args') + return typing_extensions.get_args(v) + + +def get_origin(v: Any) -> Any: + pydantic_generic_metadata: PydanticGenericMetadata | None = getattr(v, '__pydantic_generic_metadata__', None) + if pydantic_generic_metadata: + return pydantic_generic_metadata.get('origin') + return typing_extensions.get_origin(v) + + +def get_standard_typevars_map(cls: type[Any]) -> dict[TypeVarType, Any] | None: + """Package a generic type's typevars and parametrization (if present) into a dictionary compatible with the + `replace_types` function. Specifically, this works with standard typing generics and typing._GenericAlias. + """ + origin = get_origin(cls) + if origin is None: + return None + if not hasattr(origin, '__parameters__'): + return None + + # In this case, we know that cls is a _GenericAlias, and origin is the generic type + # So it is safe to access cls.__args__ and origin.__parameters__ + args: tuple[Any, ...] = cls.__args__ # type: ignore + parameters: tuple[TypeVarType, ...] = origin.__parameters__ + return dict(zip(parameters, args)) + + +def get_model_typevars_map(cls: type[BaseModel]) -> dict[TypeVarType, Any] | None: + """Package a generic BaseModel's typevars and concrete parametrization (if present) into a dictionary compatible + with the `replace_types` function. + + Since BaseModel.__class_getitem__ does not produce a typing._GenericAlias, and the BaseModel generic info is + stored in the __pydantic_generic_metadata__ attribute, we need special handling here. + """ + # TODO: This could be unified with `get_standard_typevars_map` if we stored the generic metadata + # in the __origin__, __args__, and __parameters__ attributes of the model. + generic_metadata = cls.__pydantic_generic_metadata__ + origin = generic_metadata['origin'] + args = generic_metadata['args'] + return dict(zip(iter_contained_typevars(origin), args)) + + +def replace_types(type_: Any, type_map: Mapping[Any, Any] | None) -> Any: + """Return type with all occurrences of `type_map` keys recursively replaced with their values. + + Args: + type_: The class or generic alias. + type_map: Mapping from `TypeVar` instance to concrete types. + + Returns: + A new type representing the basic structure of `type_` with all + `typevar_map` keys recursively replaced. + + Example: + ```py + from typing import List, Tuple, Union + + from pydantic._internal._generics import replace_types + + replace_types(Tuple[str, Union[List[str], float]], {str: int}) + #> Tuple[int, Union[List[int], float]] + ``` + """ + if not type_map: + return type_ + + type_args = get_args(type_) + origin_type = get_origin(type_) + + if origin_type is typing_extensions.Annotated: + annotated_type, *annotations = type_args + annotated = replace_types(annotated_type, type_map) + for annotation in annotations: + annotated = typing_extensions.Annotated[annotated, annotation] + return annotated + + # Having type args is a good indicator that this is a typing module + # class instantiation or a generic alias of some sort. + if type_args: + resolved_type_args = tuple(replace_types(arg, type_map) for arg in type_args) + if all_identical(type_args, resolved_type_args): + # If all arguments are the same, there is no need to modify the + # type or create a new object at all + return type_ + if ( + origin_type is not None + and isinstance(type_, typing_base) + and not isinstance(origin_type, typing_base) + and getattr(type_, '_name', None) is not None + ): + # In python < 3.9 generic aliases don't exist so any of these like `list`, + # `type` or `collections.abc.Callable` need to be translated. + # See: https://www.python.org/dev/peps/pep-0585 + origin_type = getattr(typing, type_._name) + assert origin_type is not None + # PEP-604 syntax (Ex.: list | str) is represented with a types.UnionType object that does not have __getitem__. + # We also cannot use isinstance() since we have to compare types. + if sys.version_info >= (3, 10) and origin_type is types.UnionType: + return _UnionGenericAlias(origin_type, resolved_type_args) + # NotRequired[T] and Required[T] don't support tuple type resolved_type_args, hence the condition below + return origin_type[resolved_type_args[0] if len(resolved_type_args) == 1 else resolved_type_args] + + # We handle pydantic generic models separately as they don't have the same + # semantics as "typing" classes or generic aliases + + if not origin_type and is_model_class(type_): + parameters = type_.__pydantic_generic_metadata__['parameters'] + if not parameters: + return type_ + resolved_type_args = tuple(replace_types(t, type_map) for t in parameters) + if all_identical(parameters, resolved_type_args): + return type_ + return type_[resolved_type_args] + + # Handle special case for typehints that can have lists as arguments. + # `typing.Callable[[int, str], int]` is an example for this. + if isinstance(type_, (List, list)): + resolved_list = list(replace_types(element, type_map) for element in type_) + if all_identical(type_, resolved_list): + return type_ + return resolved_list + + # If all else fails, we try to resolve the type directly and otherwise just + # return the input with no modifications. + return type_map.get(type_, type_) + + +def has_instance_in_type(type_: Any, isinstance_target: Any) -> bool: + """Checks if the type, or any of its arbitrary nested args, satisfy + `isinstance(, isinstance_target)`. + """ + if isinstance(type_, isinstance_target): + return True + + type_args = get_args(type_) + origin_type = get_origin(type_) + + if origin_type is typing_extensions.Annotated: + annotated_type, *annotations = type_args + return has_instance_in_type(annotated_type, isinstance_target) + + # Having type args is a good indicator that this is a typing module + # class instantiation or a generic alias of some sort. + if any(has_instance_in_type(a, isinstance_target) for a in type_args): + return True + + # Handle special case for typehints that can have lists as arguments. + # `typing.Callable[[int, str], int]` is an example for this. + if isinstance(type_, (List, list)) and not isinstance(type_, typing_extensions.ParamSpec): + if any(has_instance_in_type(element, isinstance_target) for element in type_): + return True + + return False + + +def check_parameters_count(cls: type[BaseModel], parameters: tuple[Any, ...]) -> None: + """Check the generic model parameters count is equal. + + Args: + cls: The generic model. + parameters: A tuple of passed parameters to the generic model. + + Raises: + TypeError: If the passed parameters count is not equal to generic model parameters count. + """ + actual = len(parameters) + expected = len(cls.__pydantic_generic_metadata__['parameters']) + if actual != expected: + description = 'many' if actual > expected else 'few' + raise TypeError(f'Too {description} parameters for {cls}; actual {actual}, expected {expected}') + + +_generic_recursion_cache: ContextVar[set[str] | None] = ContextVar('_generic_recursion_cache', default=None) + + +@contextmanager +def generic_recursion_self_type( + origin: type[BaseModel], args: tuple[Any, ...] +) -> Iterator[PydanticRecursiveRef | None]: + """This contextmanager should be placed around the recursive calls used to build a generic type, + and accept as arguments the generic origin type and the type arguments being passed to it. + + If the same origin and arguments are observed twice, it implies that a self-reference placeholder + can be used while building the core schema, and will produce a schema_ref that will be valid in the + final parent schema. + """ + previously_seen_type_refs = _generic_recursion_cache.get() + if previously_seen_type_refs is None: + previously_seen_type_refs = set() + token = _generic_recursion_cache.set(previously_seen_type_refs) + else: + token = None + + try: + type_ref = get_type_ref(origin, args_override=args) + if type_ref in previously_seen_type_refs: + self_type = PydanticRecursiveRef(type_ref=type_ref) + yield self_type + else: + previously_seen_type_refs.add(type_ref) + yield None + finally: + if token: + _generic_recursion_cache.reset(token) + + +def recursively_defined_type_refs() -> set[str]: + visited = _generic_recursion_cache.get() + if not visited: + return set() # not in a generic recursion, so there are no types + + return visited.copy() # don't allow modifications + + +def get_cached_generic_type_early(parent: type[BaseModel], typevar_values: Any) -> type[BaseModel] | None: + """The use of a two-stage cache lookup approach was necessary to have the highest performance possible for + repeated calls to `__class_getitem__` on generic types (which may happen in tighter loops during runtime), + while still ensuring that certain alternative parametrizations ultimately resolve to the same type. + + As a concrete example, this approach was necessary to make Model[List[T]][int] equal to Model[List[int]]. + The approach could be modified to not use two different cache keys at different points, but the + _early_cache_key is optimized to be as quick to compute as possible (for repeated-access speed), and the + _late_cache_key is optimized to be as "correct" as possible, so that two types that will ultimately be the + same after resolving the type arguments will always produce cache hits. + + If we wanted to move to only using a single cache key per type, we would either need to always use the + slower/more computationally intensive logic associated with _late_cache_key, or would need to accept + that Model[List[T]][int] is a different type than Model[List[T]][int]. Because we rely on subclass relationships + during validation, I think it is worthwhile to ensure that types that are functionally equivalent are actually + equal. + """ + return _GENERIC_TYPES_CACHE.get(_early_cache_key(parent, typevar_values)) + + +def get_cached_generic_type_late( + parent: type[BaseModel], typevar_values: Any, origin: type[BaseModel], args: tuple[Any, ...] +) -> type[BaseModel] | None: + """See the docstring of `get_cached_generic_type_early` for more information about the two-stage cache lookup.""" + cached = _GENERIC_TYPES_CACHE.get(_late_cache_key(origin, args, typevar_values)) + if cached is not None: + set_cached_generic_type(parent, typevar_values, cached, origin, args) + return cached + + +def set_cached_generic_type( + parent: type[BaseModel], + typevar_values: tuple[Any, ...], + type_: type[BaseModel], + origin: type[BaseModel] | None = None, + args: tuple[Any, ...] | None = None, +) -> None: + """See the docstring of `get_cached_generic_type_early` for more information about why items are cached with + two different keys. + """ + _GENERIC_TYPES_CACHE[_early_cache_key(parent, typevar_values)] = type_ + if len(typevar_values) == 1: + _GENERIC_TYPES_CACHE[_early_cache_key(parent, typevar_values[0])] = type_ + if origin and args: + _GENERIC_TYPES_CACHE[_late_cache_key(origin, args, typevar_values)] = type_ + + +def _union_orderings_key(typevar_values: Any) -> Any: + """This is intended to help differentiate between Union types with the same arguments in different order. + + Thanks to caching internal to the `typing` module, it is not possible to distinguish between + List[Union[int, float]] and List[Union[float, int]] (and similarly for other "parent" origins besides List) + because `typing` considers Union[int, float] to be equal to Union[float, int]. + + However, you _can_ distinguish between (top-level) Union[int, float] vs. Union[float, int]. + Because we parse items as the first Union type that is successful, we get slightly more consistent behavior + if we make an effort to distinguish the ordering of items in a union. It would be best if we could _always_ + get the exact-correct order of items in the union, but that would require a change to the `typing` module itself. + (See https://github.com/python/cpython/issues/86483 for reference.) + """ + if isinstance(typevar_values, tuple): + args_data = [] + for value in typevar_values: + args_data.append(_union_orderings_key(value)) + return tuple(args_data) + elif typing_extensions.get_origin(typevar_values) is typing.Union: + return get_args(typevar_values) + else: + return () + + +def _early_cache_key(cls: type[BaseModel], typevar_values: Any) -> GenericTypesCacheKey: + """This is intended for minimal computational overhead during lookups of cached types. + + Note that this is overly simplistic, and it's possible that two different cls/typevar_values + inputs would ultimately result in the same type being created in BaseModel.__class_getitem__. + To handle this, we have a fallback _late_cache_key that is checked later if the _early_cache_key + lookup fails, and should result in a cache hit _precisely_ when the inputs to __class_getitem__ + would result in the same type. + """ + return cls, typevar_values, _union_orderings_key(typevar_values) + + +def _late_cache_key(origin: type[BaseModel], args: tuple[Any, ...], typevar_values: Any) -> GenericTypesCacheKey: + """This is intended for use later in the process of creating a new type, when we have more information + about the exact args that will be passed. If it turns out that a different set of inputs to + __class_getitem__ resulted in the same inputs to the generic type creation process, we can still + return the cached type, and update the cache with the _early_cache_key as well. + """ + # The _union_orderings_key is placed at the start here to ensure there cannot be a collision with an + # _early_cache_key, as that function will always produce a BaseModel subclass as the first item in the key, + # whereas this function will always produce a tuple as the first item in the key. + return _union_orderings_key(typevar_values), origin, args diff --git a/env/Lib/site-packages/pydantic/_internal/_git.py b/env/Lib/site-packages/pydantic/_internal/_git.py new file mode 100644 index 0000000..bff0dca --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_git.py @@ -0,0 +1,27 @@ +"""Git utilities, adopted from mypy's git utilities (https://github.com/python/mypy/blob/master/mypy/git.py).""" + +from __future__ import annotations + +import os +import subprocess + + +def is_git_repo(dir: str) -> bool: + """Is the given directory version-controlled with git?""" + return os.path.exists(os.path.join(dir, '.git')) + + +def have_git() -> bool: + """Can we run the git executable?""" + try: + subprocess.check_output(['git', '--help']) + return True + except subprocess.CalledProcessError: + return False + except OSError: + return False + + +def git_revision(dir: str) -> str: + """Get the SHA-1 of the HEAD of a git repository.""" + return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=dir).decode('utf-8').strip() diff --git a/env/Lib/site-packages/pydantic/_internal/_internal_dataclass.py b/env/Lib/site-packages/pydantic/_internal/_internal_dataclass.py new file mode 100644 index 0000000..33e152c --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_internal_dataclass.py @@ -0,0 +1,7 @@ +import sys + +# `slots` is available on Python >= 3.10 +if sys.version_info >= (3, 10): + slots_true = {'slots': True} +else: + slots_true = {} diff --git a/env/Lib/site-packages/pydantic/_internal/_known_annotated_metadata.py b/env/Lib/site-packages/pydantic/_internal/_known_annotated_metadata.py new file mode 100644 index 0000000..971ab68 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_known_annotated_metadata.py @@ -0,0 +1,359 @@ +from __future__ import annotations + +from collections import defaultdict +from copy import copy +from functools import lru_cache, partial +from typing import TYPE_CHECKING, Any, Callable, Iterable + +from pydantic_core import CoreSchema, PydanticCustomError, to_jsonable_python +from pydantic_core import core_schema as cs + +from ._fields import PydanticMetadata + +if TYPE_CHECKING: + from ..annotated_handlers import GetJsonSchemaHandler + +STRICT = {'strict'} +FAIL_FAST = {'fail_fast'} +LENGTH_CONSTRAINTS = {'min_length', 'max_length'} +INEQUALITY = {'le', 'ge', 'lt', 'gt'} +NUMERIC_CONSTRAINTS = {'multiple_of', *INEQUALITY} +ALLOW_INF_NAN = {'allow_inf_nan'} + +STR_CONSTRAINTS = { + *LENGTH_CONSTRAINTS, + *STRICT, + 'strip_whitespace', + 'to_lower', + 'to_upper', + 'pattern', + 'coerce_numbers_to_str', +} +BYTES_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT} + +LIST_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST} +TUPLE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST} +SET_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT, *FAIL_FAST} +DICT_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT} +GENERATOR_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *STRICT} +SEQUENCE_CONSTRAINTS = {*LENGTH_CONSTRAINTS, *FAIL_FAST} + +FLOAT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT} +DECIMAL_CONSTRAINTS = {'max_digits', 'decimal_places', *FLOAT_CONSTRAINTS} +INT_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *ALLOW_INF_NAN, *STRICT} +BOOL_CONSTRAINTS = STRICT +UUID_CONSTRAINTS = STRICT + +DATE_TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} +TIMEDELTA_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} +TIME_CONSTRAINTS = {*NUMERIC_CONSTRAINTS, *STRICT} +LAX_OR_STRICT_CONSTRAINTS = STRICT +ENUM_CONSTRAINTS = STRICT + +UNION_CONSTRAINTS = {'union_mode'} +URL_CONSTRAINTS = { + 'max_length', + 'allowed_schemes', + 'host_required', + 'default_host', + 'default_port', + 'default_path', +} + +TEXT_SCHEMA_TYPES = ('str', 'bytes', 'url', 'multi-host-url') +SEQUENCE_SCHEMA_TYPES = ('list', 'tuple', 'set', 'frozenset', 'generator', *TEXT_SCHEMA_TYPES) +NUMERIC_SCHEMA_TYPES = ('float', 'int', 'date', 'time', 'timedelta', 'datetime') + +CONSTRAINTS_TO_ALLOWED_SCHEMAS: dict[str, set[str]] = defaultdict(set) + +constraint_schema_pairings: list[tuple[set[str], tuple[str, ...]]] = [ + (STR_CONSTRAINTS, TEXT_SCHEMA_TYPES), + (BYTES_CONSTRAINTS, ('bytes',)), + (LIST_CONSTRAINTS, ('list',)), + (TUPLE_CONSTRAINTS, ('tuple',)), + (SET_CONSTRAINTS, ('set', 'frozenset')), + (DICT_CONSTRAINTS, ('dict',)), + (GENERATOR_CONSTRAINTS, ('generator',)), + (FLOAT_CONSTRAINTS, ('float',)), + (INT_CONSTRAINTS, ('int',)), + (DATE_TIME_CONSTRAINTS, ('date', 'time', 'datetime')), + (TIMEDELTA_CONSTRAINTS, ('timedelta',)), + (TIME_CONSTRAINTS, ('time',)), + # TODO: this is a bit redundant, we could probably avoid some of these + (STRICT, (*TEXT_SCHEMA_TYPES, *SEQUENCE_SCHEMA_TYPES, *NUMERIC_SCHEMA_TYPES, 'typed-dict', 'model')), + (UNION_CONSTRAINTS, ('union',)), + (URL_CONSTRAINTS, ('url', 'multi-host-url')), + (BOOL_CONSTRAINTS, ('bool',)), + (UUID_CONSTRAINTS, ('uuid',)), + (LAX_OR_STRICT_CONSTRAINTS, ('lax-or-strict',)), + (ENUM_CONSTRAINTS, ('enum',)), + (DECIMAL_CONSTRAINTS, ('decimal',)), +] + +for constraints, schemas in constraint_schema_pairings: + for c in constraints: + CONSTRAINTS_TO_ALLOWED_SCHEMAS[c].update(schemas) + + +def add_js_update_schema(s: cs.CoreSchema, f: Callable[[], dict[str, Any]]) -> None: + def update_js_schema(s: cs.CoreSchema, handler: GetJsonSchemaHandler) -> dict[str, Any]: + js_schema = handler(s) + js_schema.update(f()) + return js_schema + + if 'metadata' in s: + metadata = s['metadata'] + if 'pydantic_js_functions' in s: + metadata['pydantic_js_functions'].append(update_js_schema) + else: + metadata['pydantic_js_functions'] = [update_js_schema] + else: + s['metadata'] = {'pydantic_js_functions': [update_js_schema]} + + +def as_jsonable_value(v: Any) -> Any: + if type(v) not in (int, str, float, bytes, bool, type(None)): + return to_jsonable_python(v) + return v + + +def expand_grouped_metadata(annotations: Iterable[Any]) -> Iterable[Any]: + """Expand the annotations. + + Args: + annotations: An iterable of annotations. + + Returns: + An iterable of expanded annotations. + + Example: + ```py + from annotated_types import Ge, Len + + from pydantic._internal._known_annotated_metadata import expand_grouped_metadata + + print(list(expand_grouped_metadata([Ge(4), Len(5)]))) + #> [Ge(ge=4), MinLen(min_length=5)] + ``` + """ + import annotated_types as at + + from pydantic.fields import FieldInfo # circular import + + for annotation in annotations: + if isinstance(annotation, at.GroupedMetadata): + yield from annotation + elif isinstance(annotation, FieldInfo): + yield from annotation.metadata + # this is a bit problematic in that it results in duplicate metadata + # all of our "consumers" can handle it, but it is not ideal + # we probably should split up FieldInfo into: + # - annotated types metadata + # - individual metadata known only to Pydantic + annotation = copy(annotation) + annotation.metadata = [] + yield annotation + else: + yield annotation + + +@lru_cache +def _get_at_to_constraint_map() -> dict[type, str]: + """Return a mapping of annotated types to constraints. + + Normally, we would define a mapping like this in the module scope, but we can't do that + because we don't permit module level imports of `annotated_types`, in an attempt to speed up + the import time of `pydantic`. We still only want to have this dictionary defined in one place, + so we use this function to cache the result. + """ + import annotated_types as at + + return { + at.Gt: 'gt', + at.Ge: 'ge', + at.Lt: 'lt', + at.Le: 'le', + at.MultipleOf: 'multiple_of', + at.MinLen: 'min_length', + at.MaxLen: 'max_length', + } + + +def apply_known_metadata(annotation: Any, schema: CoreSchema) -> CoreSchema | None: # noqa: C901 + """Apply `annotation` to `schema` if it is an annotation we know about (Gt, Le, etc.). + Otherwise return `None`. + + This does not handle all known annotations. If / when it does, it can always + return a CoreSchema and return the unmodified schema if the annotation should be ignored. + + Assumes that GroupedMetadata has already been expanded via `expand_grouped_metadata`. + + Args: + annotation: The annotation. + schema: The schema. + + Returns: + An updated schema with annotation if it is an annotation we know about, `None` otherwise. + + Raises: + PydanticCustomError: If `Predicate` fails. + """ + import annotated_types as at + + from ._validators import forbid_inf_nan_check, get_constraint_validator + + schema = schema.copy() + schema_update, other_metadata = collect_known_metadata([annotation]) + schema_type = schema['type'] + + chain_schema_constraints: set[str] = { + 'pattern', + 'strip_whitespace', + 'to_lower', + 'to_upper', + 'coerce_numbers_to_str', + } + chain_schema_steps: list[CoreSchema] = [] + + for constraint, value in schema_update.items(): + if constraint not in CONSTRAINTS_TO_ALLOWED_SCHEMAS: + raise ValueError(f'Unknown constraint {constraint}') + allowed_schemas = CONSTRAINTS_TO_ALLOWED_SCHEMAS[constraint] + + # if it becomes necessary to handle more than one constraint + # in this recursive case with function-after or function-wrap, we should refactor + # this is a bit challenging because we sometimes want to apply constraints to the inner schema, + # whereas other times we want to wrap the existing schema with a new one that enforces a new constraint. + if schema_type in {'function-before', 'function-wrap', 'function-after'} and constraint == 'strict': + schema['schema'] = apply_known_metadata(annotation, schema['schema']) # type: ignore # schema is function-after schema + return schema + + if schema_type in allowed_schemas: + if constraint == 'union_mode' and schema_type == 'union': + schema['mode'] = value # type: ignore # schema is UnionSchema + else: + schema[constraint] = value + continue + + if constraint in chain_schema_constraints: + chain_schema_steps.append(cs.str_schema(**{constraint: value})) + elif constraint in {*NUMERIC_CONSTRAINTS, *LENGTH_CONSTRAINTS}: + if constraint in NUMERIC_CONSTRAINTS: + json_schema_constraint = constraint + elif constraint in LENGTH_CONSTRAINTS: + inner_schema = schema + while inner_schema['type'] in {'function-before', 'function-wrap', 'function-after'}: + inner_schema = inner_schema['schema'] # type: ignore + inner_schema_type = inner_schema['type'] + if inner_schema_type == 'list' or ( + inner_schema_type == 'json-or-python' and inner_schema['json_schema']['type'] == 'list' # type: ignore + ): + json_schema_constraint = 'minItems' if constraint == 'min_length' else 'maxItems' + else: + json_schema_constraint = 'minLength' if constraint == 'min_length' else 'maxLength' + + schema = cs.no_info_after_validator_function( + partial(get_constraint_validator(constraint), **{constraint: value}), schema + ) + add_js_update_schema(schema, lambda: {json_schema_constraint: as_jsonable_value(value)}) + elif constraint == 'allow_inf_nan' and value is False: + schema = cs.no_info_after_validator_function( + forbid_inf_nan_check, + schema, + ) + else: + raise RuntimeError(f'Unable to apply constraint {constraint} to schema {schema_type}') + + for annotation in other_metadata: + if (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()): + constraint = at_to_constraint_map[annotation_type] + schema = cs.no_info_after_validator_function( + partial(get_constraint_validator(constraint), {constraint: getattr(annotation, constraint)}), schema + ) + continue + elif isinstance(annotation, at.Predicate): + predicate_name = f'{annotation.func.__qualname__} ' if hasattr(annotation.func, '__qualname__') else '' + + def val_func(v: Any) -> Any: + # annotation.func may also raise an exception, let it pass through + if not annotation.func(v): + raise PydanticCustomError( + 'predicate_failed', + f'Predicate {predicate_name}failed', # type: ignore + ) + return v + + schema = cs.no_info_after_validator_function(val_func, schema) + else: + # ignore any other unknown metadata + return None + + if chain_schema_steps: + chain_schema_steps = [schema] + chain_schema_steps + return cs.chain_schema(chain_schema_steps) + + return schema + + +def collect_known_metadata(annotations: Iterable[Any]) -> tuple[dict[str, Any], list[Any]]: + """Split `annotations` into known metadata and unknown annotations. + + Args: + annotations: An iterable of annotations. + + Returns: + A tuple contains a dict of known metadata and a list of unknown annotations. + + Example: + ```py + from annotated_types import Gt, Len + + from pydantic._internal._known_annotated_metadata import collect_known_metadata + + print(collect_known_metadata([Gt(1), Len(42), ...])) + #> ({'gt': 1, 'min_length': 42}, [Ellipsis]) + ``` + """ + annotations = expand_grouped_metadata(annotations) + + res: dict[str, Any] = {} + remaining: list[Any] = [] + + for annotation in annotations: + # isinstance(annotation, PydanticMetadata) also covers ._fields:_PydanticGeneralMetadata + if isinstance(annotation, PydanticMetadata): + res.update(annotation.__dict__) + # we don't use dataclasses.asdict because that recursively calls asdict on the field values + elif (annotation_type := type(annotation)) in (at_to_constraint_map := _get_at_to_constraint_map()): + constraint = at_to_constraint_map[annotation_type] + res[constraint] = getattr(annotation, constraint) + elif isinstance(annotation, type) and issubclass(annotation, PydanticMetadata): + # also support PydanticMetadata classes being used without initialisation, + # e.g. `Annotated[int, Strict]` as well as `Annotated[int, Strict()]` + res.update({k: v for k, v in vars(annotation).items() if not k.startswith('_')}) + else: + remaining.append(annotation) + # Nones can sneak in but pydantic-core will reject them + # it'd be nice to clean things up so we don't put in None (we probably don't _need_ to, it was just easier) + # but this is simple enough to kick that can down the road + res = {k: v for k, v in res.items() if v is not None} + return res, remaining + + +def check_metadata(metadata: dict[str, Any], allowed: Iterable[str], source_type: Any) -> None: + """A small utility function to validate that the given metadata can be applied to the target. + More than saving lines of code, this gives us a consistent error message for all of our internal implementations. + + Args: + metadata: A dict of metadata. + allowed: An iterable of allowed metadata. + source_type: The source type. + + Raises: + TypeError: If there is metadatas that can't be applied on source type. + """ + unknown = metadata.keys() - set(allowed) + if unknown: + raise TypeError( + f'The following constraints cannot be applied to {source_type!r}: {", ".join([f"{k!r}" for k in unknown])}' + ) diff --git a/env/Lib/site-packages/pydantic/_internal/_mock_val_ser.py b/env/Lib/site-packages/pydantic/_internal/_mock_val_ser.py new file mode 100644 index 0000000..3e55af7 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_mock_val_ser.py @@ -0,0 +1,194 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable, Generic, Iterator, Mapping, TypeVar, Union + +from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator +from typing_extensions import Literal + +from ..errors import PydanticErrorCodes, PydanticUserError +from ..plugin._schema_validator import PluggableSchemaValidator + +if TYPE_CHECKING: + from ..dataclasses import PydanticDataclass + from ..main import BaseModel + + +ValSer = TypeVar('ValSer', bound=Union[SchemaValidator, PluggableSchemaValidator, SchemaSerializer]) +T = TypeVar('T') + + +class MockCoreSchema(Mapping[str, Any]): + """Mocker for `pydantic_core.CoreSchema` which optionally attempts to + rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails. + """ + + __slots__ = '_error_message', '_code', '_attempt_rebuild', '_built_memo' + + def __init__( + self, + error_message: str, + *, + code: PydanticErrorCodes, + attempt_rebuild: Callable[[], CoreSchema | None] | None = None, + ) -> None: + self._error_message = error_message + self._code: PydanticErrorCodes = code + self._attempt_rebuild = attempt_rebuild + self._built_memo: CoreSchema | None = None + + def __getitem__(self, key: str) -> Any: + return self._get_built().__getitem__(key) + + def __len__(self) -> int: + return self._get_built().__len__() + + def __iter__(self) -> Iterator[str]: + return self._get_built().__iter__() + + def _get_built(self) -> CoreSchema: + if self._built_memo is not None: + return self._built_memo + + if self._attempt_rebuild: + schema = self._attempt_rebuild() + if schema is not None: + self._built_memo = schema + return schema + raise PydanticUserError(self._error_message, code=self._code) + + def rebuild(self) -> CoreSchema | None: + self._built_memo = None + if self._attempt_rebuild: + val_ser = self._attempt_rebuild() + if val_ser is not None: + return val_ser + else: + raise PydanticUserError(self._error_message, code=self._code) + return None + + +class MockValSer(Generic[ValSer]): + """Mocker for `pydantic_core.SchemaValidator` or `pydantic_core.SchemaSerializer` which optionally attempts to + rebuild the thing it's mocking when one of its methods is accessed and raises an error if that fails. + """ + + __slots__ = '_error_message', '_code', '_val_or_ser', '_attempt_rebuild' + + def __init__( + self, + error_message: str, + *, + code: PydanticErrorCodes, + val_or_ser: Literal['validator', 'serializer'], + attempt_rebuild: Callable[[], ValSer | None] | None = None, + ) -> None: + self._error_message = error_message + self._val_or_ser = SchemaValidator if val_or_ser == 'validator' else SchemaSerializer + self._code: PydanticErrorCodes = code + self._attempt_rebuild = attempt_rebuild + + def __getattr__(self, item: str) -> None: + __tracebackhide__ = True + if self._attempt_rebuild: + val_ser = self._attempt_rebuild() + if val_ser is not None: + return getattr(val_ser, item) + + # raise an AttributeError if `item` doesn't exist + getattr(self._val_or_ser, item) + raise PydanticUserError(self._error_message, code=self._code) + + def rebuild(self) -> ValSer | None: + if self._attempt_rebuild: + val_ser = self._attempt_rebuild() + if val_ser is not None: + return val_ser + else: + raise PydanticUserError(self._error_message, code=self._code) + return None + + +def set_model_mocks(cls: type[BaseModel], cls_name: str, undefined_name: str = 'all referenced types') -> None: + """Set `__pydantic_validator__` and `__pydantic_serializer__` to `MockValSer`s on a model. + + Args: + cls: The model class to set the mocks on + cls_name: Name of the model class, used in error messages + undefined_name: Name of the undefined thing, used in error messages + """ + undefined_type_error_message = ( + f'`{cls_name}` is not fully defined; you should define {undefined_name},' + f' then call `{cls_name}.model_rebuild()`.' + ) + + def attempt_rebuild_fn(attr_fn: Callable[[type[BaseModel]], T]) -> Callable[[], T | None]: + def handler() -> T | None: + if cls.model_rebuild(raise_errors=False, _parent_namespace_depth=5) is not False: + return attr_fn(cls) + else: + return None + + return handler + + cls.__pydantic_core_schema__ = MockCoreSchema( # type: ignore[assignment] + undefined_type_error_message, + code='class-not-fully-defined', + attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__), + ) + cls.__pydantic_validator__ = MockValSer( # type: ignore[assignment] + undefined_type_error_message, + code='class-not-fully-defined', + val_or_ser='validator', + attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__), + ) + cls.__pydantic_serializer__ = MockValSer( # type: ignore[assignment] + undefined_type_error_message, + code='class-not-fully-defined', + val_or_ser='serializer', + attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__), + ) + + +def set_dataclass_mocks( + cls: type[PydanticDataclass], cls_name: str, undefined_name: str = 'all referenced types' +) -> None: + """Set `__pydantic_validator__` and `__pydantic_serializer__` to `MockValSer`s on a dataclass. + + Args: + cls: The model class to set the mocks on + cls_name: Name of the model class, used in error messages + undefined_name: Name of the undefined thing, used in error messages + """ + from ..dataclasses import rebuild_dataclass + + undefined_type_error_message = ( + f'`{cls_name}` is not fully defined; you should define {undefined_name},' + f' then call `pydantic.dataclasses.rebuild_dataclass({cls_name})`.' + ) + + def attempt_rebuild_fn(attr_fn: Callable[[type[PydanticDataclass]], T]) -> Callable[[], T | None]: + def handler() -> T | None: + if rebuild_dataclass(cls, raise_errors=False, _parent_namespace_depth=5) is not False: + return attr_fn(cls) + else: + return None + + return handler + + cls.__pydantic_core_schema__ = MockCoreSchema( # type: ignore[assignment] + undefined_type_error_message, + code='class-not-fully-defined', + attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_core_schema__), + ) + cls.__pydantic_validator__ = MockValSer( # type: ignore[assignment] + undefined_type_error_message, + code='class-not-fully-defined', + val_or_ser='validator', + attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_validator__), + ) + cls.__pydantic_serializer__ = MockValSer( # type: ignore[assignment] + undefined_type_error_message, + code='class-not-fully-defined', + val_or_ser='validator', + attempt_rebuild=attempt_rebuild_fn(lambda c: c.__pydantic_serializer__), + ) diff --git a/env/Lib/site-packages/pydantic/_internal/_model_construction.py b/env/Lib/site-packages/pydantic/_internal/_model_construction.py new file mode 100644 index 0000000..3212476 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_model_construction.py @@ -0,0 +1,708 @@ +"""Private logic for creating models.""" + +from __future__ import annotations as _annotations + +import builtins +import operator +import typing +import warnings +import weakref +from abc import ABCMeta +from functools import partial +from types import FunctionType +from typing import Any, Callable, Generic, NoReturn + +import typing_extensions +from pydantic_core import PydanticUndefined, SchemaSerializer +from typing_extensions import dataclass_transform, deprecated + +from ..errors import PydanticUndefinedAnnotation, PydanticUserError +from ..plugin._schema_validator import create_schema_validator +from ..warnings import GenericBeforeBaseModelWarning, PydanticDeprecatedSince20 +from ._config import ConfigWrapper +from ._decorators import DecoratorInfos, PydanticDescriptorProxy, get_attribute_from_bases, unwrap_wrapped_function +from ._fields import collect_model_fields, is_valid_field_name, is_valid_privateattr_name +from ._generate_schema import GenerateSchema +from ._generics import PydanticGenericMetadata, get_model_typevars_map +from ._mock_val_ser import set_model_mocks +from ._schema_generation_shared import CallbackGetCoreSchemaHandler +from ._signature import generate_pydantic_signature +from ._typing_extra import get_cls_types_namespace, is_annotated, is_classvar, parent_frame_namespace +from ._utils import ClassAttribute, SafeGetItemProxy +from ._validate_call import ValidateCallWrapper + +if typing.TYPE_CHECKING: + from ..fields import Field as PydanticModelField + from ..fields import FieldInfo, ModelPrivateAttr + from ..fields import PrivateAttr as PydanticModelPrivateAttr + from ..main import BaseModel +else: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + PydanticModelField = object() + PydanticModelPrivateAttr = object() + +object_setattr = object.__setattr__ + + +class _ModelNamespaceDict(dict): + """A dictionary subclass that intercepts attribute setting on model classes and + warns about overriding of decorators. + """ + + def __setitem__(self, k: str, v: object) -> None: + existing: Any = self.get(k, None) + if existing and v is not existing and isinstance(existing, PydanticDescriptorProxy): + warnings.warn(f'`{k}` overrides an existing Pydantic `{existing.decorator_info.decorator_repr}` decorator') + + return super().__setitem__(k, v) + + +@dataclass_transform(kw_only_default=True, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr)) +class ModelMetaclass(ABCMeta): + def __new__( + mcs, + cls_name: str, + bases: tuple[type[Any], ...], + namespace: dict[str, Any], + __pydantic_generic_metadata__: PydanticGenericMetadata | None = None, + __pydantic_reset_parent_namespace__: bool = True, + _create_model_module: str | None = None, + **kwargs: Any, + ) -> type: + """Metaclass for creating Pydantic models. + + Args: + cls_name: The name of the class to be created. + bases: The base classes of the class to be created. + namespace: The attribute dictionary of the class to be created. + __pydantic_generic_metadata__: Metadata for generic models. + __pydantic_reset_parent_namespace__: Reset parent namespace. + _create_model_module: The module of the class to be created, if created by `create_model`. + **kwargs: Catch-all for any other keyword arguments. + + Returns: + The new class created by the metaclass. + """ + # Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we rely on the fact + # that `BaseModel` itself won't have any bases, but any subclass of it will, to determine whether the `__new__` + # call we're in the middle of is for the `BaseModel` class. + if bases: + base_field_names, class_vars, base_private_attributes = mcs._collect_bases_data(bases) + + config_wrapper = ConfigWrapper.for_model(bases, namespace, kwargs) + namespace['model_config'] = config_wrapper.config_dict + private_attributes = inspect_namespace( + namespace, config_wrapper.ignored_types, class_vars, base_field_names + ) + if private_attributes or base_private_attributes: + original_model_post_init = get_model_post_init(namespace, bases) + if original_model_post_init is not None: + # if there are private_attributes and a model_post_init function, we handle both + + def wrapped_model_post_init(self: BaseModel, context: Any, /) -> None: + """We need to both initialize private attributes and call the user-defined model_post_init + method. + """ + init_private_attributes(self, context) + original_model_post_init(self, context) + + namespace['model_post_init'] = wrapped_model_post_init + else: + namespace['model_post_init'] = init_private_attributes + + namespace['__class_vars__'] = class_vars + namespace['__private_attributes__'] = {**base_private_attributes, **private_attributes} + + cls: type[BaseModel] = super().__new__(mcs, cls_name, bases, namespace, **kwargs) # type: ignore + + from ..main import BaseModel + + mro = cls.__mro__ + if Generic in mro and mro.index(Generic) < mro.index(BaseModel): + warnings.warn( + GenericBeforeBaseModelWarning( + 'Classes should inherit from `BaseModel` before generic classes (e.g. `typing.Generic[T]`) ' + 'for pydantic generics to work properly.' + ), + stacklevel=2, + ) + + cls.__pydantic_custom_init__ = not getattr(cls.__init__, '__pydantic_base_init__', False) + cls.__pydantic_post_init__ = None if cls.model_post_init is BaseModel.model_post_init else 'model_post_init' + + cls.__pydantic_decorators__ = DecoratorInfos.build(cls) + + # Use the getattr below to grab the __parameters__ from the `typing.Generic` parent class + if __pydantic_generic_metadata__: + cls.__pydantic_generic_metadata__ = __pydantic_generic_metadata__ + else: + parent_parameters = getattr(cls, '__pydantic_generic_metadata__', {}).get('parameters', ()) + parameters = getattr(cls, '__parameters__', None) or parent_parameters + if parameters and parent_parameters and not all(x in parameters for x in parent_parameters): + from ..root_model import RootModelRootType + + missing_parameters = tuple(x for x in parameters if x not in parent_parameters) + if RootModelRootType in parent_parameters and RootModelRootType not in parameters: + # This is a special case where the user has subclassed `RootModel`, but has not parametrized + # RootModel with the generic type identifiers being used. Ex: + # class MyModel(RootModel, Generic[T]): + # root: T + # Should instead just be: + # class MyModel(RootModel[T]): + # root: T + parameters_str = ', '.join([x.__name__ for x in missing_parameters]) + error_message = ( + f'{cls.__name__} is a subclass of `RootModel`, but does not include the generic type identifier(s) ' + f'{parameters_str} in its parameters. ' + f'You should parametrize RootModel directly, e.g., `class {cls.__name__}(RootModel[{parameters_str}]): ...`.' + ) + else: + combined_parameters = parent_parameters + missing_parameters + parameters_str = ', '.join([str(x) for x in combined_parameters]) + generic_type_label = f'typing.Generic[{parameters_str}]' + error_message = ( + f'All parameters must be present on typing.Generic;' + f' you should inherit from {generic_type_label}.' + ) + if Generic not in bases: # pragma: no cover + # We raise an error here not because it is desirable, but because some cases are mishandled. + # It would be nice to remove this error and still have things behave as expected, it's just + # challenging because we are using a custom `__class_getitem__` to parametrize generic models, + # and not returning a typing._GenericAlias from it. + bases_str = ', '.join([x.__name__ for x in bases] + [generic_type_label]) + error_message += ( + f' Note: `typing.Generic` must go last: `class {cls.__name__}({bases_str}): ...`)' + ) + raise TypeError(error_message) + + cls.__pydantic_generic_metadata__ = { + 'origin': None, + 'args': (), + 'parameters': parameters, + } + + cls.__pydantic_complete__ = False # Ensure this specific class gets completed + + # preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487 + # for attributes not in `new_namespace` (e.g. private attributes) + for name, obj in private_attributes.items(): + obj.__set_name__(cls, name) + + if __pydantic_reset_parent_namespace__: + cls.__pydantic_parent_namespace__ = build_lenient_weakvaluedict(parent_frame_namespace()) + parent_namespace = getattr(cls, '__pydantic_parent_namespace__', None) + if isinstance(parent_namespace, dict): + parent_namespace = unpack_lenient_weakvaluedict(parent_namespace) + + types_namespace = get_cls_types_namespace(cls, parent_namespace) + set_model_fields(cls, bases, config_wrapper, types_namespace) + + if config_wrapper.frozen and '__hash__' not in namespace: + set_default_hash_func(cls, bases) + + complete_model_class( + cls, + cls_name, + config_wrapper, + raise_errors=False, + types_namespace=types_namespace, + create_model_module=_create_model_module, + ) + + # If this is placed before the complete_model_class call above, + # the generic computed fields return type is set to PydanticUndefined + cls.model_computed_fields = {k: v.info for k, v in cls.__pydantic_decorators__.computed_fields.items()} + + set_deprecated_descriptors(cls) + + # using super(cls, cls) on the next line ensures we only call the parent class's __pydantic_init_subclass__ + # I believe the `type: ignore` is only necessary because mypy doesn't realize that this code branch is + # only hit for _proper_ subclasses of BaseModel + super(cls, cls).__pydantic_init_subclass__(**kwargs) # type: ignore[misc] + return cls + else: + # this is the BaseModel class itself being created, no logic required + return super().__new__(mcs, cls_name, bases, namespace, **kwargs) + + if not typing.TYPE_CHECKING: # pragma: no branch + # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access + + def __getattr__(self, item: str) -> Any: + """This is necessary to keep attribute access working for class attribute access.""" + private_attributes = self.__dict__.get('__private_attributes__') + if private_attributes and item in private_attributes: + return private_attributes[item] + raise AttributeError(item) + + @classmethod + def __prepare__(cls, *args: Any, **kwargs: Any) -> dict[str, object]: + return _ModelNamespaceDict() + + def __instancecheck__(self, instance: Any) -> bool: + """Avoid calling ABC _abc_subclasscheck unless we're pretty sure. + + See #3829 and python/cpython#92810 + """ + return hasattr(instance, '__pydantic_validator__') and super().__instancecheck__(instance) + + @staticmethod + def _collect_bases_data(bases: tuple[type[Any], ...]) -> tuple[set[str], set[str], dict[str, ModelPrivateAttr]]: + from ..main import BaseModel + + field_names: set[str] = set() + class_vars: set[str] = set() + private_attributes: dict[str, ModelPrivateAttr] = {} + for base in bases: + if issubclass(base, BaseModel) and base is not BaseModel: + # model_fields might not be defined yet in the case of generics, so we use getattr here: + field_names.update(getattr(base, 'model_fields', {}).keys()) + class_vars.update(base.__class_vars__) + private_attributes.update(base.__private_attributes__) + return field_names, class_vars, private_attributes + + @property + @deprecated('The `__fields__` attribute is deprecated, use `model_fields` instead.', category=None) + def __fields__(self) -> dict[str, FieldInfo]: + warnings.warn( + 'The `__fields__` attribute is deprecated, use `model_fields` instead.', PydanticDeprecatedSince20 + ) + return self.model_fields # type: ignore + + def __dir__(self) -> list[str]: + attributes = list(super().__dir__()) + if '__fields__' in attributes: + attributes.remove('__fields__') + return attributes + + +def init_private_attributes(self: BaseModel, context: Any, /) -> None: + """This function is meant to behave like a BaseModel method to initialise private attributes. + + It takes context as an argument since that's what pydantic-core passes when calling it. + + Args: + self: The BaseModel instance. + context: The context. + """ + if getattr(self, '__pydantic_private__', None) is None: + pydantic_private = {} + for name, private_attr in self.__private_attributes__.items(): + default = private_attr.get_default() + if default is not PydanticUndefined: + pydantic_private[name] = default + object_setattr(self, '__pydantic_private__', pydantic_private) + + +def get_model_post_init(namespace: dict[str, Any], bases: tuple[type[Any], ...]) -> Callable[..., Any] | None: + """Get the `model_post_init` method from the namespace or the class bases, or `None` if not defined.""" + if 'model_post_init' in namespace: + return namespace['model_post_init'] + + from ..main import BaseModel + + model_post_init = get_attribute_from_bases(bases, 'model_post_init') + if model_post_init is not BaseModel.model_post_init: + return model_post_init + + +def inspect_namespace( # noqa C901 + namespace: dict[str, Any], + ignored_types: tuple[type[Any], ...], + base_class_vars: set[str], + base_class_fields: set[str], +) -> dict[str, ModelPrivateAttr]: + """Iterate over the namespace and: + * gather private attributes + * check for items which look like fields but are not (e.g. have no annotation) and warn. + + Args: + namespace: The attribute dictionary of the class to be created. + ignored_types: A tuple of ignore types. + base_class_vars: A set of base class class variables. + base_class_fields: A set of base class fields. + + Returns: + A dict contains private attributes info. + + Raises: + TypeError: If there is a `__root__` field in model. + NameError: If private attribute name is invalid. + PydanticUserError: + - If a field does not have a type annotation. + - If a field on base class was overridden by a non-annotated attribute. + """ + from ..fields import FieldInfo, ModelPrivateAttr, PrivateAttr + + all_ignored_types = ignored_types + default_ignored_types() + + private_attributes: dict[str, ModelPrivateAttr] = {} + raw_annotations = namespace.get('__annotations__', {}) + + if '__root__' in raw_annotations or '__root__' in namespace: + raise TypeError("To define root models, use `pydantic.RootModel` rather than a field called '__root__'") + + ignored_names: set[str] = set() + for var_name, value in list(namespace.items()): + if var_name == 'model_config' or var_name == '__pydantic_extra__': + continue + elif ( + isinstance(value, type) + and value.__module__ == namespace['__module__'] + and '__qualname__' in namespace + and value.__qualname__.startswith(namespace['__qualname__']) + ): + # `value` is a nested type defined in this namespace; don't error + continue + elif isinstance(value, all_ignored_types) or value.__class__.__module__ == 'functools': + ignored_names.add(var_name) + continue + elif isinstance(value, ModelPrivateAttr): + if var_name.startswith('__'): + raise NameError( + 'Private attributes must not use dunder names;' + f' use a single underscore prefix instead of {var_name!r}.' + ) + elif is_valid_field_name(var_name): + raise NameError( + 'Private attributes must not use valid field names;' + f' use sunder names, e.g. {"_" + var_name!r} instead of {var_name!r}.' + ) + private_attributes[var_name] = value + del namespace[var_name] + elif isinstance(value, FieldInfo) and not is_valid_field_name(var_name): + suggested_name = var_name.lstrip('_') or 'my_field' # don't suggest '' for all-underscore name + raise NameError( + f'Fields must not use names with leading underscores;' + f' e.g., use {suggested_name!r} instead of {var_name!r}.' + ) + + elif var_name.startswith('__'): + continue + elif is_valid_privateattr_name(var_name): + if var_name not in raw_annotations or not is_classvar(raw_annotations[var_name]): + private_attributes[var_name] = PrivateAttr(default=value) + del namespace[var_name] + elif var_name in base_class_vars: + continue + elif var_name not in raw_annotations: + if var_name in base_class_fields: + raise PydanticUserError( + f'Field {var_name!r} defined on a base class was overridden by a non-annotated attribute. ' + f'All field definitions, including overrides, require a type annotation.', + code='model-field-overridden', + ) + elif isinstance(value, FieldInfo): + raise PydanticUserError( + f'Field {var_name!r} requires a type annotation', code='model-field-missing-annotation' + ) + else: + raise PydanticUserError( + f'A non-annotated attribute was detected: `{var_name} = {value!r}`. All model fields require a ' + f'type annotation; if `{var_name}` is not meant to be a field, you may be able to resolve this ' + f"error by annotating it as a `ClassVar` or updating `model_config['ignored_types']`.", + code='model-field-missing-annotation', + ) + + for ann_name, ann_type in raw_annotations.items(): + if ( + is_valid_privateattr_name(ann_name) + and ann_name not in private_attributes + and ann_name not in ignored_names + and not is_classvar(ann_type) + and ann_type not in all_ignored_types + and getattr(ann_type, '__module__', None) != 'functools' + ): + if is_annotated(ann_type): + _, *metadata = typing_extensions.get_args(ann_type) + private_attr = next((v for v in metadata if isinstance(v, ModelPrivateAttr)), None) + if private_attr is not None: + private_attributes[ann_name] = private_attr + continue + private_attributes[ann_name] = PrivateAttr() + + return private_attributes + + +def set_default_hash_func(cls: type[BaseModel], bases: tuple[type[Any], ...]) -> None: + base_hash_func = get_attribute_from_bases(bases, '__hash__') + new_hash_func = make_hash_func(cls) + if base_hash_func in {None, object.__hash__} or getattr(base_hash_func, '__code__', None) == new_hash_func.__code__: + # If `__hash__` is some default, we generate a hash function. + # It will be `None` if not overridden from BaseModel. + # It may be `object.__hash__` if there is another + # parent class earlier in the bases which doesn't override `__hash__` (e.g. `typing.Generic`). + # It may be a value set by `set_default_hash_func` if `cls` is a subclass of another frozen model. + # In the last case we still need a new hash function to account for new `model_fields`. + cls.__hash__ = new_hash_func + + +def make_hash_func(cls: type[BaseModel]) -> Any: + getter = operator.itemgetter(*cls.model_fields.keys()) if cls.model_fields else lambda _: 0 + + def hash_func(self: Any) -> int: + try: + return hash(getter(self.__dict__)) + except KeyError: + # In rare cases (such as when using the deprecated copy method), the __dict__ may not contain + # all model fields, which is how we can get here. + # getter(self.__dict__) is much faster than any 'safe' method that accounts for missing keys, + # and wrapping it in a `try` doesn't slow things down much in the common case. + return hash(getter(SafeGetItemProxy(self.__dict__))) + + return hash_func + + +def set_model_fields( + cls: type[BaseModel], bases: tuple[type[Any], ...], config_wrapper: ConfigWrapper, types_namespace: dict[str, Any] +) -> None: + """Collect and set `cls.model_fields` and `cls.__class_vars__`. + + Args: + cls: BaseModel or dataclass. + bases: Parents of the class, generally `cls.__bases__`. + config_wrapper: The config wrapper instance. + types_namespace: Optional extra namespace to look for types in. + """ + typevars_map = get_model_typevars_map(cls) + fields, class_vars = collect_model_fields(cls, bases, config_wrapper, types_namespace, typevars_map=typevars_map) + + cls.model_fields = fields + cls.__class_vars__.update(class_vars) + + for k in class_vars: + # Class vars should not be private attributes + # We remove them _here_ and not earlier because we rely on inspecting the class to determine its classvars, + # but private attributes are determined by inspecting the namespace _prior_ to class creation. + # In the case that a classvar with a leading-'_' is defined via a ForwardRef (e.g., when using + # `__future__.annotations`), we want to remove the private attribute which was detected _before_ we knew it + # evaluated to a classvar + + value = cls.__private_attributes__.pop(k, None) + if value is not None and value.default is not PydanticUndefined: + setattr(cls, k, value.default) + + +def complete_model_class( + cls: type[BaseModel], + cls_name: str, + config_wrapper: ConfigWrapper, + *, + raise_errors: bool = True, + types_namespace: dict[str, Any] | None, + create_model_module: str | None = None, +) -> bool: + """Finish building a model class. + + This logic must be called after class has been created since validation functions must be bound + and `get_type_hints` requires a class object. + + Args: + cls: BaseModel or dataclass. + cls_name: The model or dataclass name. + config_wrapper: The config wrapper instance. + raise_errors: Whether to raise errors. + types_namespace: Optional extra namespace to look for types in. + create_model_module: The module of the class to be created, if created by `create_model`. + + Returns: + `True` if the model is successfully completed, else `False`. + + Raises: + PydanticUndefinedAnnotation: If `PydanticUndefinedAnnotation` occurs in`__get_pydantic_core_schema__` + and `raise_errors=True`. + """ + typevars_map = get_model_typevars_map(cls) + gen_schema = GenerateSchema( + config_wrapper, + types_namespace, + typevars_map, + ) + + handler = CallbackGetCoreSchemaHandler( + partial(gen_schema.generate_schema, from_dunder_get_core_schema=False), + gen_schema, + ref_mode='unpack', + ) + + if config_wrapper.defer_build and 'model' in config_wrapper.experimental_defer_build_mode: + set_model_mocks(cls, cls_name) + return False + + try: + schema = cls.__get_pydantic_core_schema__(cls, handler) + except PydanticUndefinedAnnotation as e: + if raise_errors: + raise + set_model_mocks(cls, cls_name, f'`{e.name}`') + return False + + core_config = config_wrapper.core_config(cls) + + try: + schema = gen_schema.clean_schema(schema) + except gen_schema.CollectedInvalid: + set_model_mocks(cls, cls_name) + return False + + # debug(schema) + cls.__pydantic_core_schema__ = schema + + cls.__pydantic_validator__ = create_schema_validator( + schema, + cls, + create_model_module or cls.__module__, + cls.__qualname__, + 'create_model' if create_model_module else 'BaseModel', + core_config, + config_wrapper.plugin_settings, + ) + cls.__pydantic_serializer__ = SchemaSerializer(schema, core_config) + cls.__pydantic_complete__ = True + + # set __signature__ attr only for model class, but not for its instances + cls.__signature__ = ClassAttribute( + '__signature__', + generate_pydantic_signature(init=cls.__init__, fields=cls.model_fields, config_wrapper=config_wrapper), + ) + return True + + +def set_deprecated_descriptors(cls: type[BaseModel]) -> None: + """Set data descriptors on the class for deprecated fields.""" + for field, field_info in cls.model_fields.items(): + if (msg := field_info.deprecation_message) is not None: + desc = _DeprecatedFieldDescriptor(msg) + desc.__set_name__(cls, field) + setattr(cls, field, desc) + + for field, computed_field_info in cls.model_computed_fields.items(): + if ( + (msg := computed_field_info.deprecation_message) is not None + # Avoid having two warnings emitted: + and not hasattr(unwrap_wrapped_function(computed_field_info.wrapped_property), '__deprecated__') + ): + desc = _DeprecatedFieldDescriptor(msg, computed_field_info.wrapped_property) + desc.__set_name__(cls, field) + setattr(cls, field, desc) + + +class _DeprecatedFieldDescriptor: + """Data descriptor used to emit a runtime deprecation warning before accessing a deprecated field. + + Attributes: + msg: The deprecation message to be emitted. + wrapped_property: The property instance if the deprecated field is a computed field, or `None`. + field_name: The name of the field being deprecated. + """ + + field_name: str + + def __init__(self, msg: str, wrapped_property: property | None = None) -> None: + self.msg = msg + self.wrapped_property = wrapped_property + + def __set_name__(self, cls: type[BaseModel], name: str) -> None: + self.field_name = name + + def __get__(self, obj: BaseModel | None, obj_type: type[BaseModel] | None = None) -> Any: + if obj is None: + raise AttributeError(self.field_name) + + warnings.warn(self.msg, builtins.DeprecationWarning, stacklevel=2) + + if self.wrapped_property is not None: + return self.wrapped_property.__get__(obj, obj_type) + return obj.__dict__[self.field_name] + + # Defined to take precedence over the instance's dictionary + # Note that it will not be called when setting a value on a model instance + # as `BaseModel.__setattr__` is defined and takes priority. + def __set__(self, obj: Any, value: Any) -> NoReturn: + raise AttributeError(self.field_name) + + +class _PydanticWeakRef: + """Wrapper for `weakref.ref` that enables `pickle` serialization. + + Cloudpickle fails to serialize `weakref.ref` objects due to an arcane error related + to abstract base classes (`abc.ABC`). This class works around the issue by wrapping + `weakref.ref` instead of subclassing it. + + See https://github.com/pydantic/pydantic/issues/6763 for context. + + Semantics: + - If not pickled, behaves the same as a `weakref.ref`. + - If pickled along with the referenced object, the same `weakref.ref` behavior + will be maintained between them after unpickling. + - If pickled without the referenced object, after unpickling the underlying + reference will be cleared (`__call__` will always return `None`). + """ + + def __init__(self, obj: Any): + if obj is None: + # The object will be `None` upon deserialization if the serialized weakref + # had lost its underlying object. + self._wr = None + else: + self._wr = weakref.ref(obj) + + def __call__(self) -> Any: + if self._wr is None: + return None + else: + return self._wr() + + def __reduce__(self) -> tuple[Callable, tuple[weakref.ReferenceType | None]]: + return _PydanticWeakRef, (self(),) + + +def build_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None: + """Takes an input dictionary, and produces a new value that (invertibly) replaces the values with weakrefs. + + We can't just use a WeakValueDictionary because many types (including int, str, etc.) can't be stored as values + in a WeakValueDictionary. + + The `unpack_lenient_weakvaluedict` function can be used to reverse this operation. + """ + if d is None: + return None + result = {} + for k, v in d.items(): + try: + proxy = _PydanticWeakRef(v) + except TypeError: + proxy = v + result[k] = proxy + return result + + +def unpack_lenient_weakvaluedict(d: dict[str, Any] | None) -> dict[str, Any] | None: + """Inverts the transform performed by `build_lenient_weakvaluedict`.""" + if d is None: + return None + + result = {} + for k, v in d.items(): + if isinstance(v, _PydanticWeakRef): + v = v() + if v is not None: + result[k] = v + else: + result[k] = v + return result + + +def default_ignored_types() -> tuple[type[Any], ...]: + from ..fields import ComputedFieldInfo + + return ( + FunctionType, + property, + classmethod, + staticmethod, + PydanticDescriptorProxy, + ComputedFieldInfo, + ValidateCallWrapper, + ) diff --git a/env/Lib/site-packages/pydantic/_internal/_repr.py b/env/Lib/site-packages/pydantic/_internal/_repr.py new file mode 100644 index 0000000..83cb4cc --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_repr.py @@ -0,0 +1,118 @@ +"""Tools to provide pretty/human-readable display of objects.""" + +from __future__ import annotations as _annotations + +import types +import typing +from typing import Any + +import typing_extensions + +from . import _typing_extra + +if typing.TYPE_CHECKING: + ReprArgs: typing_extensions.TypeAlias = 'typing.Iterable[tuple[str | None, Any]]' + RichReprResult: typing_extensions.TypeAlias = ( + 'typing.Iterable[Any | tuple[Any] | tuple[str, Any] | tuple[str, Any, Any]]' + ) + + +class PlainRepr(str): + """String class where repr doesn't include quotes. Useful with Representation when you want to return a string + representation of something that is valid (or pseudo-valid) python. + """ + + def __repr__(self) -> str: + return str(self) + + +class Representation: + # Mixin to provide `__str__`, `__repr__`, and `__pretty__` and `__rich_repr__` methods. + # `__pretty__` is used by [devtools](https://python-devtools.helpmanual.io/). + # `__rich_repr__` is used by [rich](https://rich.readthedocs.io/en/stable/pretty.html). + # (this is not a docstring to avoid adding a docstring to classes which inherit from Representation) + + # we don't want to use a type annotation here as it can break get_type_hints + __slots__ = tuple() # type: typing.Collection[str] + + def __repr_args__(self) -> ReprArgs: + """Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden. + + Can either return: + * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]` + * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]` + """ + attrs_names = self.__slots__ + if not attrs_names and hasattr(self, '__dict__'): + attrs_names = self.__dict__.keys() + attrs = ((s, getattr(self, s)) for s in attrs_names) + return [(a, v) for a, v in attrs if v is not None] + + def __repr_name__(self) -> str: + """Name of the instance's class, used in __repr__.""" + return self.__class__.__name__ + + def __repr_str__(self, join_str: str) -> str: + return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__()) + + def __pretty__(self, fmt: typing.Callable[[Any], Any], **kwargs: Any) -> typing.Generator[Any, None, None]: + """Used by devtools (https://python-devtools.helpmanual.io/) to pretty print objects.""" + yield self.__repr_name__() + '(' + yield 1 + for name, value in self.__repr_args__(): + if name is not None: + yield name + '=' + yield fmt(value) + yield ',' + yield 0 + yield -1 + yield ')' + + def __rich_repr__(self) -> RichReprResult: + """Used by Rich (https://rich.readthedocs.io/en/stable/pretty.html) to pretty print objects.""" + for name, field_repr in self.__repr_args__(): + if name is None: + yield field_repr + else: + yield name, field_repr + + def __str__(self) -> str: + return self.__repr_str__(' ') + + def __repr__(self) -> str: + return f'{self.__repr_name__()}({self.__repr_str__(", ")})' + + +def display_as_type(obj: Any) -> str: + """Pretty representation of a type, should be as close as possible to the original type definition string. + + Takes some logic from `typing._type_repr`. + """ + if isinstance(obj, types.FunctionType): + return obj.__name__ + elif obj is ...: + return '...' + elif isinstance(obj, Representation): + return repr(obj) + elif isinstance(obj, typing_extensions.TypeAliasType): + return str(obj) + + if not isinstance(obj, (_typing_extra.typing_base, _typing_extra.WithArgsTypes, type)): + obj = obj.__class__ + + if _typing_extra.origin_is_union(typing_extensions.get_origin(obj)): + args = ', '.join(map(display_as_type, typing_extensions.get_args(obj))) + return f'Union[{args}]' + elif isinstance(obj, _typing_extra.WithArgsTypes): + if typing_extensions.get_origin(obj) == typing_extensions.Literal: + args = ', '.join(map(repr, typing_extensions.get_args(obj))) + else: + args = ', '.join(map(display_as_type, typing_extensions.get_args(obj))) + try: + return f'{obj.__qualname__}[{args}]' + except AttributeError: + return str(obj) # handles TypeAliasType in 3.12 + elif isinstance(obj, type): + return obj.__qualname__ + else: + return repr(obj).replace('typing.', '').replace('typing_extensions.', '') diff --git a/env/Lib/site-packages/pydantic/_internal/_schema_generation_shared.py b/env/Lib/site-packages/pydantic/_internal/_schema_generation_shared.py new file mode 100644 index 0000000..f35c665 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_schema_generation_shared.py @@ -0,0 +1,125 @@ +"""Types and utility functions used by various other internal tools.""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable + +from pydantic_core import core_schema +from typing_extensions import Literal + +from ..annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler + +if TYPE_CHECKING: + from ..json_schema import GenerateJsonSchema, JsonSchemaValue + from ._core_utils import CoreSchemaOrField + from ._generate_schema import GenerateSchema + + GetJsonSchemaFunction = Callable[[CoreSchemaOrField, GetJsonSchemaHandler], JsonSchemaValue] + HandlerOverride = Callable[[CoreSchemaOrField], JsonSchemaValue] + + +class GenerateJsonSchemaHandler(GetJsonSchemaHandler): + """JsonSchemaHandler implementation that doesn't do ref unwrapping by default. + + This is used for any Annotated metadata so that we don't end up with conflicting + modifications to the definition schema. + + Used internally by Pydantic, please do not rely on this implementation. + See `GetJsonSchemaHandler` for the handler API. + """ + + def __init__(self, generate_json_schema: GenerateJsonSchema, handler_override: HandlerOverride | None) -> None: + self.generate_json_schema = generate_json_schema + self.handler = handler_override or generate_json_schema.generate_inner + self.mode = generate_json_schema.mode + + def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue: + return self.handler(core_schema) + + def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue) -> JsonSchemaValue: + """Resolves `$ref` in the json schema. + + This returns the input json schema if there is no `$ref` in json schema. + + Args: + maybe_ref_json_schema: The input json schema that may contains `$ref`. + + Returns: + Resolved json schema. + + Raises: + LookupError: If it can't find the definition for `$ref`. + """ + if '$ref' not in maybe_ref_json_schema: + return maybe_ref_json_schema + ref = maybe_ref_json_schema['$ref'] + json_schema = self.generate_json_schema.get_schema_from_definitions(ref) + if json_schema is None: + raise LookupError( + f'Could not find a ref for {ref}.' + ' Maybe you tried to call resolve_ref_schema from within a recursive model?' + ) + return json_schema + + +class CallbackGetCoreSchemaHandler(GetCoreSchemaHandler): + """Wrapper to use an arbitrary function as a `GetCoreSchemaHandler`. + + Used internally by Pydantic, please do not rely on this implementation. + See `GetCoreSchemaHandler` for the handler API. + """ + + def __init__( + self, + handler: Callable[[Any], core_schema.CoreSchema], + generate_schema: GenerateSchema, + ref_mode: Literal['to-def', 'unpack'] = 'to-def', + ) -> None: + self._handler = handler + self._generate_schema = generate_schema + self._ref_mode = ref_mode + + def __call__(self, source_type: Any, /) -> core_schema.CoreSchema: + schema = self._handler(source_type) + ref = schema.get('ref') + if self._ref_mode == 'to-def': + if ref is not None: + self._generate_schema.defs.definitions[ref] = schema + return core_schema.definition_reference_schema(ref) + return schema + else: # ref_mode = 'unpack + return self.resolve_ref_schema(schema) + + def _get_types_namespace(self) -> dict[str, Any] | None: + return self._generate_schema._types_namespace + + def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema: + return self._generate_schema.generate_schema(source_type) + + @property + def field_name(self) -> str | None: + return self._generate_schema.field_name_stack.get() + + def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema) -> core_schema.CoreSchema: + """Resolves reference in the core schema. + + Args: + maybe_ref_schema: The input core schema that may contains reference. + + Returns: + Resolved core schema. + + Raises: + LookupError: If it can't find the definition for reference. + """ + if maybe_ref_schema['type'] == 'definition-ref': + ref = maybe_ref_schema['schema_ref'] + if ref not in self._generate_schema.defs.definitions: + raise LookupError( + f'Could not find a ref for {ref}.' + ' Maybe you tried to call resolve_ref_schema from within a recursive model?' + ) + return self._generate_schema.defs.definitions[ref] + elif maybe_ref_schema['type'] == 'definitions': + return self.resolve_ref_schema(maybe_ref_schema['schema']) + return maybe_ref_schema diff --git a/env/Lib/site-packages/pydantic/_internal/_signature.py b/env/Lib/site-packages/pydantic/_internal/_signature.py new file mode 100644 index 0000000..816a165 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_signature.py @@ -0,0 +1,164 @@ +from __future__ import annotations + +import dataclasses +from inspect import Parameter, Signature, signature +from typing import TYPE_CHECKING, Any, Callable + +from pydantic_core import PydanticUndefined + +from ._config import ConfigWrapper +from ._utils import is_valid_identifier + +if TYPE_CHECKING: + from ..fields import FieldInfo + + +def _field_name_for_signature(field_name: str, field_info: FieldInfo) -> str: + """Extract the correct name to use for the field when generating a signature. + + Assuming the field has a valid alias, this will return the alias. Otherwise, it will return the field name. + First priority is given to the validation_alias, then the alias, then the field name. + + Args: + field_name: The name of the field + field_info: The corresponding FieldInfo object. + + Returns: + The correct name to use when generating a signature. + """ + + def _alias_if_valid(x: Any) -> str | None: + """Return the alias if it is a valid alias and identifier, else None.""" + return x if isinstance(x, str) and is_valid_identifier(x) else None + + return _alias_if_valid(field_info.alias) or _alias_if_valid(field_info.validation_alias) or field_name + + +def _process_param_defaults(param: Parameter) -> Parameter: + """Modify the signature for a parameter in a dataclass where the default value is a FieldInfo instance. + + Args: + param (Parameter): The parameter + + Returns: + Parameter: The custom processed parameter + """ + from ..fields import FieldInfo + + param_default = param.default + if isinstance(param_default, FieldInfo): + annotation = param.annotation + # Replace the annotation if appropriate + # inspect does "clever" things to show annotations as strings because we have + # `from __future__ import annotations` in main, we don't want that + if annotation == 'Any': + annotation = Any + + # Replace the field default + default = param_default.default + if default is PydanticUndefined: + if param_default.default_factory is PydanticUndefined: + default = Signature.empty + else: + # this is used by dataclasses to indicate a factory exists: + default = dataclasses._HAS_DEFAULT_FACTORY # type: ignore + return param.replace( + annotation=annotation, name=_field_name_for_signature(param.name, param_default), default=default + ) + return param + + +def _generate_signature_parameters( # noqa: C901 (ignore complexity, could use a refactor) + init: Callable[..., None], + fields: dict[str, FieldInfo], + config_wrapper: ConfigWrapper, +) -> dict[str, Parameter]: + """Generate a mapping of parameter names to Parameter objects for a pydantic BaseModel or dataclass.""" + from itertools import islice + + present_params = signature(init).parameters.values() + merged_params: dict[str, Parameter] = {} + var_kw = None + use_var_kw = False + + for param in islice(present_params, 1, None): # skip self arg + # inspect does "clever" things to show annotations as strings because we have + # `from __future__ import annotations` in main, we don't want that + if fields.get(param.name): + # exclude params with init=False + if getattr(fields[param.name], 'init', True) is False: + continue + param = param.replace(name=_field_name_for_signature(param.name, fields[param.name])) + if param.annotation == 'Any': + param = param.replace(annotation=Any) + if param.kind is param.VAR_KEYWORD: + var_kw = param + continue + merged_params[param.name] = param + + if var_kw: # if custom init has no var_kw, fields which are not declared in it cannot be passed through + allow_names = config_wrapper.populate_by_name + for field_name, field in fields.items(): + # when alias is a str it should be used for signature generation + param_name = _field_name_for_signature(field_name, field) + + if field_name in merged_params or param_name in merged_params: + continue + + if not is_valid_identifier(param_name): + if allow_names: + param_name = field_name + else: + use_var_kw = True + continue + + kwargs = {} if field.is_required() else {'default': field.get_default(call_default_factory=False)} + merged_params[param_name] = Parameter( + param_name, Parameter.KEYWORD_ONLY, annotation=field.rebuild_annotation(), **kwargs + ) + + if config_wrapper.extra == 'allow': + use_var_kw = True + + if var_kw and use_var_kw: + # Make sure the parameter for extra kwargs + # does not have the same name as a field + default_model_signature = [ + ('self', Parameter.POSITIONAL_ONLY), + ('data', Parameter.VAR_KEYWORD), + ] + if [(p.name, p.kind) for p in present_params] == default_model_signature: + # if this is the standard model signature, use extra_data as the extra args name + var_kw_name = 'extra_data' + else: + # else start from var_kw + var_kw_name = var_kw.name + + # generate a name that's definitely unique + while var_kw_name in fields: + var_kw_name += '_' + merged_params[var_kw_name] = var_kw.replace(name=var_kw_name) + + return merged_params + + +def generate_pydantic_signature( + init: Callable[..., None], fields: dict[str, FieldInfo], config_wrapper: ConfigWrapper, is_dataclass: bool = False +) -> Signature: + """Generate signature for a pydantic BaseModel or dataclass. + + Args: + init: The class init. + fields: The model fields. + config_wrapper: The config wrapper instance. + is_dataclass: Whether the model is a dataclass. + + Returns: + The dataclass/BaseModel subclass signature. + """ + merged_params = _generate_signature_parameters(init, fields, config_wrapper) + + if is_dataclass: + merged_params = {k: _process_param_defaults(v) for k, v in merged_params.items()} + + return Signature(parameters=list(merged_params.values()), return_annotation=None) diff --git a/env/Lib/site-packages/pydantic/_internal/_std_types_schema.py b/env/Lib/site-packages/pydantic/_internal/_std_types_schema.py new file mode 100644 index 0000000..9f8b958 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_std_types_schema.py @@ -0,0 +1,722 @@ +"""Logic for generating pydantic-core schemas for standard library types. + +Import of this module is deferred since it contains imports of many standard library modules. +""" + +from __future__ import annotations as _annotations + +import collections +import collections.abc +import dataclasses +import decimal +import inspect +import os +import typing +from enum import Enum +from functools import partial +from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network +from operator import attrgetter +from typing import Any, Callable, Iterable, Literal, Tuple, TypeVar + +import typing_extensions +from pydantic_core import ( + CoreSchema, + MultiHostUrl, + PydanticCustomError, + PydanticOmit, + Url, + core_schema, +) +from typing_extensions import get_args, get_origin + +from pydantic.errors import PydanticSchemaGenerationError +from pydantic.fields import FieldInfo +from pydantic.types import Strict + +from ..config import ConfigDict +from ..json_schema import JsonSchemaValue +from . import _known_annotated_metadata, _typing_extra, _validators +from ._core_utils import get_type_ref +from ._internal_dataclass import slots_true +from ._schema_generation_shared import GetCoreSchemaHandler, GetJsonSchemaHandler + +if typing.TYPE_CHECKING: + from ._generate_schema import GenerateSchema + + StdSchemaFunction = Callable[[GenerateSchema, type[Any]], core_schema.CoreSchema] + + +@dataclasses.dataclass(**slots_true) +class SchemaTransformer: + get_core_schema: Callable[[Any, GetCoreSchemaHandler], CoreSchema] + get_json_schema: Callable[[CoreSchema, GetJsonSchemaHandler], JsonSchemaValue] + + def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: + return self.get_core_schema(source_type, handler) + + def __get_pydantic_json_schema__(self, schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue: + return self.get_json_schema(schema, handler) + + +def get_enum_core_schema(enum_type: type[Enum], config: ConfigDict) -> CoreSchema: + cases: list[Any] = list(enum_type.__members__.values()) + + enum_ref = get_type_ref(enum_type) + description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__) + if description == 'An enumeration.': # This is the default value provided by enum.EnumMeta.__new__; don't use it + description = None + js_updates = {'title': enum_type.__name__, 'description': description} + js_updates = {k: v for k, v in js_updates.items() if v is not None} + + sub_type: Literal['str', 'int', 'float'] | None = None + if issubclass(enum_type, int): + sub_type = 'int' + value_ser_type: core_schema.SerSchema = core_schema.simple_ser_schema('int') + elif issubclass(enum_type, str): + # this handles `StrEnum` (3.11 only), and also `Foobar(str, Enum)` + sub_type = 'str' + value_ser_type = core_schema.simple_ser_schema('str') + elif issubclass(enum_type, float): + sub_type = 'float' + value_ser_type = core_schema.simple_ser_schema('float') + else: + # TODO this is an ugly hack, how do we trigger an Any schema for serialization? + value_ser_type = core_schema.plain_serializer_function_ser_schema(lambda x: x) + + if cases: + + def get_json_schema(schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue: + json_schema = handler(schema) + original_schema = handler.resolve_ref_schema(json_schema) + original_schema.update(js_updates) + return json_schema + + # we don't want to add the missing to the schema if it's the default one + default_missing = getattr(enum_type._missing_, '__func__', None) == Enum._missing_.__func__ # type: ignore + enum_schema = core_schema.enum_schema( + enum_type, + cases, + sub_type=sub_type, + missing=None if default_missing else enum_type._missing_, + ref=enum_ref, + metadata={'pydantic_js_functions': [get_json_schema]}, + ) + + if config.get('use_enum_values', False): + enum_schema = core_schema.no_info_after_validator_function( + attrgetter('value'), enum_schema, serialization=value_ser_type + ) + + return enum_schema + + else: + + def get_json_schema_no_cases(_, handler: GetJsonSchemaHandler) -> JsonSchemaValue: + json_schema = handler(core_schema.enum_schema(enum_type, cases, sub_type=sub_type, ref=enum_ref)) + original_schema = handler.resolve_ref_schema(json_schema) + original_schema.update(js_updates) + return json_schema + + # Use an isinstance check for enums with no cases. + # The most important use case for this is creating TypeVar bounds for generics that should + # be restricted to enums. This is more consistent than it might seem at first, since you can only + # subclass enum.Enum (or subclasses of enum.Enum) if all parent classes have no cases. + # We use the get_json_schema function when an Enum subclass has been declared with no cases + # so that we can still generate a valid json schema. + return core_schema.is_instance_schema( + enum_type, + metadata={'pydantic_js_functions': [get_json_schema_no_cases]}, + ) + + +@dataclasses.dataclass(**slots_true) +class InnerSchemaValidator: + """Use a fixed CoreSchema, avoiding interference from outward annotations.""" + + core_schema: CoreSchema + js_schema: JsonSchemaValue | None = None + js_core_schema: CoreSchema | None = None + js_schema_update: JsonSchemaValue | None = None + + def __get_pydantic_json_schema__(self, _schema: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue: + if self.js_schema is not None: + return self.js_schema + js_schema = handler(self.js_core_schema or self.core_schema) + if self.js_schema_update is not None: + js_schema.update(self.js_schema_update) + return js_schema + + def __get_pydantic_core_schema__(self, _source_type: Any, _handler: GetCoreSchemaHandler) -> CoreSchema: + return self.core_schema + + +def decimal_prepare_pydantic_annotations( + source: Any, annotations: Iterable[Any], config: ConfigDict +) -> tuple[Any, list[Any]] | None: + if source is not decimal.Decimal: + return None + + metadata, remaining_annotations = _known_annotated_metadata.collect_known_metadata(annotations) + + config_allow_inf_nan = config.get('allow_inf_nan') + if config_allow_inf_nan is not None: + metadata.setdefault('allow_inf_nan', config_allow_inf_nan) + + _known_annotated_metadata.check_metadata( + metadata, {*_known_annotated_metadata.FLOAT_CONSTRAINTS, 'max_digits', 'decimal_places'}, decimal.Decimal + ) + return source, [InnerSchemaValidator(core_schema.decimal_schema(**metadata)), *remaining_annotations] + + +def datetime_prepare_pydantic_annotations( + source_type: Any, annotations: Iterable[Any], _config: ConfigDict +) -> tuple[Any, list[Any]] | None: + import datetime + + metadata, remaining_annotations = _known_annotated_metadata.collect_known_metadata(annotations) + if source_type is datetime.date: + sv = InnerSchemaValidator(core_schema.date_schema(**metadata)) + elif source_type is datetime.datetime: + sv = InnerSchemaValidator(core_schema.datetime_schema(**metadata)) + elif source_type is datetime.time: + sv = InnerSchemaValidator(core_schema.time_schema(**metadata)) + elif source_type is datetime.timedelta: + sv = InnerSchemaValidator(core_schema.timedelta_schema(**metadata)) + else: + return None + # check now that we know the source type is correct + _known_annotated_metadata.check_metadata(metadata, _known_annotated_metadata.DATE_TIME_CONSTRAINTS, source_type) + return (source_type, [sv, *remaining_annotations]) + + +def uuid_prepare_pydantic_annotations( + source_type: Any, annotations: Iterable[Any], _config: ConfigDict +) -> tuple[Any, list[Any]] | None: + # UUIDs have no constraints - they are fixed length, constructing a UUID instance checks the length + + from uuid import UUID + + if source_type is not UUID: + return None + + return (source_type, [InnerSchemaValidator(core_schema.uuid_schema()), *annotations]) + + +def path_schema_prepare_pydantic_annotations( + source_type: Any, annotations: Iterable[Any], _config: ConfigDict +) -> tuple[Any, list[Any]] | None: + import pathlib + + if source_type not in { + os.PathLike, + pathlib.Path, + pathlib.PurePath, + pathlib.PosixPath, + pathlib.PurePosixPath, + pathlib.PureWindowsPath, + }: + return None + + metadata, remaining_annotations = _known_annotated_metadata.collect_known_metadata(annotations) + _known_annotated_metadata.check_metadata(metadata, _known_annotated_metadata.STR_CONSTRAINTS, source_type) + + construct_path = pathlib.PurePath if source_type is os.PathLike else source_type + + def path_validator(input_value: str) -> os.PathLike[Any]: + try: + return construct_path(input_value) + except TypeError as e: + raise PydanticCustomError('path_type', 'Input is not a valid path') from e + + constrained_str_schema = core_schema.str_schema(**metadata) + + instance_schema = core_schema.json_or_python_schema( + json_schema=core_schema.no_info_after_validator_function(path_validator, constrained_str_schema), + python_schema=core_schema.is_instance_schema(source_type), + ) + + strict: bool | None = None + for annotation in annotations: + if isinstance(annotation, Strict): + strict = annotation.strict + + schema = core_schema.lax_or_strict_schema( + lax_schema=core_schema.union_schema( + [ + instance_schema, + core_schema.no_info_after_validator_function(path_validator, constrained_str_schema), + ], + custom_error_type='path_type', + custom_error_message='Input is not a valid path', + strict=True, + ), + strict_schema=instance_schema, + serialization=core_schema.to_string_ser_schema(), + strict=strict, + ) + + return ( + source_type, + [ + InnerSchemaValidator(schema, js_core_schema=constrained_str_schema, js_schema_update={'format': 'path'}), + *remaining_annotations, + ], + ) + + +def dequeue_validator( + input_value: Any, handler: core_schema.ValidatorFunctionWrapHandler, maxlen: None | int +) -> collections.deque[Any]: + if isinstance(input_value, collections.deque): + maxlens = [v for v in (input_value.maxlen, maxlen) if v is not None] + if maxlens: + maxlen = min(maxlens) + return collections.deque(handler(input_value), maxlen=maxlen) + else: + return collections.deque(handler(input_value), maxlen=maxlen) + + +def serialize_sequence_via_list( + v: Any, handler: core_schema.SerializerFunctionWrapHandler, info: core_schema.SerializationInfo +) -> Any: + items: list[Any] = [] + + mapped_origin = SEQUENCE_ORIGIN_MAP.get(type(v), None) + if mapped_origin is None: + # we shouldn't hit this branch, should probably add a serialization error or something + return v + + for index, item in enumerate(v): + try: + v = handler(item, index) + except PydanticOmit: + pass + else: + items.append(v) + + if info.mode_is_json(): + return items + else: + return mapped_origin(items) + + +@dataclasses.dataclass(**slots_true) +class SequenceValidator: + mapped_origin: type[Any] + item_source_type: type[Any] + min_length: int | None = None + max_length: int | None = None + strict: bool | None = None + fail_fast: bool | None = None + + def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: + if self.item_source_type is Any: + items_schema = None + else: + items_schema = handler.generate_schema(self.item_source_type) + + metadata = { + 'min_length': self.min_length, + 'max_length': self.max_length, + 'strict': self.strict, + 'fail_fast': self.fail_fast, + } + + if self.mapped_origin in (list, set, frozenset): + if self.mapped_origin is list: + constrained_schema = core_schema.list_schema(items_schema, **metadata) + elif self.mapped_origin is set: + constrained_schema = core_schema.set_schema(items_schema, **metadata) + else: + assert self.mapped_origin is frozenset # safety check in case we forget to add a case + constrained_schema = core_schema.frozenset_schema(items_schema, **metadata) + + schema = constrained_schema + else: + # safety check in case we forget to add a case + assert self.mapped_origin in (collections.deque, collections.Counter) + + if self.mapped_origin is collections.deque: + # if we have a MaxLen annotation might as well set that as the default maxlen on the deque + # this lets us re-use existing metadata annotations to let users set the maxlen on a dequeue + # that e.g. comes from JSON + coerce_instance_wrap = partial( + core_schema.no_info_wrap_validator_function, + partial(dequeue_validator, maxlen=metadata.get('max_length', None)), + ) + else: + coerce_instance_wrap = partial(core_schema.no_info_after_validator_function, self.mapped_origin) + + # we have to use a lax list schema here, because we need to validate the deque's + # items via a list schema, but it's ok if the deque itself is not a list (same for Counter) + metadata_with_strict_override = {**metadata, 'strict': False} + constrained_schema = core_schema.list_schema(items_schema, **metadata_with_strict_override) + + check_instance = core_schema.json_or_python_schema( + json_schema=core_schema.list_schema(), + python_schema=core_schema.is_instance_schema(self.mapped_origin), + ) + + serialization = core_schema.wrap_serializer_function_ser_schema( + serialize_sequence_via_list, schema=items_schema or core_schema.any_schema(), info_arg=True + ) + + strict = core_schema.chain_schema([check_instance, coerce_instance_wrap(constrained_schema)]) + + if metadata.get('strict', False): + schema = strict + else: + lax = coerce_instance_wrap(constrained_schema) + schema = core_schema.lax_or_strict_schema(lax_schema=lax, strict_schema=strict) + schema['serialization'] = serialization + + return schema + + +SEQUENCE_ORIGIN_MAP: dict[Any, Any] = { + typing.Deque: collections.deque, + collections.deque: collections.deque, + list: list, + typing.List: list, + set: set, + typing.AbstractSet: set, + typing.Set: set, + frozenset: frozenset, + typing.FrozenSet: frozenset, + typing.Sequence: list, + typing.MutableSequence: list, + typing.MutableSet: set, + # this doesn't handle subclasses of these + # parametrized typing.Set creates one of these + collections.abc.MutableSet: set, + collections.abc.Set: frozenset, +} + + +def identity(s: CoreSchema) -> CoreSchema: + return s + + +def sequence_like_prepare_pydantic_annotations( + source_type: Any, annotations: Iterable[Any], _config: ConfigDict +) -> tuple[Any, list[Any]] | None: + origin: Any = get_origin(source_type) + + mapped_origin = SEQUENCE_ORIGIN_MAP.get(origin, None) if origin else SEQUENCE_ORIGIN_MAP.get(source_type, None) + if mapped_origin is None: + return None + + args = get_args(source_type) + + if not args: + args = typing.cast(Tuple[Any], (Any,)) + elif len(args) != 1: + raise ValueError('Expected sequence to have exactly 1 generic parameter') + + item_source_type = args[0] + + metadata, remaining_annotations = _known_annotated_metadata.collect_known_metadata(annotations) + _known_annotated_metadata.check_metadata(metadata, _known_annotated_metadata.SEQUENCE_CONSTRAINTS, source_type) + + return (source_type, [SequenceValidator(mapped_origin, item_source_type, **metadata), *remaining_annotations]) + + +MAPPING_ORIGIN_MAP: dict[Any, Any] = { + typing.DefaultDict: collections.defaultdict, + collections.defaultdict: collections.defaultdict, + collections.OrderedDict: collections.OrderedDict, + typing_extensions.OrderedDict: collections.OrderedDict, + dict: dict, + typing.Dict: dict, + collections.Counter: collections.Counter, + typing.Counter: collections.Counter, + # this doesn't handle subclasses of these + typing.Mapping: dict, + typing.MutableMapping: dict, + # parametrized typing.{Mutable}Mapping creates one of these + collections.abc.MutableMapping: dict, + collections.abc.Mapping: dict, +} + + +def defaultdict_validator( + input_value: Any, handler: core_schema.ValidatorFunctionWrapHandler, default_default_factory: Callable[[], Any] +) -> collections.defaultdict[Any, Any]: + if isinstance(input_value, collections.defaultdict): + default_factory = input_value.default_factory + return collections.defaultdict(default_factory, handler(input_value)) + else: + return collections.defaultdict(default_default_factory, handler(input_value)) + + +def get_defaultdict_default_default_factory(values_source_type: Any) -> Callable[[], Any]: + def infer_default() -> Callable[[], Any]: + allowed_default_types: dict[Any, Any] = { + typing.Tuple: tuple, + tuple: tuple, + collections.abc.Sequence: tuple, + collections.abc.MutableSequence: list, + typing.List: list, + list: list, + typing.Sequence: list, + typing.Set: set, + set: set, + typing.MutableSet: set, + collections.abc.MutableSet: set, + collections.abc.Set: frozenset, + typing.MutableMapping: dict, + typing.Mapping: dict, + collections.abc.Mapping: dict, + collections.abc.MutableMapping: dict, + float: float, + int: int, + str: str, + bool: bool, + } + values_type_origin = get_origin(values_source_type) or values_source_type + instructions = 'set using `DefaultDict[..., Annotated[..., Field(default_factory=...)]]`' + if isinstance(values_type_origin, TypeVar): + + def type_var_default_factory() -> None: + raise RuntimeError( + 'Generic defaultdict cannot be used without a concrete value type or an' + ' explicit default factory, ' + instructions + ) + + return type_var_default_factory + elif values_type_origin not in allowed_default_types: + # a somewhat subjective set of types that have reasonable default values + allowed_msg = ', '.join([t.__name__ for t in set(allowed_default_types.values())]) + raise PydanticSchemaGenerationError( + f'Unable to infer a default factory for keys of type {values_source_type}.' + f' Only {allowed_msg} are supported, other types require an explicit default factory' + ' ' + instructions + ) + return allowed_default_types[values_type_origin] + + # Assume Annotated[..., Field(...)] + if _typing_extra.is_annotated(values_source_type): + field_info = next((v for v in get_args(values_source_type) if isinstance(v, FieldInfo)), None) + else: + field_info = None + if field_info and field_info.default_factory: + default_default_factory = field_info.default_factory + else: + default_default_factory = infer_default() + return default_default_factory + + +@dataclasses.dataclass(**slots_true) +class MappingValidator: + mapped_origin: type[Any] + keys_source_type: type[Any] + values_source_type: type[Any] + min_length: int | None = None + max_length: int | None = None + strict: bool = False + + def serialize_mapping_via_dict(self, v: Any, handler: core_schema.SerializerFunctionWrapHandler) -> Any: + return handler(v) + + def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: + if self.keys_source_type is Any: + keys_schema = None + else: + keys_schema = handler.generate_schema(self.keys_source_type) + if self.values_source_type is Any: + values_schema = None + else: + values_schema = handler.generate_schema(self.values_source_type) + + metadata = {'min_length': self.min_length, 'max_length': self.max_length, 'strict': self.strict} + + if self.mapped_origin is dict: + schema = core_schema.dict_schema(keys_schema, values_schema, **metadata) + else: + constrained_schema = core_schema.dict_schema(keys_schema, values_schema, **metadata) + check_instance = core_schema.json_or_python_schema( + json_schema=core_schema.dict_schema(), + python_schema=core_schema.is_instance_schema(self.mapped_origin), + ) + + if self.mapped_origin is collections.defaultdict: + default_default_factory = get_defaultdict_default_default_factory(self.values_source_type) + coerce_instance_wrap = partial( + core_schema.no_info_wrap_validator_function, + partial(defaultdict_validator, default_default_factory=default_default_factory), + ) + else: + coerce_instance_wrap = partial(core_schema.no_info_after_validator_function, self.mapped_origin) + + serialization = core_schema.wrap_serializer_function_ser_schema( + self.serialize_mapping_via_dict, + schema=core_schema.dict_schema( + keys_schema or core_schema.any_schema(), values_schema or core_schema.any_schema() + ), + info_arg=False, + ) + + strict = core_schema.chain_schema([check_instance, coerce_instance_wrap(constrained_schema)]) + + if metadata.get('strict', False): + schema = strict + else: + lax = coerce_instance_wrap(constrained_schema) + schema = core_schema.lax_or_strict_schema(lax_schema=lax, strict_schema=strict) + schema['serialization'] = serialization + + return schema + + +def mapping_like_prepare_pydantic_annotations( + source_type: Any, annotations: Iterable[Any], _config: ConfigDict +) -> tuple[Any, list[Any]] | None: + origin: Any = get_origin(source_type) + + mapped_origin = MAPPING_ORIGIN_MAP.get(origin, None) if origin else MAPPING_ORIGIN_MAP.get(source_type, None) + if mapped_origin is None: + return None + + args = get_args(source_type) + + if not args: + args = typing.cast(Tuple[Any, Any], (Any, Any)) + elif mapped_origin is collections.Counter: + # a single generic + if len(args) != 1: + raise ValueError('Expected Counter to have exactly 1 generic parameter') + args = (args[0], int) # keys are always an int + elif len(args) != 2: + raise ValueError('Expected mapping to have exactly 2 generic parameters') + + keys_source_type, values_source_type = args + + metadata, remaining_annotations = _known_annotated_metadata.collect_known_metadata(annotations) + _known_annotated_metadata.check_metadata(metadata, _known_annotated_metadata.SEQUENCE_CONSTRAINTS, source_type) + + return ( + source_type, + [ + MappingValidator(mapped_origin, keys_source_type, values_source_type, **metadata), + *remaining_annotations, + ], + ) + + +def ip_prepare_pydantic_annotations( + source_type: Any, annotations: Iterable[Any], _config: ConfigDict +) -> tuple[Any, list[Any]] | None: + def make_strict_ip_schema(tp: type[Any]) -> CoreSchema: + return core_schema.json_or_python_schema( + json_schema=core_schema.no_info_after_validator_function(tp, core_schema.str_schema()), + python_schema=core_schema.is_instance_schema(tp), + ) + + if source_type is IPv4Address: + return source_type, [ + SchemaTransformer( + lambda _1, _2: core_schema.lax_or_strict_schema( + lax_schema=core_schema.no_info_plain_validator_function(_validators.ip_v4_address_validator), + strict_schema=make_strict_ip_schema(IPv4Address), + serialization=core_schema.to_string_ser_schema(), + ), + lambda _1, _2: {'type': 'string', 'format': 'ipv4'}, + ), + *annotations, + ] + if source_type is IPv4Network: + return source_type, [ + SchemaTransformer( + lambda _1, _2: core_schema.lax_or_strict_schema( + lax_schema=core_schema.no_info_plain_validator_function(_validators.ip_v4_network_validator), + strict_schema=make_strict_ip_schema(IPv4Network), + serialization=core_schema.to_string_ser_schema(), + ), + lambda _1, _2: {'type': 'string', 'format': 'ipv4network'}, + ), + *annotations, + ] + if source_type is IPv4Interface: + return source_type, [ + SchemaTransformer( + lambda _1, _2: core_schema.lax_or_strict_schema( + lax_schema=core_schema.no_info_plain_validator_function(_validators.ip_v4_interface_validator), + strict_schema=make_strict_ip_schema(IPv4Interface), + serialization=core_schema.to_string_ser_schema(), + ), + lambda _1, _2: {'type': 'string', 'format': 'ipv4interface'}, + ), + *annotations, + ] + + if source_type is IPv6Address: + return source_type, [ + SchemaTransformer( + lambda _1, _2: core_schema.lax_or_strict_schema( + lax_schema=core_schema.no_info_plain_validator_function(_validators.ip_v6_address_validator), + strict_schema=make_strict_ip_schema(IPv6Address), + serialization=core_schema.to_string_ser_schema(), + ), + lambda _1, _2: {'type': 'string', 'format': 'ipv6'}, + ), + *annotations, + ] + if source_type is IPv6Network: + return source_type, [ + SchemaTransformer( + lambda _1, _2: core_schema.lax_or_strict_schema( + lax_schema=core_schema.no_info_plain_validator_function(_validators.ip_v6_network_validator), + strict_schema=make_strict_ip_schema(IPv6Network), + serialization=core_schema.to_string_ser_schema(), + ), + lambda _1, _2: {'type': 'string', 'format': 'ipv6network'}, + ), + *annotations, + ] + if source_type is IPv6Interface: + return source_type, [ + SchemaTransformer( + lambda _1, _2: core_schema.lax_or_strict_schema( + lax_schema=core_schema.no_info_plain_validator_function(_validators.ip_v6_interface_validator), + strict_schema=make_strict_ip_schema(IPv6Interface), + serialization=core_schema.to_string_ser_schema(), + ), + lambda _1, _2: {'type': 'string', 'format': 'ipv6interface'}, + ), + *annotations, + ] + + return None + + +def url_prepare_pydantic_annotations( + source_type: Any, annotations: Iterable[Any], _config: ConfigDict +) -> tuple[Any, list[Any]] | None: + if source_type is Url: + return source_type, [ + SchemaTransformer( + lambda _1, _2: core_schema.url_schema(), + lambda cs, handler: handler(cs), + ), + *annotations, + ] + if source_type is MultiHostUrl: + return source_type, [ + SchemaTransformer( + lambda _1, _2: core_schema.multi_host_url_schema(), + lambda cs, handler: handler(cs), + ), + *annotations, + ] + + +PREPARE_METHODS: tuple[Callable[[Any, Iterable[Any], ConfigDict], tuple[Any, list[Any]] | None], ...] = ( + decimal_prepare_pydantic_annotations, + sequence_like_prepare_pydantic_annotations, + datetime_prepare_pydantic_annotations, + uuid_prepare_pydantic_annotations, + path_schema_prepare_pydantic_annotations, + mapping_like_prepare_pydantic_annotations, + ip_prepare_pydantic_annotations, + url_prepare_pydantic_annotations, +) diff --git a/env/Lib/site-packages/pydantic/_internal/_typing_extra.py b/env/Lib/site-packages/pydantic/_internal/_typing_extra.py new file mode 100644 index 0000000..71be20b --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_typing_extra.py @@ -0,0 +1,508 @@ +"""Logic for interacting with type annotations, mostly extensions, shims and hacks to wrap python's typing module.""" + +from __future__ import annotations as _annotations + +import dataclasses +import re +import sys +import types +import typing +import warnings +from collections.abc import Callable +from functools import partial +from types import GetSetDescriptorType +from typing import TYPE_CHECKING, Any, Final + +from typing_extensions import Annotated, Literal, TypeAliasType, TypeGuard, deprecated, get_args, get_origin + +if TYPE_CHECKING: + from ._dataclasses import StandardDataclass + +try: + from typing import _TypingBase # type: ignore[attr-defined] +except ImportError: + from typing import _Final as _TypingBase # type: ignore[attr-defined] + +typing_base = _TypingBase + + +if sys.version_info < (3, 9): + # python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on) + TypingGenericAlias = () +else: + from typing import GenericAlias as TypingGenericAlias # type: ignore + + +if sys.version_info < (3, 11): + from typing_extensions import NotRequired, Required +else: + from typing import NotRequired, Required # noqa: F401 + + +if sys.version_info < (3, 10): + + def origin_is_union(tp: type[Any] | None) -> bool: + return tp is typing.Union + + WithArgsTypes = (TypingGenericAlias,) + +else: + + def origin_is_union(tp: type[Any] | None) -> bool: + return tp is typing.Union or tp is types.UnionType + + WithArgsTypes = typing._GenericAlias, types.GenericAlias, types.UnionType # type: ignore[attr-defined] + + +if sys.version_info < (3, 10): + NoneType = type(None) + EllipsisType = type(Ellipsis) +else: + from types import NoneType as NoneType + + +LITERAL_TYPES: set[Any] = {Literal} +if hasattr(typing, 'Literal'): + LITERAL_TYPES.add(typing.Literal) # type: ignore + +# Check if `deprecated` is a type to prevent errors when using typing_extensions < 4.9.0 +DEPRECATED_TYPES: tuple[Any, ...] = (deprecated,) if isinstance(deprecated, type) else () +if hasattr(warnings, 'deprecated'): + DEPRECATED_TYPES = (*DEPRECATED_TYPES, warnings.deprecated) # type: ignore + +NONE_TYPES: tuple[Any, ...] = (None, NoneType, *(tp[None] for tp in LITERAL_TYPES)) + + +TypeVarType = Any # since mypy doesn't allow the use of TypeVar as a type + + +def is_none_type(type_: Any) -> bool: + return type_ in NONE_TYPES + + +def is_callable_type(type_: type[Any]) -> bool: + return type_ is Callable or get_origin(type_) is Callable + + +def is_literal_type(type_: type[Any]) -> bool: + return Literal is not None and get_origin(type_) in LITERAL_TYPES + + +def is_deprecated_instance(instance: Any) -> TypeGuard[deprecated]: + return isinstance(instance, DEPRECATED_TYPES) + + +def literal_values(type_: type[Any]) -> tuple[Any, ...]: + return get_args(type_) + + +def all_literal_values(type_: type[Any]) -> list[Any]: + """This method is used to retrieve all Literal values as + Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586) + e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]`. + """ + if not is_literal_type(type_): + return [type_] + + values = literal_values(type_) + return list(x for value in values for x in all_literal_values(value)) + + +def is_annotated(ann_type: Any) -> bool: + return get_origin(ann_type) is Annotated + + +def annotated_type(type_: Any) -> Any | None: + return get_args(type_)[0] if is_annotated(type_) else None + + +def is_namedtuple(type_: type[Any]) -> bool: + """Check if a given class is a named tuple. + It can be either a `typing.NamedTuple` or `collections.namedtuple`. + """ + from ._utils import lenient_issubclass + + return lenient_issubclass(type_, tuple) and hasattr(type_, '_fields') + + +test_new_type = typing.NewType('test_new_type', str) + + +def is_new_type(type_: type[Any]) -> bool: + """Check whether type_ was created using typing.NewType. + + Can't use isinstance because it fails <3.10. + """ + return isinstance(type_, test_new_type.__class__) and hasattr(type_, '__supertype__') # type: ignore[arg-type] + + +def _check_classvar(v: type[Any] | None) -> bool: + if v is None: + return False + + return v.__class__ == typing.ClassVar.__class__ and getattr(v, '_name', None) == 'ClassVar' + + +def is_classvar(ann_type: type[Any]) -> bool: + if _check_classvar(ann_type) or _check_classvar(get_origin(ann_type)): + return True + + # this is an ugly workaround for class vars that contain forward references and are therefore themselves + # forward references, see #3679 + if ann_type.__class__ == typing.ForwardRef and re.match( + r'(\w+\.)?ClassVar\[', + ann_type.__forward_arg__, # type: ignore + ): + return True + + return False + + +def _check_finalvar(v: type[Any] | None) -> bool: + """Check if a given type is a `typing.Final` type.""" + if v is None: + return False + + return v.__class__ == Final.__class__ and (sys.version_info < (3, 8) or getattr(v, '_name', None) == 'Final') + + +def is_finalvar(ann_type: Any) -> bool: + return _check_finalvar(ann_type) or _check_finalvar(get_origin(ann_type)) + + +def parent_frame_namespace(*, parent_depth: int = 2) -> dict[str, Any] | None: + """We allow use of items in parent namespace to get around the issue with `get_type_hints` only looking in the + global module namespace. See https://github.com/pydantic/pydantic/issues/2678#issuecomment-1008139014 -> Scope + and suggestion at the end of the next comment by @gvanrossum. + + WARNING 1: it matters exactly where this is called. By default, this function will build a namespace from the + parent of where it is called. + + WARNING 2: this only looks in the parent namespace, not other parents since (AFAIK) there's no way to collect a + dict of exactly what's in scope. Using `f_back` would work sometimes but would be very wrong and confusing in many + other cases. See https://discuss.python.org/t/is-there-a-way-to-access-parent-nested-namespaces/20659. + """ + frame = sys._getframe(parent_depth) + # if f_back is None, it's the global module namespace and we don't need to include it here + if frame.f_back is None: + return None + else: + return frame.f_locals + + +def add_module_globals(obj: Any, globalns: dict[str, Any] | None = None) -> dict[str, Any]: + module_name = getattr(obj, '__module__', None) + if module_name: + try: + module_globalns = sys.modules[module_name].__dict__ + except KeyError: + # happens occasionally, see https://github.com/pydantic/pydantic/issues/2363 + pass + else: + if globalns: + return {**module_globalns, **globalns} + else: + # copy module globals to make sure it can't be updated later + return module_globalns.copy() + + return globalns or {} + + +def get_cls_types_namespace(cls: type[Any], parent_namespace: dict[str, Any] | None = None) -> dict[str, Any]: + ns = add_module_globals(cls, parent_namespace) + ns[cls.__name__] = cls + return ns + + +def get_cls_type_hints_lenient(obj: Any, globalns: dict[str, Any] | None = None) -> dict[str, Any]: + """Collect annotations from a class, including those from parent classes. + + Unlike `typing.get_type_hints`, this function will not error if a forward reference is not resolvable. + """ + hints = {} + for base in reversed(obj.__mro__): + ann = base.__dict__.get('__annotations__') + localns = dict(vars(base)) + if ann is not None and ann is not GetSetDescriptorType: + for name, value in ann.items(): + hints[name] = eval_type_lenient(value, globalns, localns) + return hints + + +def eval_type_lenient(value: Any, globalns: dict[str, Any] | None = None, localns: dict[str, Any] | None = None) -> Any: + """Behaves like typing._eval_type, except it won't raise an error if a forward reference can't be resolved.""" + if value is None: + value = NoneType + elif isinstance(value, str): + value = _make_forward_ref(value, is_argument=False, is_class=True) + + try: + return eval_type_backport(value, globalns, localns) + except NameError: + # the point of this function is to be tolerant to this case + return value + + +def eval_type_backport( + value: Any, + globalns: dict[str, Any] | None = None, + localns: dict[str, Any] | None = None, + type_params: tuple[Any] | None = None, +) -> Any: + """Like `typing._eval_type`, but falls back to the `eval_type_backport` package if it's + installed to let older Python versions use newer typing features. + Specifically, this transforms `X | Y` into `typing.Union[X, Y]` + and `list[X]` into `typing.List[X]` etc. (for all the types made generic in PEP 585) + if the original syntax is not supported in the current Python version. + """ + try: + if sys.version_info >= (3, 13): + return typing._eval_type( # type: ignore + value, globalns, localns, type_params=type_params + ) + else: + return typing._eval_type( # type: ignore + value, globalns, localns + ) + except TypeError as e: + if not (isinstance(value, typing.ForwardRef) and is_backport_fixable_error(e)): + raise + try: + from eval_type_backport import eval_type_backport + except ImportError: + raise TypeError( + f'You have a type annotation {value.__forward_arg__!r} ' + f'which makes use of newer typing features than are supported in your version of Python. ' + f'To handle this error, you should either remove the use of new syntax ' + f'or install the `eval_type_backport` package.' + ) from e + + return eval_type_backport(value, globalns, localns, try_default=False) + + +def is_backport_fixable_error(e: TypeError) -> bool: + msg = str(e) + return msg.startswith('unsupported operand type(s) for |: ') or "' object is not subscriptable" in msg + + +def get_function_type_hints( + function: Callable[..., Any], *, include_keys: set[str] | None = None, types_namespace: dict[str, Any] | None = None +) -> dict[str, Any]: + """Like `typing.get_type_hints`, but doesn't convert `X` to `Optional[X]` if the default value is `None`, also + copes with `partial`. + """ + try: + if isinstance(function, partial): + annotations = function.func.__annotations__ + else: + annotations = function.__annotations__ + except AttributeError: + type_hints = get_type_hints(function) + if isinstance(function, type): + # `type[...]` is a callable, which returns an instance of itself. + # At some point, we might even look into the return type of `__new__` + # if it returns something else. + type_hints.setdefault('return', function) + return type_hints + + globalns = add_module_globals(function) + type_hints = {} + type_params: tuple[Any] = getattr(function, '__type_params__', ()) # type: ignore + for name, value in annotations.items(): + if include_keys is not None and name not in include_keys: + continue + if value is None: + value = NoneType + elif isinstance(value, str): + value = _make_forward_ref(value) + + type_hints[name] = eval_type_backport(value, globalns, types_namespace, type_params) + + return type_hints + + +if sys.version_info < (3, 9, 8) or (3, 10) <= sys.version_info < (3, 10, 1): + + def _make_forward_ref( + arg: Any, + is_argument: bool = True, + *, + is_class: bool = False, + ) -> typing.ForwardRef: + """Wrapper for ForwardRef that accounts for the `is_class` argument missing in older versions. + The `module` argument is omitted as it breaks <3.9.8, =3.10.0 and isn't used in the calls below. + + See https://github.com/python/cpython/pull/28560 for some background. + The backport happened on 3.9.8, see: + https://github.com/pydantic/pydantic/discussions/6244#discussioncomment-6275458, + and on 3.10.1 for the 3.10 branch, see: + https://github.com/pydantic/pydantic/issues/6912 + + Implemented as EAFP with memory. + """ + return typing.ForwardRef(arg, is_argument) + +else: + _make_forward_ref = typing.ForwardRef + + +if sys.version_info >= (3, 10): + get_type_hints = typing.get_type_hints + +else: + """ + For older versions of python, we have a custom implementation of `get_type_hints` which is a close as possible to + the implementation in CPython 3.10.8. + """ + + @typing.no_type_check + def get_type_hints( # noqa: C901 + obj: Any, + globalns: dict[str, Any] | None = None, + localns: dict[str, Any] | None = None, + include_extras: bool = False, + ) -> dict[str, Any]: # pragma: no cover + """Taken verbatim from python 3.10.8 unchanged, except: + * type annotations of the function definition above. + * prefixing `typing.` where appropriate + * Use `_make_forward_ref` instead of `typing.ForwardRef` to handle the `is_class` argument. + + https://github.com/python/cpython/blob/aaaf5174241496afca7ce4d4584570190ff972fe/Lib/typing.py#L1773-L1875 + + DO NOT CHANGE THIS METHOD UNLESS ABSOLUTELY NECESSARY. + ====================================================== + + Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, adds Optional[t] if a + default value equal to None is set and recursively replaces all + 'Annotated[T, ...]' with 'T' (unless 'include_extras=True'). + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. For classes, the search + order is globals first then locals. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + """ + if getattr(obj, '__no_type_check__', None): + return {} + # Classes require a special treatment. + if isinstance(obj, type): + hints = {} + for base in reversed(obj.__mro__): + if globalns is None: + base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {}) + else: + base_globals = globalns + ann = base.__dict__.get('__annotations__', {}) + if isinstance(ann, types.GetSetDescriptorType): + ann = {} + base_locals = dict(vars(base)) if localns is None else localns + if localns is None and globalns is None: + # This is surprising, but required. Before Python 3.10, + # get_type_hints only evaluated the globalns of + # a class. To maintain backwards compatibility, we reverse + # the globalns and localns order so that eval() looks into + # *base_globals* first rather than *base_locals*. + # This only affects ForwardRefs. + base_globals, base_locals = base_locals, base_globals + for name, value in ann.items(): + if value is None: + value = type(None) + if isinstance(value, str): + value = _make_forward_ref(value, is_argument=False, is_class=True) + + value = eval_type_backport(value, base_globals, base_locals) + hints[name] = value + if not include_extras and hasattr(typing, '_strip_annotations'): + return { + k: typing._strip_annotations(t) # type: ignore + for k, t in hints.items() + } + else: + return hints + + if globalns is None: + if isinstance(obj, types.ModuleType): + globalns = obj.__dict__ + else: + nsobj = obj + # Find globalns for the unwrapped object. + while hasattr(nsobj, '__wrapped__'): + nsobj = nsobj.__wrapped__ + globalns = getattr(nsobj, '__globals__', {}) + if localns is None: + localns = globalns + elif localns is None: + localns = globalns + hints = getattr(obj, '__annotations__', None) + if hints is None: + # Return empty annotations for something that _could_ have them. + if isinstance(obj, typing._allowed_types): # type: ignore + return {} + else: + raise TypeError(f'{obj!r} is not a module, class, method, ' 'or function.') + defaults = typing._get_defaults(obj) # type: ignore + hints = dict(hints) + for name, value in hints.items(): + if value is None: + value = type(None) + if isinstance(value, str): + # class-level forward refs were handled above, this must be either + # a module-level annotation or a function argument annotation + + value = _make_forward_ref( + value, + is_argument=not isinstance(obj, types.ModuleType), + is_class=False, + ) + value = eval_type_backport(value, globalns, localns) + if name in defaults and defaults[name] is None: + value = typing.Optional[value] + hints[name] = value + return hints if include_extras else {k: typing._strip_annotations(t) for k, t in hints.items()} # type: ignore + + +def is_dataclass(_cls: type[Any]) -> TypeGuard[type[StandardDataclass]]: + # The dataclasses.is_dataclass function doesn't seem to provide TypeGuard functionality, + # so I created this convenience function + return dataclasses.is_dataclass(_cls) + + +def origin_is_type_alias_type(origin: Any) -> TypeGuard[TypeAliasType]: + return isinstance(origin, TypeAliasType) + + +if sys.version_info >= (3, 10): + + def is_generic_alias(type_: type[Any]) -> bool: + return isinstance(type_, (types.GenericAlias, typing._GenericAlias)) # type: ignore[attr-defined] + +else: + + def is_generic_alias(type_: type[Any]) -> bool: + return isinstance(type_, typing._GenericAlias) # type: ignore + + +def is_self_type(tp: Any) -> bool: + """Check if a given class is a Self type (from `typing` or `typing_extensions`)""" + return isinstance(tp, typing_base) and getattr(tp, '_name', None) == 'Self' diff --git a/env/Lib/site-packages/pydantic/_internal/_utils.py b/env/Lib/site-packages/pydantic/_internal/_utils.py new file mode 100644 index 0000000..de19243 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_utils.py @@ -0,0 +1,362 @@ +"""Bucket of reusable internal utilities. + +This should be reduced as much as possible with functions only used in one place, moved to that place. +""" + +from __future__ import annotations as _annotations + +import dataclasses +import keyword +import typing +import weakref +from collections import OrderedDict, defaultdict, deque +from copy import deepcopy +from itertools import zip_longest +from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType +from typing import Any, Mapping, TypeVar + +from typing_extensions import TypeAlias, TypeGuard + +from . import _repr, _typing_extra + +if typing.TYPE_CHECKING: + MappingIntStrAny: TypeAlias = 'typing.Mapping[int, Any] | typing.Mapping[str, Any]' + AbstractSetIntStr: TypeAlias = 'typing.AbstractSet[int] | typing.AbstractSet[str]' + from ..main import BaseModel + + +# these are types that are returned unchanged by deepcopy +IMMUTABLE_NON_COLLECTIONS_TYPES: set[type[Any]] = { + int, + float, + complex, + str, + bool, + bytes, + type, + _typing_extra.NoneType, + FunctionType, + BuiltinFunctionType, + LambdaType, + weakref.ref, + CodeType, + # note: including ModuleType will differ from behaviour of deepcopy by not producing error. + # It might be not a good idea in general, but considering that this function used only internally + # against default values of fields, this will allow to actually have a field with module as default value + ModuleType, + NotImplemented.__class__, + Ellipsis.__class__, +} + +# these are types that if empty, might be copied with simple copy() instead of deepcopy() +BUILTIN_COLLECTIONS: set[type[Any]] = { + list, + set, + tuple, + frozenset, + dict, + OrderedDict, + defaultdict, + deque, +} + + +def sequence_like(v: Any) -> bool: + return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque)) + + +def lenient_isinstance(o: Any, class_or_tuple: type[Any] | tuple[type[Any], ...] | None) -> bool: # pragma: no cover + try: + return isinstance(o, class_or_tuple) # type: ignore[arg-type] + except TypeError: + return False + + +def lenient_issubclass(cls: Any, class_or_tuple: Any) -> bool: # pragma: no cover + try: + return isinstance(cls, type) and issubclass(cls, class_or_tuple) + except TypeError: + if isinstance(cls, _typing_extra.WithArgsTypes): + return False + raise # pragma: no cover + + +def is_model_class(cls: Any) -> TypeGuard[type[BaseModel]]: + """Returns true if cls is a _proper_ subclass of BaseModel, and provides proper type-checking, + unlike raw calls to lenient_issubclass. + """ + from ..main import BaseModel + + return lenient_issubclass(cls, BaseModel) and cls is not BaseModel + + +def is_valid_identifier(identifier: str) -> bool: + """Checks that a string is a valid identifier and not a Python keyword. + :param identifier: The identifier to test. + :return: True if the identifier is valid. + """ + return identifier.isidentifier() and not keyword.iskeyword(identifier) + + +KeyType = TypeVar('KeyType') + + +def deep_update(mapping: dict[KeyType, Any], *updating_mappings: dict[KeyType, Any]) -> dict[KeyType, Any]: + updated_mapping = mapping.copy() + for updating_mapping in updating_mappings: + for k, v in updating_mapping.items(): + if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict): + updated_mapping[k] = deep_update(updated_mapping[k], v) + else: + updated_mapping[k] = v + return updated_mapping + + +def update_not_none(mapping: dict[Any, Any], **update: Any) -> None: + mapping.update({k: v for k, v in update.items() if v is not None}) + + +T = TypeVar('T') + + +def unique_list( + input_list: list[T] | tuple[T, ...], + *, + name_factory: typing.Callable[[T], str] = str, +) -> list[T]: + """Make a list unique while maintaining order. + We update the list if another one with the same name is set + (e.g. model validator overridden in subclass). + """ + result: list[T] = [] + result_names: list[str] = [] + for v in input_list: + v_name = name_factory(v) + if v_name not in result_names: + result_names.append(v_name) + result.append(v) + else: + result[result_names.index(v_name)] = v + + return result + + +class ValueItems(_repr.Representation): + """Class for more convenient calculation of excluded or included fields on values.""" + + __slots__ = ('_items', '_type') + + def __init__(self, value: Any, items: AbstractSetIntStr | MappingIntStrAny) -> None: + items = self._coerce_items(items) + + if isinstance(value, (list, tuple)): + items = self._normalize_indexes(items, len(value)) # type: ignore + + self._items: MappingIntStrAny = items # type: ignore + + def is_excluded(self, item: Any) -> bool: + """Check if item is fully excluded. + + :param item: key or index of a value + """ + return self.is_true(self._items.get(item)) + + def is_included(self, item: Any) -> bool: + """Check if value is contained in self._items. + + :param item: key or index of value + """ + return item in self._items + + def for_element(self, e: int | str) -> AbstractSetIntStr | MappingIntStrAny | None: + """:param e: key or index of element on value + :return: raw values for element if self._items is dict and contain needed element + """ + item = self._items.get(e) # type: ignore + return item if not self.is_true(item) else None + + def _normalize_indexes(self, items: MappingIntStrAny, v_length: int) -> dict[int | str, Any]: + """:param items: dict or set of indexes which will be normalized + :param v_length: length of sequence indexes of which will be + + >>> self._normalize_indexes({0: True, -2: True, -1: True}, 4) + {0: True, 2: True, 3: True} + >>> self._normalize_indexes({'__all__': True}, 4) + {0: True, 1: True, 2: True, 3: True} + """ + normalized_items: dict[int | str, Any] = {} + all_items = None + for i, v in items.items(): + if not (isinstance(v, typing.Mapping) or isinstance(v, typing.AbstractSet) or self.is_true(v)): + raise TypeError(f'Unexpected type of exclude value for index "{i}" {v.__class__}') + if i == '__all__': + all_items = self._coerce_value(v) + continue + if not isinstance(i, int): + raise TypeError( + 'Excluding fields from a sequence of sub-models or dicts must be performed index-wise: ' + 'expected integer keys or keyword "__all__"' + ) + normalized_i = v_length + i if i < 0 else i + normalized_items[normalized_i] = self.merge(v, normalized_items.get(normalized_i)) + + if not all_items: + return normalized_items + if self.is_true(all_items): + for i in range(v_length): + normalized_items.setdefault(i, ...) + return normalized_items + for i in range(v_length): + normalized_item = normalized_items.setdefault(i, {}) + if not self.is_true(normalized_item): + normalized_items[i] = self.merge(all_items, normalized_item) + return normalized_items + + @classmethod + def merge(cls, base: Any, override: Any, intersect: bool = False) -> Any: + """Merge a `base` item with an `override` item. + + Both `base` and `override` are converted to dictionaries if possible. + Sets are converted to dictionaries with the sets entries as keys and + Ellipsis as values. + + Each key-value pair existing in `base` is merged with `override`, + while the rest of the key-value pairs are updated recursively with this function. + + Merging takes place based on the "union" of keys if `intersect` is + set to `False` (default) and on the intersection of keys if + `intersect` is set to `True`. + """ + override = cls._coerce_value(override) + base = cls._coerce_value(base) + if override is None: + return base + if cls.is_true(base) or base is None: + return override + if cls.is_true(override): + return base if intersect else override + + # intersection or union of keys while preserving ordering: + if intersect: + merge_keys = [k for k in base if k in override] + [k for k in override if k in base] + else: + merge_keys = list(base) + [k for k in override if k not in base] + + merged: dict[int | str, Any] = {} + for k in merge_keys: + merged_item = cls.merge(base.get(k), override.get(k), intersect=intersect) + if merged_item is not None: + merged[k] = merged_item + + return merged + + @staticmethod + def _coerce_items(items: AbstractSetIntStr | MappingIntStrAny) -> MappingIntStrAny: + if isinstance(items, typing.Mapping): + pass + elif isinstance(items, typing.AbstractSet): + items = dict.fromkeys(items, ...) # type: ignore + else: + class_name = getattr(items, '__class__', '???') + raise TypeError(f'Unexpected type of exclude value {class_name}') + return items # type: ignore + + @classmethod + def _coerce_value(cls, value: Any) -> Any: + if value is None or cls.is_true(value): + return value + return cls._coerce_items(value) + + @staticmethod + def is_true(v: Any) -> bool: + return v is True or v is ... + + def __repr_args__(self) -> _repr.ReprArgs: + return [(None, self._items)] + + +if typing.TYPE_CHECKING: + + def ClassAttribute(name: str, value: T) -> T: ... + +else: + + class ClassAttribute: + """Hide class attribute from its instances.""" + + __slots__ = 'name', 'value' + + def __init__(self, name: str, value: Any) -> None: + self.name = name + self.value = value + + def __get__(self, instance: Any, owner: type[Any]) -> None: + if instance is None: + return self.value + raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only') + + +Obj = TypeVar('Obj') + + +def smart_deepcopy(obj: Obj) -> Obj: + """Return type as is for immutable built-in types + Use obj.copy() for built-in empty collections + Use copy.deepcopy() for non-empty collections and unknown objects. + """ + obj_type = obj.__class__ + if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES: + return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway + try: + if not obj and obj_type in BUILTIN_COLLECTIONS: + # faster way for empty collections, no need to copy its members + return obj if obj_type is tuple else obj.copy() # tuple doesn't have copy method # type: ignore + except (TypeError, ValueError, RuntimeError): + # do we really dare to catch ALL errors? Seems a bit risky + pass + + return deepcopy(obj) # slowest way when we actually might need a deepcopy + + +_SENTINEL = object() + + +def all_identical(left: typing.Iterable[Any], right: typing.Iterable[Any]) -> bool: + """Check that the items of `left` are the same objects as those in `right`. + + >>> a, b = object(), object() + >>> all_identical([a, b, a], [a, b, a]) + True + >>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical" + False + """ + for left_item, right_item in zip_longest(left, right, fillvalue=_SENTINEL): + if left_item is not right_item: + return False + return True + + +@dataclasses.dataclass(frozen=True) +class SafeGetItemProxy: + """Wrapper redirecting `__getitem__` to `get` with a sentinel value as default + + This makes is safe to use in `operator.itemgetter` when some keys may be missing + """ + + # Define __slots__manually for performances + # @dataclasses.dataclass() only support slots=True in python>=3.10 + __slots__ = ('wrapped',) + + wrapped: Mapping[str, Any] + + def __getitem__(self, key: str, /) -> Any: + return self.wrapped.get(key, _SENTINEL) + + # required to pass the object to operator.itemgetter() instances due to a quirk of typeshed + # https://github.com/python/mypy/issues/13713 + # https://github.com/python/typeshed/pull/8785 + # Since this is typing-only, hide it in a typing.TYPE_CHECKING block + if typing.TYPE_CHECKING: + + def __contains__(self, key: str, /) -> bool: + return self.wrapped.__contains__(key) diff --git a/env/Lib/site-packages/pydantic/_internal/_validate_call.py b/env/Lib/site-packages/pydantic/_internal/_validate_call.py new file mode 100644 index 0000000..3fae2d1 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_validate_call.py @@ -0,0 +1,99 @@ +from __future__ import annotations as _annotations + +import inspect +from functools import partial +from typing import Any, Awaitable, Callable + +import pydantic_core + +from ..config import ConfigDict +from ..plugin._schema_validator import create_schema_validator +from . import _generate_schema, _typing_extra +from ._config import ConfigWrapper + + +class ValidateCallWrapper: + """This is a wrapper around a function that validates the arguments passed to it, and optionally the return value.""" + + __slots__ = ( + '__pydantic_validator__', + '__name__', + '__qualname__', + '__annotations__', + '__dict__', # required for __module__ + ) + + def __init__( + self, + function: Callable[..., Any], + config: ConfigDict | None, + validate_return: bool, + namespace: dict[str, Any] | None, + ): + if isinstance(function, partial): + func = function.func + schema_type = func + self.__name__ = f'partial({func.__name__})' + self.__qualname__ = f'partial({func.__qualname__})' + self.__module__ = func.__module__ + else: + schema_type = function + self.__name__ = function.__name__ + self.__qualname__ = function.__qualname__ + self.__module__ = function.__module__ + + global_ns = _typing_extra.add_module_globals(function, None) + # TODO: this is a bit of a hack, we should probably have a better way to handle this + # specifically, we shouldn't be pumping the namespace full of type_params + # when we take namespace and type_params arguments in eval_type_backport + type_params = getattr(schema_type, '__type_params__', ()) + namespace = { + **{param.__name__: param for param in type_params}, + **(global_ns or {}), + **(namespace or {}), + } + config_wrapper = ConfigWrapper(config) + gen_schema = _generate_schema.GenerateSchema(config_wrapper, namespace) + schema = gen_schema.clean_schema(gen_schema.generate_schema(function)) + core_config = config_wrapper.core_config(self) + + self.__pydantic_validator__ = create_schema_validator( + schema, + schema_type, + self.__module__, + self.__qualname__, + 'validate_call', + core_config, + config_wrapper.plugin_settings, + ) + + if validate_return: + signature = inspect.signature(function) + return_type = signature.return_annotation if signature.return_annotation is not signature.empty else Any + gen_schema = _generate_schema.GenerateSchema(config_wrapper, namespace) + schema = gen_schema.clean_schema(gen_schema.generate_schema(return_type)) + validator = create_schema_validator( + schema, + schema_type, + self.__module__, + self.__qualname__, + 'validate_call', + core_config, + config_wrapper.plugin_settings, + ) + if inspect.iscoroutinefunction(function): + + async def return_val_wrapper(aw: Awaitable[Any]) -> None: + return validator.validate_python(await aw) + + self.__return_pydantic_validator__ = return_val_wrapper + else: + self.__return_pydantic_validator__ = validator.validate_python + else: + self.__return_pydantic_validator__ = None + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + res = self.__pydantic_validator__.validate_python(pydantic_core.ArgsKwargs(args, kwargs)) + if self.__return_pydantic_validator__: + return self.__return_pydantic_validator__(res) + return res diff --git a/env/Lib/site-packages/pydantic/_internal/_validators.py b/env/Lib/site-packages/pydantic/_internal/_validators.py new file mode 100644 index 0000000..870b536 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_internal/_validators.py @@ -0,0 +1,308 @@ +"""Validator functions for standard library types. + +Import of this module is deferred since it contains imports of many standard library modules. +""" + +from __future__ import annotations as _annotations + +import math +import re +import typing +from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network +from typing import Any, Callable + +from pydantic_core import PydanticCustomError, core_schema +from pydantic_core._pydantic_core import PydanticKnownError + + +def sequence_validator( + input_value: typing.Sequence[Any], + /, + validator: core_schema.ValidatorFunctionWrapHandler, +) -> typing.Sequence[Any]: + """Validator for `Sequence` types, isinstance(v, Sequence) has already been called.""" + value_type = type(input_value) + + # We don't accept any plain string as a sequence + # Relevant issue: https://github.com/pydantic/pydantic/issues/5595 + if issubclass(value_type, (str, bytes)): + raise PydanticCustomError( + 'sequence_str', + "'{type_name}' instances are not allowed as a Sequence value", + {'type_name': value_type.__name__}, + ) + + # TODO: refactor sequence validation to validate with either a list or a tuple + # schema, depending on the type of the value. + # Additionally, we should be able to remove one of either this validator or the + # SequenceValidator in _std_types_schema.py (preferably this one, while porting over some logic). + # Effectively, a refactor for sequence validation is needed. + if value_type is tuple: + input_value = list(input_value) + + v_list = validator(input_value) + + # the rest of the logic is just re-creating the original type from `v_list` + if value_type is list: + return v_list + elif issubclass(value_type, range): + # return the list as we probably can't re-create the range + return v_list + elif value_type is tuple: + return tuple(v_list) + else: + # best guess at how to re-create the original type, more custom construction logic might be required + return value_type(v_list) # type: ignore[call-arg] + + +def import_string(value: Any) -> Any: + if isinstance(value, str): + try: + return _import_string_logic(value) + except ImportError as e: + raise PydanticCustomError('import_error', 'Invalid python path: {error}', {'error': str(e)}) from e + else: + # otherwise we just return the value and let the next validator do the rest of the work + return value + + +def _import_string_logic(dotted_path: str) -> Any: + """Inspired by uvicorn — dotted paths should include a colon before the final item if that item is not a module. + (This is necessary to distinguish between a submodule and an attribute when there is a conflict.). + + If the dotted path does not include a colon and the final item is not a valid module, importing as an attribute + rather than a submodule will be attempted automatically. + + So, for example, the following values of `dotted_path` result in the following returned values: + * 'collections': + * 'collections.abc': + * 'collections.abc:Mapping': + * `collections.abc.Mapping`: (though this is a bit slower than the previous line) + + An error will be raised under any of the following scenarios: + * `dotted_path` contains more than one colon (e.g., 'collections:abc:Mapping') + * the substring of `dotted_path` before the colon is not a valid module in the environment (e.g., '123:Mapping') + * the substring of `dotted_path` after the colon is not an attribute of the module (e.g., 'collections:abc123') + """ + from importlib import import_module + + components = dotted_path.strip().split(':') + if len(components) > 2: + raise ImportError(f"Import strings should have at most one ':'; received {dotted_path!r}") + + module_path = components[0] + if not module_path: + raise ImportError(f'Import strings should have a nonempty module name; received {dotted_path!r}') + + try: + module = import_module(module_path) + except ModuleNotFoundError as e: + if '.' in module_path: + # Check if it would be valid if the final item was separated from its module with a `:` + maybe_module_path, maybe_attribute = dotted_path.strip().rsplit('.', 1) + try: + return _import_string_logic(f'{maybe_module_path}:{maybe_attribute}') + except ImportError: + pass + raise ImportError(f'No module named {module_path!r}') from e + raise e + + if len(components) > 1: + attribute = components[1] + try: + return getattr(module, attribute) + except AttributeError as e: + raise ImportError(f'cannot import name {attribute!r} from {module_path!r}') from e + else: + return module + + +def pattern_either_validator(input_value: Any, /) -> typing.Pattern[Any]: + if isinstance(input_value, typing.Pattern): + return input_value + elif isinstance(input_value, (str, bytes)): + # todo strict mode + return compile_pattern(input_value) # type: ignore + else: + raise PydanticCustomError('pattern_type', 'Input should be a valid pattern') + + +def pattern_str_validator(input_value: Any, /) -> typing.Pattern[str]: + if isinstance(input_value, typing.Pattern): + if isinstance(input_value.pattern, str): + return input_value + else: + raise PydanticCustomError('pattern_str_type', 'Input should be a string pattern') + elif isinstance(input_value, str): + return compile_pattern(input_value) + elif isinstance(input_value, bytes): + raise PydanticCustomError('pattern_str_type', 'Input should be a string pattern') + else: + raise PydanticCustomError('pattern_type', 'Input should be a valid pattern') + + +def pattern_bytes_validator(input_value: Any, /) -> typing.Pattern[bytes]: + if isinstance(input_value, typing.Pattern): + if isinstance(input_value.pattern, bytes): + return input_value + else: + raise PydanticCustomError('pattern_bytes_type', 'Input should be a bytes pattern') + elif isinstance(input_value, bytes): + return compile_pattern(input_value) + elif isinstance(input_value, str): + raise PydanticCustomError('pattern_bytes_type', 'Input should be a bytes pattern') + else: + raise PydanticCustomError('pattern_type', 'Input should be a valid pattern') + + +PatternType = typing.TypeVar('PatternType', str, bytes) + + +def compile_pattern(pattern: PatternType) -> typing.Pattern[PatternType]: + try: + return re.compile(pattern) + except re.error: + raise PydanticCustomError('pattern_regex', 'Input should be a valid regular expression') + + +def ip_v4_address_validator(input_value: Any, /) -> IPv4Address: + if isinstance(input_value, IPv4Address): + return input_value + + try: + return IPv4Address(input_value) + except ValueError: + raise PydanticCustomError('ip_v4_address', 'Input is not a valid IPv4 address') + + +def ip_v6_address_validator(input_value: Any, /) -> IPv6Address: + if isinstance(input_value, IPv6Address): + return input_value + + try: + return IPv6Address(input_value) + except ValueError: + raise PydanticCustomError('ip_v6_address', 'Input is not a valid IPv6 address') + + +def ip_v4_network_validator(input_value: Any, /) -> IPv4Network: + """Assume IPv4Network initialised with a default `strict` argument. + + See more: + https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network + """ + if isinstance(input_value, IPv4Network): + return input_value + + try: + return IPv4Network(input_value) + except ValueError: + raise PydanticCustomError('ip_v4_network', 'Input is not a valid IPv4 network') + + +def ip_v6_network_validator(input_value: Any, /) -> IPv6Network: + """Assume IPv6Network initialised with a default `strict` argument. + + See more: + https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network + """ + if isinstance(input_value, IPv6Network): + return input_value + + try: + return IPv6Network(input_value) + except ValueError: + raise PydanticCustomError('ip_v6_network', 'Input is not a valid IPv6 network') + + +def ip_v4_interface_validator(input_value: Any, /) -> IPv4Interface: + if isinstance(input_value, IPv4Interface): + return input_value + + try: + return IPv4Interface(input_value) + except ValueError: + raise PydanticCustomError('ip_v4_interface', 'Input is not a valid IPv4 interface') + + +def ip_v6_interface_validator(input_value: Any, /) -> IPv6Interface: + if isinstance(input_value, IPv6Interface): + return input_value + + try: + return IPv6Interface(input_value) + except ValueError: + raise PydanticCustomError('ip_v6_interface', 'Input is not a valid IPv6 interface') + + +def greater_than_validator(x: Any, gt: Any) -> Any: + if not (x > gt): + raise PydanticKnownError('greater_than', {'gt': gt}) + return x + + +def greater_than_or_equal_validator(x: Any, ge: Any) -> Any: + if not (x >= ge): + raise PydanticKnownError('greater_than_equal', {'ge': ge}) + return x + + +def less_than_validator(x: Any, lt: Any) -> Any: + if not (x < lt): + raise PydanticKnownError('less_than', {'lt': lt}) + return x + + +def less_than_or_equal_validator(x: Any, le: Any) -> Any: + if not (x <= le): + raise PydanticKnownError('less_than_equal', {'le': le}) + return x + + +def multiple_of_validator(x: Any, multiple_of: Any) -> Any: + if not (x % multiple_of == 0): + raise PydanticKnownError('multiple_of', {'multiple_of': multiple_of}) + return x + + +def min_length_validator(x: Any, min_length: Any) -> Any: + if not (len(x) >= min_length): + raise PydanticKnownError( + 'too_short', + {'field_type': 'Value', 'min_length': min_length, 'actual_length': len(x)}, + ) + return x + + +def max_length_validator(x: Any, max_length: Any) -> Any: + if len(x) > max_length: + raise PydanticKnownError( + 'too_long', + {'field_type': 'Value', 'max_length': max_length, 'actual_length': len(x)}, + ) + return x + + +def forbid_inf_nan_check(x: Any) -> Any: + if not math.isfinite(x): + raise PydanticKnownError('finite_number') + return x + + +_CONSTRAINT_TO_VALIDATOR_MAP: dict[str, Callable] = { + 'gt': greater_than_validator, + 'ge': greater_than_or_equal_validator, + 'lt': less_than_validator, + 'le': less_than_or_equal_validator, + 'multiple_of': multiple_of_validator, + 'min_length': min_length_validator, + 'max_length': max_length_validator, +} + + +def get_constraint_validator(constraint: str) -> Callable: + """Fetch the validator function for the given constraint.""" + try: + return _CONSTRAINT_TO_VALIDATOR_MAP[constraint] + except KeyError: + raise TypeError(f'Unknown constraint {constraint}') diff --git a/env/Lib/site-packages/pydantic/_migration.py b/env/Lib/site-packages/pydantic/_migration.py new file mode 100644 index 0000000..c8478a6 --- /dev/null +++ b/env/Lib/site-packages/pydantic/_migration.py @@ -0,0 +1,308 @@ +import sys +from typing import Any, Callable, Dict + +from .version import version_short + +MOVED_IN_V2 = { + 'pydantic.utils:version_info': 'pydantic.version:version_info', + 'pydantic.error_wrappers:ValidationError': 'pydantic:ValidationError', + 'pydantic.utils:to_camel': 'pydantic.alias_generators:to_pascal', + 'pydantic.utils:to_lower_camel': 'pydantic.alias_generators:to_camel', + 'pydantic:PyObject': 'pydantic.types:ImportString', + 'pydantic.types:PyObject': 'pydantic.types:ImportString', + 'pydantic.generics:GenericModel': 'pydantic.BaseModel', +} + +DEPRECATED_MOVED_IN_V2 = { + 'pydantic.tools:schema_of': 'pydantic.deprecated.tools:schema_of', + 'pydantic.tools:parse_obj_as': 'pydantic.deprecated.tools:parse_obj_as', + 'pydantic.tools:schema_json_of': 'pydantic.deprecated.tools:schema_json_of', + 'pydantic.json:pydantic_encoder': 'pydantic.deprecated.json:pydantic_encoder', + 'pydantic:validate_arguments': 'pydantic.deprecated.decorator:validate_arguments', + 'pydantic.json:custom_pydantic_encoder': 'pydantic.deprecated.json:custom_pydantic_encoder', + 'pydantic.json:timedelta_isoformat': 'pydantic.deprecated.json:timedelta_isoformat', + 'pydantic.decorator:validate_arguments': 'pydantic.deprecated.decorator:validate_arguments', + 'pydantic.class_validators:validator': 'pydantic.deprecated.class_validators:validator', + 'pydantic.class_validators:root_validator': 'pydantic.deprecated.class_validators:root_validator', + 'pydantic.config:BaseConfig': 'pydantic.deprecated.config:BaseConfig', + 'pydantic.config:Extra': 'pydantic.deprecated.config:Extra', +} + +REDIRECT_TO_V1 = { + f'pydantic.utils:{obj}': f'pydantic.v1.utils:{obj}' + for obj in ( + 'deep_update', + 'GetterDict', + 'lenient_issubclass', + 'lenient_isinstance', + 'is_valid_field', + 'update_not_none', + 'import_string', + 'Representation', + 'ROOT_KEY', + 'smart_deepcopy', + 'sequence_like', + ) +} + + +REMOVED_IN_V2 = { + 'pydantic:ConstrainedBytes', + 'pydantic:ConstrainedDate', + 'pydantic:ConstrainedDecimal', + 'pydantic:ConstrainedFloat', + 'pydantic:ConstrainedFrozenSet', + 'pydantic:ConstrainedInt', + 'pydantic:ConstrainedList', + 'pydantic:ConstrainedSet', + 'pydantic:ConstrainedStr', + 'pydantic:JsonWrapper', + 'pydantic:NoneBytes', + 'pydantic:NoneStr', + 'pydantic:NoneStrBytes', + 'pydantic:Protocol', + 'pydantic:Required', + 'pydantic:StrBytes', + 'pydantic:compiled', + 'pydantic.config:get_config', + 'pydantic.config:inherit_config', + 'pydantic.config:prepare_config', + 'pydantic:create_model_from_namedtuple', + 'pydantic:create_model_from_typeddict', + 'pydantic.dataclasses:create_pydantic_model_from_dataclass', + 'pydantic.dataclasses:make_dataclass_validator', + 'pydantic.dataclasses:set_validation', + 'pydantic.datetime_parse:parse_date', + 'pydantic.datetime_parse:parse_time', + 'pydantic.datetime_parse:parse_datetime', + 'pydantic.datetime_parse:parse_duration', + 'pydantic.error_wrappers:ErrorWrapper', + 'pydantic.errors:AnyStrMaxLengthError', + 'pydantic.errors:AnyStrMinLengthError', + 'pydantic.errors:ArbitraryTypeError', + 'pydantic.errors:BoolError', + 'pydantic.errors:BytesError', + 'pydantic.errors:CallableError', + 'pydantic.errors:ClassError', + 'pydantic.errors:ColorError', + 'pydantic.errors:ConfigError', + 'pydantic.errors:DataclassTypeError', + 'pydantic.errors:DateError', + 'pydantic.errors:DateNotInTheFutureError', + 'pydantic.errors:DateNotInThePastError', + 'pydantic.errors:DateTimeError', + 'pydantic.errors:DecimalError', + 'pydantic.errors:DecimalIsNotFiniteError', + 'pydantic.errors:DecimalMaxDigitsError', + 'pydantic.errors:DecimalMaxPlacesError', + 'pydantic.errors:DecimalWholeDigitsError', + 'pydantic.errors:DictError', + 'pydantic.errors:DurationError', + 'pydantic.errors:EmailError', + 'pydantic.errors:EnumError', + 'pydantic.errors:EnumMemberError', + 'pydantic.errors:ExtraError', + 'pydantic.errors:FloatError', + 'pydantic.errors:FrozenSetError', + 'pydantic.errors:FrozenSetMaxLengthError', + 'pydantic.errors:FrozenSetMinLengthError', + 'pydantic.errors:HashableError', + 'pydantic.errors:IPv4AddressError', + 'pydantic.errors:IPv4InterfaceError', + 'pydantic.errors:IPv4NetworkError', + 'pydantic.errors:IPv6AddressError', + 'pydantic.errors:IPv6InterfaceError', + 'pydantic.errors:IPv6NetworkError', + 'pydantic.errors:IPvAnyAddressError', + 'pydantic.errors:IPvAnyInterfaceError', + 'pydantic.errors:IPvAnyNetworkError', + 'pydantic.errors:IntEnumError', + 'pydantic.errors:IntegerError', + 'pydantic.errors:InvalidByteSize', + 'pydantic.errors:InvalidByteSizeUnit', + 'pydantic.errors:InvalidDiscriminator', + 'pydantic.errors:InvalidLengthForBrand', + 'pydantic.errors:JsonError', + 'pydantic.errors:JsonTypeError', + 'pydantic.errors:ListError', + 'pydantic.errors:ListMaxLengthError', + 'pydantic.errors:ListMinLengthError', + 'pydantic.errors:ListUniqueItemsError', + 'pydantic.errors:LuhnValidationError', + 'pydantic.errors:MissingDiscriminator', + 'pydantic.errors:MissingError', + 'pydantic.errors:NoneIsAllowedError', + 'pydantic.errors:NoneIsNotAllowedError', + 'pydantic.errors:NotDigitError', + 'pydantic.errors:NotNoneError', + 'pydantic.errors:NumberNotGeError', + 'pydantic.errors:NumberNotGtError', + 'pydantic.errors:NumberNotLeError', + 'pydantic.errors:NumberNotLtError', + 'pydantic.errors:NumberNotMultipleError', + 'pydantic.errors:PathError', + 'pydantic.errors:PathNotADirectoryError', + 'pydantic.errors:PathNotAFileError', + 'pydantic.errors:PathNotExistsError', + 'pydantic.errors:PatternError', + 'pydantic.errors:PyObjectError', + 'pydantic.errors:PydanticTypeError', + 'pydantic.errors:PydanticValueError', + 'pydantic.errors:SequenceError', + 'pydantic.errors:SetError', + 'pydantic.errors:SetMaxLengthError', + 'pydantic.errors:SetMinLengthError', + 'pydantic.errors:StrError', + 'pydantic.errors:StrRegexError', + 'pydantic.errors:StrictBoolError', + 'pydantic.errors:SubclassError', + 'pydantic.errors:TimeError', + 'pydantic.errors:TupleError', + 'pydantic.errors:TupleLengthError', + 'pydantic.errors:UUIDError', + 'pydantic.errors:UUIDVersionError', + 'pydantic.errors:UrlError', + 'pydantic.errors:UrlExtraError', + 'pydantic.errors:UrlHostError', + 'pydantic.errors:UrlHostTldError', + 'pydantic.errors:UrlPortError', + 'pydantic.errors:UrlSchemeError', + 'pydantic.errors:UrlSchemePermittedError', + 'pydantic.errors:UrlUserInfoError', + 'pydantic.errors:WrongConstantError', + 'pydantic.main:validate_model', + 'pydantic.networks:stricturl', + 'pydantic:parse_file_as', + 'pydantic:parse_raw_as', + 'pydantic:stricturl', + 'pydantic.tools:parse_file_as', + 'pydantic.tools:parse_raw_as', + 'pydantic.types:ConstrainedBytes', + 'pydantic.types:ConstrainedDate', + 'pydantic.types:ConstrainedDecimal', + 'pydantic.types:ConstrainedFloat', + 'pydantic.types:ConstrainedFrozenSet', + 'pydantic.types:ConstrainedInt', + 'pydantic.types:ConstrainedList', + 'pydantic.types:ConstrainedSet', + 'pydantic.types:ConstrainedStr', + 'pydantic.types:JsonWrapper', + 'pydantic.types:NoneBytes', + 'pydantic.types:NoneStr', + 'pydantic.types:NoneStrBytes', + 'pydantic.types:StrBytes', + 'pydantic.typing:evaluate_forwardref', + 'pydantic.typing:AbstractSetIntStr', + 'pydantic.typing:AnyCallable', + 'pydantic.typing:AnyClassMethod', + 'pydantic.typing:CallableGenerator', + 'pydantic.typing:DictAny', + 'pydantic.typing:DictIntStrAny', + 'pydantic.typing:DictStrAny', + 'pydantic.typing:IntStr', + 'pydantic.typing:ListStr', + 'pydantic.typing:MappingIntStrAny', + 'pydantic.typing:NoArgAnyCallable', + 'pydantic.typing:NoneType', + 'pydantic.typing:ReprArgs', + 'pydantic.typing:SetStr', + 'pydantic.typing:StrPath', + 'pydantic.typing:TupleGenerator', + 'pydantic.typing:WithArgsTypes', + 'pydantic.typing:all_literal_values', + 'pydantic.typing:display_as_type', + 'pydantic.typing:get_all_type_hints', + 'pydantic.typing:get_args', + 'pydantic.typing:get_origin', + 'pydantic.typing:get_sub_types', + 'pydantic.typing:is_callable_type', + 'pydantic.typing:is_classvar', + 'pydantic.typing:is_finalvar', + 'pydantic.typing:is_literal_type', + 'pydantic.typing:is_namedtuple', + 'pydantic.typing:is_new_type', + 'pydantic.typing:is_none_type', + 'pydantic.typing:is_typeddict', + 'pydantic.typing:is_typeddict_special', + 'pydantic.typing:is_union', + 'pydantic.typing:new_type_supertype', + 'pydantic.typing:resolve_annotations', + 'pydantic.typing:typing_base', + 'pydantic.typing:update_field_forward_refs', + 'pydantic.typing:update_model_forward_refs', + 'pydantic.utils:ClassAttribute', + 'pydantic.utils:DUNDER_ATTRIBUTES', + 'pydantic.utils:PyObjectStr', + 'pydantic.utils:ValueItems', + 'pydantic.utils:almost_equal_floats', + 'pydantic.utils:get_discriminator_alias_and_values', + 'pydantic.utils:get_model', + 'pydantic.utils:get_unique_discriminator_alias', + 'pydantic.utils:in_ipython', + 'pydantic.utils:is_valid_identifier', + 'pydantic.utils:path_type', + 'pydantic.utils:validate_field_name', + 'pydantic:validate_model', +} + + +def getattr_migration(module: str) -> Callable[[str], Any]: + """Implement PEP 562 for objects that were either moved or removed on the migration + to V2. + + Args: + module: The module name. + + Returns: + A callable that will raise an error if the object is not found. + """ + # This avoids circular import with errors.py. + from .errors import PydanticImportError + + def wrapper(name: str) -> object: + """Raise an error if the object is not found, or warn if it was moved. + + In case it was moved, it still returns the object. + + Args: + name: The object name. + + Returns: + The object. + """ + if name == '__path__': + raise AttributeError(f'module {module!r} has no attribute {name!r}') + + import warnings + + from ._internal._validators import import_string + + import_path = f'{module}:{name}' + if import_path in MOVED_IN_V2.keys(): + new_location = MOVED_IN_V2[import_path] + warnings.warn(f'`{import_path}` has been moved to `{new_location}`.') + return import_string(MOVED_IN_V2[import_path]) + if import_path in DEPRECATED_MOVED_IN_V2: + # skip the warning here because a deprecation warning will be raised elsewhere + return import_string(DEPRECATED_MOVED_IN_V2[import_path]) + if import_path in REDIRECT_TO_V1: + new_location = REDIRECT_TO_V1[import_path] + warnings.warn( + f'`{import_path}` has been removed. We are importing from `{new_location}` instead.' + 'See the migration guide for more details: https://docs.pydantic.dev/latest/migration/' + ) + return import_string(REDIRECT_TO_V1[import_path]) + if import_path == 'pydantic:BaseSettings': + raise PydanticImportError( + '`BaseSettings` has been moved to the `pydantic-settings` package. ' + f'See https://docs.pydantic.dev/{version_short()}/migration/#basesettings-has-moved-to-pydantic-settings ' + 'for more details.' + ) + if import_path in REMOVED_IN_V2: + raise PydanticImportError(f'`{import_path}` has been removed in V2.') + globals: Dict[str, Any] = sys.modules[module].__dict__ + if name in globals: + return globals[name] + raise AttributeError(f'module {module!r} has no attribute {name!r}') + + return wrapper diff --git a/env/Lib/site-packages/pydantic/alias_generators.py b/env/Lib/site-packages/pydantic/alias_generators.py new file mode 100644 index 0000000..0b7653f --- /dev/null +++ b/env/Lib/site-packages/pydantic/alias_generators.py @@ -0,0 +1,62 @@ +"""Alias generators for converting between different capitalization conventions.""" + +import re + +__all__ = ('to_pascal', 'to_camel', 'to_snake') + +# TODO: in V3, change the argument names to be more descriptive +# Generally, don't only convert from snake_case, or name the functions +# more specifically like snake_to_camel. + + +def to_pascal(snake: str) -> str: + """Convert a snake_case string to PascalCase. + + Args: + snake: The string to convert. + + Returns: + The PascalCase string. + """ + camel = snake.title() + return re.sub('([0-9A-Za-z])_(?=[0-9A-Z])', lambda m: m.group(1), camel) + + +def to_camel(snake: str) -> str: + """Convert a snake_case string to camelCase. + + Args: + snake: The string to convert. + + Returns: + The converted camelCase string. + """ + # If the string is already in camelCase and does not contain a digit followed + # by a lowercase letter, return it as it is + if re.match('^[a-z]+[A-Za-z0-9]*$', snake) and not re.search(r'\d[a-z]', snake): + return snake + + camel = to_pascal(snake) + return re.sub('(^_*[A-Z])', lambda m: m.group(1).lower(), camel) + + +def to_snake(camel: str) -> str: + """Convert a PascalCase, camelCase, or kebab-case string to snake_case. + + Args: + camel: The string to convert. + + Returns: + The converted string in snake_case. + """ + # Handle the sequence of uppercase letters followed by a lowercase letter + snake = re.sub(r'([A-Z]+)([A-Z][a-z])', lambda m: f'{m.group(1)}_{m.group(2)}', camel) + # Insert an underscore between a lowercase letter and an uppercase letter + snake = re.sub(r'([a-z])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake) + # Insert an underscore between a digit and an uppercase letter + snake = re.sub(r'([0-9])([A-Z])', lambda m: f'{m.group(1)}_{m.group(2)}', snake) + # Insert an underscore between a lowercase letter and a digit + snake = re.sub(r'([a-z])([0-9])', lambda m: f'{m.group(1)}_{m.group(2)}', snake) + # Replace hyphens with underscores to handle kebab-case + snake = snake.replace('-', '_') + return snake.lower() diff --git a/env/Lib/site-packages/pydantic/aliases.py b/env/Lib/site-packages/pydantic/aliases.py new file mode 100644 index 0000000..441fee1 --- /dev/null +++ b/env/Lib/site-packages/pydantic/aliases.py @@ -0,0 +1,132 @@ +"""Support for alias configurations.""" + +from __future__ import annotations + +import dataclasses +from typing import Any, Callable, Literal + +from pydantic_core import PydanticUndefined + +from ._internal import _internal_dataclass + +__all__ = ('AliasGenerator', 'AliasPath', 'AliasChoices') + + +@dataclasses.dataclass(**_internal_dataclass.slots_true) +class AliasPath: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/alias#aliaspath-and-aliaschoices + + A data class used by `validation_alias` as a convenience to create aliases. + + Attributes: + path: A list of string or integer aliases. + """ + + path: list[int | str] + + def __init__(self, first_arg: str, *args: str | int) -> None: + self.path = [first_arg] + list(args) + + def convert_to_aliases(self) -> list[str | int]: + """Converts arguments to a list of string or integer aliases. + + Returns: + The list of aliases. + """ + return self.path + + def search_dict_for_path(self, d: dict) -> Any: + """Searches a dictionary for the path specified by the alias. + + Returns: + The value at the specified path, or `PydanticUndefined` if the path is not found. + """ + v = d + for k in self.path: + if isinstance(v, str): + # disallow indexing into a str, like for AliasPath('x', 0) and x='abc' + return PydanticUndefined + try: + v = v[k] + except (KeyError, IndexError, TypeError): + return PydanticUndefined + return v + + +@dataclasses.dataclass(**_internal_dataclass.slots_true) +class AliasChoices: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/alias#aliaspath-and-aliaschoices + + A data class used by `validation_alias` as a convenience to create aliases. + + Attributes: + choices: A list containing a string or `AliasPath`. + """ + + choices: list[str | AliasPath] + + def __init__(self, first_choice: str | AliasPath, *choices: str | AliasPath) -> None: + self.choices = [first_choice] + list(choices) + + def convert_to_aliases(self) -> list[list[str | int]]: + """Converts arguments to a list of lists containing string or integer aliases. + + Returns: + The list of aliases. + """ + aliases: list[list[str | int]] = [] + for c in self.choices: + if isinstance(c, AliasPath): + aliases.append(c.convert_to_aliases()) + else: + aliases.append([c]) + return aliases + + +@dataclasses.dataclass(**_internal_dataclass.slots_true) +class AliasGenerator: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/alias#using-an-aliasgenerator + + A data class used by `alias_generator` as a convenience to create various aliases. + + Attributes: + alias: A callable that takes a field name and returns an alias for it. + validation_alias: A callable that takes a field name and returns a validation alias for it. + serialization_alias: A callable that takes a field name and returns a serialization alias for it. + """ + + alias: Callable[[str], str] | None = None + validation_alias: Callable[[str], str | AliasPath | AliasChoices] | None = None + serialization_alias: Callable[[str], str] | None = None + + def _generate_alias( + self, + alias_kind: Literal['alias', 'validation_alias', 'serialization_alias'], + allowed_types: tuple[type[str] | type[AliasPath] | type[AliasChoices], ...], + field_name: str, + ) -> str | AliasPath | AliasChoices | None: + """Generate an alias of the specified kind. Returns None if the alias generator is None. + + Raises: + TypeError: If the alias generator produces an invalid type. + """ + alias = None + if alias_generator := getattr(self, alias_kind): + alias = alias_generator(field_name) + if alias and not isinstance(alias, allowed_types): + raise TypeError( + f'Invalid `{alias_kind}` type. `{alias_kind}` generator must produce one of `{allowed_types}`' + ) + return alias + + def generate_aliases(self, field_name: str) -> tuple[str | None, str | AliasPath | AliasChoices | None, str | None]: + """Generate `alias`, `validation_alias`, and `serialization_alias` for a field. + + Returns: + A tuple of three aliases - validation, alias, and serialization. + """ + alias = self._generate_alias('alias', (str,), field_name) + validation_alias = self._generate_alias('validation_alias', (str, AliasChoices, AliasPath), field_name) + serialization_alias = self._generate_alias('serialization_alias', (str,), field_name) + + return alias, validation_alias, serialization_alias # type: ignore diff --git a/env/Lib/site-packages/pydantic/annotated_handlers.py b/env/Lib/site-packages/pydantic/annotated_handlers.py new file mode 100644 index 0000000..ac3d213 --- /dev/null +++ b/env/Lib/site-packages/pydantic/annotated_handlers.py @@ -0,0 +1,121 @@ +"""Type annotations to use with `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__`.""" + +from __future__ import annotations as _annotations + +from typing import TYPE_CHECKING, Any, Union + +from pydantic_core import core_schema + +if TYPE_CHECKING: + from .json_schema import JsonSchemaMode, JsonSchemaValue + + CoreSchemaOrField = Union[ + core_schema.CoreSchema, + core_schema.ModelField, + core_schema.DataclassField, + core_schema.TypedDictField, + core_schema.ComputedField, + ] + +__all__ = 'GetJsonSchemaHandler', 'GetCoreSchemaHandler' + + +class GetJsonSchemaHandler: + """Handler to call into the next JSON schema generation function. + + Attributes: + mode: Json schema mode, can be `validation` or `serialization`. + """ + + mode: JsonSchemaMode + + def __call__(self, core_schema: CoreSchemaOrField, /) -> JsonSchemaValue: + """Call the inner handler and get the JsonSchemaValue it returns. + This will call the next JSON schema modifying function up until it calls + into `pydantic.json_schema.GenerateJsonSchema`, which will raise a + `pydantic.errors.PydanticInvalidForJsonSchema` error if it cannot generate + a JSON schema. + + Args: + core_schema: A `pydantic_core.core_schema.CoreSchema`. + + Returns: + JsonSchemaValue: The JSON schema generated by the inner JSON schema modify + functions. + """ + raise NotImplementedError + + def resolve_ref_schema(self, maybe_ref_json_schema: JsonSchemaValue, /) -> JsonSchemaValue: + """Get the real schema for a `{"$ref": ...}` schema. + If the schema given is not a `$ref` schema, it will be returned as is. + This means you don't have to check before calling this function. + + Args: + maybe_ref_json_schema: A JsonSchemaValue which may be a `$ref` schema. + + Raises: + LookupError: If the ref is not found. + + Returns: + JsonSchemaValue: A JsonSchemaValue that has no `$ref`. + """ + raise NotImplementedError + + +class GetCoreSchemaHandler: + """Handler to call into the next CoreSchema schema generation function.""" + + def __call__(self, source_type: Any, /) -> core_schema.CoreSchema: + """Call the inner handler and get the CoreSchema it returns. + This will call the next CoreSchema modifying function up until it calls + into Pydantic's internal schema generation machinery, which will raise a + `pydantic.errors.PydanticSchemaGenerationError` error if it cannot generate + a CoreSchema for the given source type. + + Args: + source_type: The input type. + + Returns: + CoreSchema: The `pydantic-core` CoreSchema generated. + """ + raise NotImplementedError + + def generate_schema(self, source_type: Any, /) -> core_schema.CoreSchema: + """Generate a schema unrelated to the current context. + Use this function if e.g. you are handling schema generation for a sequence + and want to generate a schema for its items. + Otherwise, you may end up doing something like applying a `min_length` constraint + that was intended for the sequence itself to its items! + + Args: + source_type: The input type. + + Returns: + CoreSchema: The `pydantic-core` CoreSchema generated. + """ + raise NotImplementedError + + def resolve_ref_schema(self, maybe_ref_schema: core_schema.CoreSchema, /) -> core_schema.CoreSchema: + """Get the real schema for a `definition-ref` schema. + If the schema given is not a `definition-ref` schema, it will be returned as is. + This means you don't have to check before calling this function. + + Args: + maybe_ref_schema: A `CoreSchema`, `ref`-based or not. + + Raises: + LookupError: If the `ref` is not found. + + Returns: + A concrete `CoreSchema`. + """ + raise NotImplementedError + + @property + def field_name(self) -> str | None: + """Get the name of the closest field to this validator.""" + raise NotImplementedError + + def _get_types_namespace(self) -> dict[str, Any] | None: + """Internal method used during type resolution for serializer annotations.""" + raise NotImplementedError diff --git a/env/Lib/site-packages/pydantic/class_validators.py b/env/Lib/site-packages/pydantic/class_validators.py new file mode 100644 index 0000000..9977150 --- /dev/null +++ b/env/Lib/site-packages/pydantic/class_validators.py @@ -0,0 +1,5 @@ +"""`class_validators` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/color.py b/env/Lib/site-packages/pydantic/color.py new file mode 100644 index 0000000..c702fc6 --- /dev/null +++ b/env/Lib/site-packages/pydantic/color.py @@ -0,0 +1,604 @@ +"""Color definitions are used as per the CSS3 +[CSS Color Module Level 3](http://www.w3.org/TR/css3-color/#svg-color) specification. + +A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`. + +In these cases the _last_ color when sorted alphabetically takes preferences, +eg. `Color((0, 255, 255)).as_named() == 'cyan'` because "cyan" comes after "aqua". + +Warning: Deprecated + The `Color` class is deprecated, use `pydantic_extra_types` instead. + See [`pydantic-extra-types.Color`](../usage/types/extra_types/color_types.md) + for more information. +""" + +import math +import re +from colorsys import hls_to_rgb, rgb_to_hls +from typing import Any, Callable, Optional, Tuple, Type, Union, cast + +from pydantic_core import CoreSchema, PydanticCustomError, core_schema +from typing_extensions import deprecated + +from ._internal import _repr +from ._internal._schema_generation_shared import GetJsonSchemaHandler as _GetJsonSchemaHandler +from .json_schema import JsonSchemaValue +from .warnings import PydanticDeprecatedSince20 + +ColorTuple = Union[Tuple[int, int, int], Tuple[int, int, int, float]] +ColorType = Union[ColorTuple, str] +HslColorTuple = Union[Tuple[float, float, float], Tuple[float, float, float, float]] + + +class RGBA: + """Internal use only as a representation of a color.""" + + __slots__ = 'r', 'g', 'b', 'alpha', '_tuple' + + def __init__(self, r: float, g: float, b: float, alpha: Optional[float]): + self.r = r + self.g = g + self.b = b + self.alpha = alpha + + self._tuple: Tuple[float, float, float, Optional[float]] = (r, g, b, alpha) + + def __getitem__(self, item: Any) -> Any: + return self._tuple[item] + + +# these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached +_r_255 = r'(\d{1,3}(?:\.\d+)?)' +_r_comma = r'\s*,\s*' +_r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)' +_r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?' +_r_sl = r'(\d{1,3}(?:\.\d+)?)%' +r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*' +r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*' +# CSS3 RGB examples: rgb(0, 0, 0), rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 50%) +r_rgb = rf'\s*rgba?\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}(?:{_r_comma}{_r_alpha})?\s*\)\s*' +# CSS3 HSL examples: hsl(270, 60%, 50%), hsla(270, 60%, 50%, 0.5), hsla(270, 60%, 50%, 50%) +r_hsl = rf'\s*hsla?\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}(?:{_r_comma}{_r_alpha})?\s*\)\s*' +# CSS4 RGB examples: rgb(0 0 0), rgb(0 0 0 / 0.5), rgb(0 0 0 / 50%), rgba(0 0 0 / 50%) +r_rgb_v4_style = rf'\s*rgba?\(\s*{_r_255}\s+{_r_255}\s+{_r_255}(?:\s*/\s*{_r_alpha})?\s*\)\s*' +# CSS4 HSL examples: hsl(270 60% 50%), hsl(270 60% 50% / 0.5), hsl(270 60% 50% / 50%), hsla(270 60% 50% / 50%) +r_hsl_v4_style = rf'\s*hsla?\(\s*{_r_h}\s+{_r_sl}\s+{_r_sl}(?:\s*/\s*{_r_alpha})?\s*\)\s*' + +# colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used +repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'} +rads = 2 * math.pi + + +@deprecated( + 'The `Color` class is deprecated, use `pydantic_extra_types` instead. ' + 'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_color/.', + category=PydanticDeprecatedSince20, +) +class Color(_repr.Representation): + """Represents a color.""" + + __slots__ = '_original', '_rgba' + + def __init__(self, value: ColorType) -> None: + self._rgba: RGBA + self._original: ColorType + if isinstance(value, (tuple, list)): + self._rgba = parse_tuple(value) + elif isinstance(value, str): + self._rgba = parse_str(value) + elif isinstance(value, Color): + self._rgba = value._rgba + value = value._original + else: + raise PydanticCustomError( + 'color_error', 'value is not a valid color: value must be a tuple, list or string' + ) + + # if we've got here value must be a valid color + self._original = value + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: _GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = {} + field_schema.update(type='string', format='color') + return field_schema + + def original(self) -> ColorType: + """Original value passed to `Color`.""" + return self._original + + def as_named(self, *, fallback: bool = False) -> str: + """Returns the name of the color if it can be found in `COLORS_BY_VALUE` dictionary, + otherwise returns the hexadecimal representation of the color or raises `ValueError`. + + Args: + fallback: If True, falls back to returning the hexadecimal representation of + the color instead of raising a ValueError when no named color is found. + + Returns: + The name of the color, or the hexadecimal representation of the color. + + Raises: + ValueError: When no named color is found and fallback is `False`. + """ + if self._rgba.alpha is None: + rgb = cast(Tuple[int, int, int], self.as_rgb_tuple()) + try: + return COLORS_BY_VALUE[rgb] + except KeyError as e: + if fallback: + return self.as_hex() + else: + raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e + else: + return self.as_hex() + + def as_hex(self) -> str: + """Returns the hexadecimal representation of the color. + + Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string + a "short" representation of the color is possible and whether there's an alpha channel. + + Returns: + The hexadecimal representation of the color. + """ + values = [float_to_255(c) for c in self._rgba[:3]] + if self._rgba.alpha is not None: + values.append(float_to_255(self._rgba.alpha)) + + as_hex = ''.join(f'{v:02x}' for v in values) + if all(c in repeat_colors for c in values): + as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2)) + return '#' + as_hex + + def as_rgb(self) -> str: + """Color as an `rgb(, , )` or `rgba(, , , )` string.""" + if self._rgba.alpha is None: + return f'rgb({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)})' + else: + return ( + f'rgba({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)}, ' + f'{round(self._alpha_float(), 2)})' + ) + + def as_rgb_tuple(self, *, alpha: Optional[bool] = None) -> ColorTuple: + """Returns the color as an RGB or RGBA tuple. + + Args: + alpha: Whether to include the alpha channel. There are three options for this input: + + - `None` (default): Include alpha only if it's set. (e.g. not `None`) + - `True`: Always include alpha. + - `False`: Always omit alpha. + + Returns: + A tuple that contains the values of the red, green, and blue channels in the range 0 to 255. + If alpha is included, it is in the range 0 to 1. + """ + r, g, b = (float_to_255(c) for c in self._rgba[:3]) + if alpha is None: + if self._rgba.alpha is None: + return r, g, b + else: + return r, g, b, self._alpha_float() + elif alpha: + return r, g, b, self._alpha_float() + else: + # alpha is False + return r, g, b + + def as_hsl(self) -> str: + """Color as an `hsl(, , )` or `hsl(, , , )` string.""" + if self._rgba.alpha is None: + h, s, li = self.as_hsl_tuple(alpha=False) # type: ignore + return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})' + else: + h, s, li, a = self.as_hsl_tuple(alpha=True) # type: ignore + return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})' + + def as_hsl_tuple(self, *, alpha: Optional[bool] = None) -> HslColorTuple: + """Returns the color as an HSL or HSLA tuple. + + Args: + alpha: Whether to include the alpha channel. + + - `None` (default): Include the alpha channel only if it's set (e.g. not `None`). + - `True`: Always include alpha. + - `False`: Always omit alpha. + + Returns: + The color as a tuple of hue, saturation, lightness, and alpha (if included). + All elements are in the range 0 to 1. + + Note: + This is HSL as used in HTML and most other places, not HLS as used in Python's `colorsys`. + """ + h, l, s = rgb_to_hls(self._rgba.r, self._rgba.g, self._rgba.b) # noqa: E741 + if alpha is None: + if self._rgba.alpha is None: + return h, s, l + else: + return h, s, l, self._alpha_float() + if alpha: + return h, s, l, self._alpha_float() + else: + # alpha is False + return h, s, l + + def _alpha_float(self) -> float: + return 1 if self._rgba.alpha is None else self._rgba.alpha + + @classmethod + def __get_pydantic_core_schema__( + cls, source: Type[Any], handler: Callable[[Any], CoreSchema] + ) -> core_schema.CoreSchema: + return core_schema.with_info_plain_validator_function( + cls._validate, serialization=core_schema.to_string_ser_schema() + ) + + @classmethod + def _validate(cls, __input_value: Any, _: Any) -> 'Color': + return cls(__input_value) + + def __str__(self) -> str: + return self.as_named(fallback=True) + + def __repr_args__(self) -> '_repr.ReprArgs': + return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())] + + def __eq__(self, other: Any) -> bool: + return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple() + + def __hash__(self) -> int: + return hash(self.as_rgb_tuple()) + + +def parse_tuple(value: Tuple[Any, ...]) -> RGBA: + """Parse a tuple or list to get RGBA values. + + Args: + value: A tuple or list. + + Returns: + An `RGBA` tuple parsed from the input tuple. + + Raises: + PydanticCustomError: If tuple is not valid. + """ + if len(value) == 3: + r, g, b = (parse_color_value(v) for v in value) + return RGBA(r, g, b, None) + elif len(value) == 4: + r, g, b = (parse_color_value(v) for v in value[:3]) + return RGBA(r, g, b, parse_float_alpha(value[3])) + else: + raise PydanticCustomError('color_error', 'value is not a valid color: tuples must have length 3 or 4') + + +def parse_str(value: str) -> RGBA: + """Parse a string representing a color to an RGBA tuple. + + Possible formats for the input string include: + + * named color, see `COLORS_BY_NAME` + * hex short eg. `fff` (prefix can be `#`, `0x` or nothing) + * hex long eg. `ffffff` (prefix can be `#`, `0x` or nothing) + * `rgb(, , )` + * `rgba(, , , )` + + Args: + value: A string representing a color. + + Returns: + An `RGBA` tuple parsed from the input string. + + Raises: + ValueError: If the input string cannot be parsed to an RGBA tuple. + """ + value_lower = value.lower() + try: + r, g, b = COLORS_BY_NAME[value_lower] + except KeyError: + pass + else: + return ints_to_rgba(r, g, b, None) + + m = re.fullmatch(r_hex_short, value_lower) + if m: + *rgb, a = m.groups() + r, g, b = (int(v * 2, 16) for v in rgb) + if a: + alpha: Optional[float] = int(a * 2, 16) / 255 + else: + alpha = None + return ints_to_rgba(r, g, b, alpha) + + m = re.fullmatch(r_hex_long, value_lower) + if m: + *rgb, a = m.groups() + r, g, b = (int(v, 16) for v in rgb) + if a: + alpha = int(a, 16) / 255 + else: + alpha = None + return ints_to_rgba(r, g, b, alpha) + + m = re.fullmatch(r_rgb, value_lower) or re.fullmatch(r_rgb_v4_style, value_lower) + if m: + return ints_to_rgba(*m.groups()) # type: ignore + + m = re.fullmatch(r_hsl, value_lower) or re.fullmatch(r_hsl_v4_style, value_lower) + if m: + return parse_hsl(*m.groups()) # type: ignore + + raise PydanticCustomError('color_error', 'value is not a valid color: string not recognised as a valid color') + + +def ints_to_rgba(r: Union[int, str], g: Union[int, str], b: Union[int, str], alpha: Optional[float] = None) -> RGBA: + """Converts integer or string values for RGB color and an optional alpha value to an `RGBA` object. + + Args: + r: An integer or string representing the red color value. + g: An integer or string representing the green color value. + b: An integer or string representing the blue color value. + alpha: A float representing the alpha value. Defaults to None. + + Returns: + An instance of the `RGBA` class with the corresponding color and alpha values. + """ + return RGBA(parse_color_value(r), parse_color_value(g), parse_color_value(b), parse_float_alpha(alpha)) + + +def parse_color_value(value: Union[int, str], max_val: int = 255) -> float: + """Parse the color value provided and return a number between 0 and 1. + + Args: + value: An integer or string color value. + max_val: Maximum range value. Defaults to 255. + + Raises: + PydanticCustomError: If the value is not a valid color. + + Returns: + A number between 0 and 1. + """ + try: + color = float(value) + except ValueError: + raise PydanticCustomError('color_error', 'value is not a valid color: color values must be a valid number') + if 0 <= color <= max_val: + return color / max_val + else: + raise PydanticCustomError( + 'color_error', + 'value is not a valid color: color values must be in the range 0 to {max_val}', + {'max_val': max_val}, + ) + + +def parse_float_alpha(value: Union[None, str, float, int]) -> Optional[float]: + """Parse an alpha value checking it's a valid float in the range 0 to 1. + + Args: + value: The input value to parse. + + Returns: + The parsed value as a float, or `None` if the value was None or equal 1. + + Raises: + PydanticCustomError: If the input value cannot be successfully parsed as a float in the expected range. + """ + if value is None: + return None + try: + if isinstance(value, str) and value.endswith('%'): + alpha = float(value[:-1]) / 100 + else: + alpha = float(value) + except ValueError: + raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be a valid float') + + if math.isclose(alpha, 1): + return None + elif 0 <= alpha <= 1: + return alpha + else: + raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be in the range 0 to 1') + + +def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: Optional[float] = None) -> RGBA: + """Parse raw hue, saturation, lightness, and alpha values and convert to RGBA. + + Args: + h: The hue value. + h_units: The unit for hue value. + sat: The saturation value. + light: The lightness value. + alpha: Alpha value. + + Returns: + An instance of `RGBA`. + """ + s_value, l_value = parse_color_value(sat, 100), parse_color_value(light, 100) + + h_value = float(h) + if h_units in {None, 'deg'}: + h_value = h_value % 360 / 360 + elif h_units == 'rad': + h_value = h_value % rads / rads + else: + # turns + h_value = h_value % 1 + + r, g, b = hls_to_rgb(h_value, l_value, s_value) + return RGBA(r, g, b, parse_float_alpha(alpha)) + + +def float_to_255(c: float) -> int: + """Converts a float value between 0 and 1 (inclusive) to an integer between 0 and 255 (inclusive). + + Args: + c: The float value to be converted. Must be between 0 and 1 (inclusive). + + Returns: + The integer equivalent of the given float value rounded to the nearest whole number. + + Raises: + ValueError: If the given float value is outside the acceptable range of 0 to 1 (inclusive). + """ + return int(round(c * 255)) + + +COLORS_BY_NAME = { + 'aliceblue': (240, 248, 255), + 'antiquewhite': (250, 235, 215), + 'aqua': (0, 255, 255), + 'aquamarine': (127, 255, 212), + 'azure': (240, 255, 255), + 'beige': (245, 245, 220), + 'bisque': (255, 228, 196), + 'black': (0, 0, 0), + 'blanchedalmond': (255, 235, 205), + 'blue': (0, 0, 255), + 'blueviolet': (138, 43, 226), + 'brown': (165, 42, 42), + 'burlywood': (222, 184, 135), + 'cadetblue': (95, 158, 160), + 'chartreuse': (127, 255, 0), + 'chocolate': (210, 105, 30), + 'coral': (255, 127, 80), + 'cornflowerblue': (100, 149, 237), + 'cornsilk': (255, 248, 220), + 'crimson': (220, 20, 60), + 'cyan': (0, 255, 255), + 'darkblue': (0, 0, 139), + 'darkcyan': (0, 139, 139), + 'darkgoldenrod': (184, 134, 11), + 'darkgray': (169, 169, 169), + 'darkgreen': (0, 100, 0), + 'darkgrey': (169, 169, 169), + 'darkkhaki': (189, 183, 107), + 'darkmagenta': (139, 0, 139), + 'darkolivegreen': (85, 107, 47), + 'darkorange': (255, 140, 0), + 'darkorchid': (153, 50, 204), + 'darkred': (139, 0, 0), + 'darksalmon': (233, 150, 122), + 'darkseagreen': (143, 188, 143), + 'darkslateblue': (72, 61, 139), + 'darkslategray': (47, 79, 79), + 'darkslategrey': (47, 79, 79), + 'darkturquoise': (0, 206, 209), + 'darkviolet': (148, 0, 211), + 'deeppink': (255, 20, 147), + 'deepskyblue': (0, 191, 255), + 'dimgray': (105, 105, 105), + 'dimgrey': (105, 105, 105), + 'dodgerblue': (30, 144, 255), + 'firebrick': (178, 34, 34), + 'floralwhite': (255, 250, 240), + 'forestgreen': (34, 139, 34), + 'fuchsia': (255, 0, 255), + 'gainsboro': (220, 220, 220), + 'ghostwhite': (248, 248, 255), + 'gold': (255, 215, 0), + 'goldenrod': (218, 165, 32), + 'gray': (128, 128, 128), + 'green': (0, 128, 0), + 'greenyellow': (173, 255, 47), + 'grey': (128, 128, 128), + 'honeydew': (240, 255, 240), + 'hotpink': (255, 105, 180), + 'indianred': (205, 92, 92), + 'indigo': (75, 0, 130), + 'ivory': (255, 255, 240), + 'khaki': (240, 230, 140), + 'lavender': (230, 230, 250), + 'lavenderblush': (255, 240, 245), + 'lawngreen': (124, 252, 0), + 'lemonchiffon': (255, 250, 205), + 'lightblue': (173, 216, 230), + 'lightcoral': (240, 128, 128), + 'lightcyan': (224, 255, 255), + 'lightgoldenrodyellow': (250, 250, 210), + 'lightgray': (211, 211, 211), + 'lightgreen': (144, 238, 144), + 'lightgrey': (211, 211, 211), + 'lightpink': (255, 182, 193), + 'lightsalmon': (255, 160, 122), + 'lightseagreen': (32, 178, 170), + 'lightskyblue': (135, 206, 250), + 'lightslategray': (119, 136, 153), + 'lightslategrey': (119, 136, 153), + 'lightsteelblue': (176, 196, 222), + 'lightyellow': (255, 255, 224), + 'lime': (0, 255, 0), + 'limegreen': (50, 205, 50), + 'linen': (250, 240, 230), + 'magenta': (255, 0, 255), + 'maroon': (128, 0, 0), + 'mediumaquamarine': (102, 205, 170), + 'mediumblue': (0, 0, 205), + 'mediumorchid': (186, 85, 211), + 'mediumpurple': (147, 112, 219), + 'mediumseagreen': (60, 179, 113), + 'mediumslateblue': (123, 104, 238), + 'mediumspringgreen': (0, 250, 154), + 'mediumturquoise': (72, 209, 204), + 'mediumvioletred': (199, 21, 133), + 'midnightblue': (25, 25, 112), + 'mintcream': (245, 255, 250), + 'mistyrose': (255, 228, 225), + 'moccasin': (255, 228, 181), + 'navajowhite': (255, 222, 173), + 'navy': (0, 0, 128), + 'oldlace': (253, 245, 230), + 'olive': (128, 128, 0), + 'olivedrab': (107, 142, 35), + 'orange': (255, 165, 0), + 'orangered': (255, 69, 0), + 'orchid': (218, 112, 214), + 'palegoldenrod': (238, 232, 170), + 'palegreen': (152, 251, 152), + 'paleturquoise': (175, 238, 238), + 'palevioletred': (219, 112, 147), + 'papayawhip': (255, 239, 213), + 'peachpuff': (255, 218, 185), + 'peru': (205, 133, 63), + 'pink': (255, 192, 203), + 'plum': (221, 160, 221), + 'powderblue': (176, 224, 230), + 'purple': (128, 0, 128), + 'red': (255, 0, 0), + 'rosybrown': (188, 143, 143), + 'royalblue': (65, 105, 225), + 'saddlebrown': (139, 69, 19), + 'salmon': (250, 128, 114), + 'sandybrown': (244, 164, 96), + 'seagreen': (46, 139, 87), + 'seashell': (255, 245, 238), + 'sienna': (160, 82, 45), + 'silver': (192, 192, 192), + 'skyblue': (135, 206, 235), + 'slateblue': (106, 90, 205), + 'slategray': (112, 128, 144), + 'slategrey': (112, 128, 144), + 'snow': (255, 250, 250), + 'springgreen': (0, 255, 127), + 'steelblue': (70, 130, 180), + 'tan': (210, 180, 140), + 'teal': (0, 128, 128), + 'thistle': (216, 191, 216), + 'tomato': (255, 99, 71), + 'turquoise': (64, 224, 208), + 'violet': (238, 130, 238), + 'wheat': (245, 222, 179), + 'white': (255, 255, 255), + 'whitesmoke': (245, 245, 245), + 'yellow': (255, 255, 0), + 'yellowgreen': (154, 205, 50), +} + +COLORS_BY_VALUE = {v: k for k, v in COLORS_BY_NAME.items()} diff --git a/env/Lib/site-packages/pydantic/dataclasses.py b/env/Lib/site-packages/pydantic/dataclasses.py new file mode 100644 index 0000000..acfd3d5 --- /dev/null +++ b/env/Lib/site-packages/pydantic/dataclasses.py @@ -0,0 +1,338 @@ +"""Provide an enhanced dataclass that performs validation.""" + +from __future__ import annotations as _annotations + +import dataclasses +import sys +import types +from typing import TYPE_CHECKING, Any, Callable, Generic, NoReturn, TypeVar, overload + +from typing_extensions import Literal, TypeGuard, dataclass_transform + +from ._internal import _config, _decorators, _typing_extra +from ._internal import _dataclasses as _pydantic_dataclasses +from ._migration import getattr_migration +from .config import ConfigDict +from .errors import PydanticUserError +from .fields import Field, FieldInfo, PrivateAttr + +if TYPE_CHECKING: + from ._internal._dataclasses import PydanticDataclass + +__all__ = 'dataclass', 'rebuild_dataclass' + +_T = TypeVar('_T') + +if sys.version_info >= (3, 10): + + @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) + @overload + def dataclass( + *, + init: Literal[False] = False, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: ConfigDict | type[object] | None = None, + validate_on_init: bool | None = None, + kw_only: bool = ..., + slots: bool = ..., + ) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore + ... + + @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) + @overload + def dataclass( + _cls: type[_T], # type: ignore + *, + init: Literal[False] = False, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: ConfigDict | type[object] | None = None, + validate_on_init: bool | None = None, + kw_only: bool = ..., + slots: bool = ..., + ) -> type[PydanticDataclass]: ... + +else: + + @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) + @overload + def dataclass( + *, + init: Literal[False] = False, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: ConfigDict | type[object] | None = None, + validate_on_init: bool | None = None, + ) -> Callable[[type[_T]], type[PydanticDataclass]]: # type: ignore + ... + + @dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) + @overload + def dataclass( + _cls: type[_T], # type: ignore + *, + init: Literal[False] = False, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: ConfigDict | type[object] | None = None, + validate_on_init: bool | None = None, + ) -> type[PydanticDataclass]: ... + + +@dataclass_transform(field_specifiers=(dataclasses.field, Field, PrivateAttr)) +def dataclass( # noqa: C901 + _cls: type[_T] | None = None, + *, + init: Literal[False] = False, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: ConfigDict | type[object] | None = None, + validate_on_init: bool | None = None, + kw_only: bool = False, + slots: bool = False, +) -> Callable[[type[_T]], type[PydanticDataclass]] | type[PydanticDataclass]: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/dataclasses/ + + A decorator used to create a Pydantic-enhanced dataclass, similar to the standard Python `dataclass`, + but with added validation. + + This function should be used similarly to `dataclasses.dataclass`. + + Args: + _cls: The target `dataclass`. + init: Included for signature compatibility with `dataclasses.dataclass`, and is passed through to + `dataclasses.dataclass` when appropriate. If specified, must be set to `False`, as pydantic inserts its + own `__init__` function. + repr: A boolean indicating whether to include the field in the `__repr__` output. + eq: Determines if a `__eq__` method should be generated for the class. + order: Determines if comparison magic methods should be generated, such as `__lt__`, but not `__eq__`. + unsafe_hash: Determines if a `__hash__` method should be included in the class, as in `dataclasses.dataclass`. + frozen: Determines if the generated class should be a 'frozen' `dataclass`, which does not allow its + attributes to be modified after it has been initialized. + config: The Pydantic config to use for the `dataclass`. + validate_on_init: A deprecated parameter included for backwards compatibility; in V2, all Pydantic dataclasses + are validated on init. + kw_only: Determines if `__init__` method parameters must be specified by keyword only. Defaults to `False`. + slots: Determines if the generated class should be a 'slots' `dataclass`, which does not allow the addition of + new attributes after instantiation. + + Returns: + A decorator that accepts a class as its argument and returns a Pydantic `dataclass`. + + Raises: + AssertionError: Raised if `init` is not `False` or `validate_on_init` is `False`. + """ + assert init is False, 'pydantic.dataclasses.dataclass only supports init=False' + assert validate_on_init is not False, 'validate_on_init=False is no longer supported' + + if sys.version_info >= (3, 10): + kwargs = dict(kw_only=kw_only, slots=slots) + else: + kwargs = {} + + def make_pydantic_fields_compatible(cls: type[Any]) -> None: + """Make sure that stdlib `dataclasses` understands `Field` kwargs like `kw_only` + To do that, we simply change + `x: int = pydantic.Field(..., kw_only=True)` + into + `x: int = dataclasses.field(default=pydantic.Field(..., kw_only=True), kw_only=True)` + """ + for annotation_cls in cls.__mro__: + # In Python < 3.9, `__annotations__` might not be present if there are no fields. + # we therefore need to use `getattr` to avoid an `AttributeError`. + annotations = getattr(annotation_cls, '__annotations__', []) + for field_name in annotations: + field_value = getattr(cls, field_name, None) + # Process only if this is an instance of `FieldInfo`. + if not isinstance(field_value, FieldInfo): + continue + + # Initialize arguments for the standard `dataclasses.field`. + field_args: dict = {'default': field_value} + + # Handle `kw_only` for Python 3.10+ + if sys.version_info >= (3, 10) and field_value.kw_only: + field_args['kw_only'] = True + + # Set `repr` attribute if it's explicitly specified to be not `True`. + if field_value.repr is not True: + field_args['repr'] = field_value.repr + + setattr(cls, field_name, dataclasses.field(**field_args)) + # In Python 3.8, dataclasses checks cls.__dict__['__annotations__'] for annotations, + # so we must make sure it's initialized before we add to it. + if cls.__dict__.get('__annotations__') is None: + cls.__annotations__ = {} + cls.__annotations__[field_name] = annotations[field_name] + + def create_dataclass(cls: type[Any]) -> type[PydanticDataclass]: + """Create a Pydantic dataclass from a regular dataclass. + + Args: + cls: The class to create the Pydantic dataclass from. + + Returns: + A Pydantic dataclass. + """ + from ._internal._utils import is_model_class + + if is_model_class(cls): + raise PydanticUserError( + f'Cannot create a Pydantic dataclass from {cls.__name__} as it is already a Pydantic model', + code='dataclass-on-model', + ) + + original_cls = cls + + config_dict = config + if config_dict is None: + # if not explicitly provided, read from the type + cls_config = getattr(cls, '__pydantic_config__', None) + if cls_config is not None: + config_dict = cls_config + config_wrapper = _config.ConfigWrapper(config_dict) + decorators = _decorators.DecoratorInfos.build(cls) + + # Keep track of the original __doc__ so that we can restore it after applying the dataclasses decorator + # Otherwise, classes with no __doc__ will have their signature added into the JSON schema description, + # since dataclasses.dataclass will set this as the __doc__ + original_doc = cls.__doc__ + + if _pydantic_dataclasses.is_builtin_dataclass(cls): + # Don't preserve the docstring for vanilla dataclasses, as it may include the signature + # This matches v1 behavior, and there was an explicit test for it + original_doc = None + + # We don't want to add validation to the existing std lib dataclass, so we will subclass it + # If the class is generic, we need to make sure the subclass also inherits from Generic + # with all the same parameters. + bases = (cls,) + if issubclass(cls, Generic): + generic_base = Generic[cls.__parameters__] # type: ignore + bases = bases + (generic_base,) + cls = types.new_class(cls.__name__, bases) + + make_pydantic_fields_compatible(cls) + + cls = dataclasses.dataclass( # type: ignore[call-overload] + cls, + # the value of init here doesn't affect anything except that it makes it easier to generate a signature + init=True, + repr=repr, + eq=eq, + order=order, + unsafe_hash=unsafe_hash, + frozen=frozen, + **kwargs, + ) + + cls.__pydantic_decorators__ = decorators # type: ignore + cls.__doc__ = original_doc + cls.__module__ = original_cls.__module__ + cls.__qualname__ = original_cls.__qualname__ + pydantic_complete = _pydantic_dataclasses.complete_dataclass( + cls, config_wrapper, raise_errors=False, types_namespace=None + ) + cls.__pydantic_complete__ = pydantic_complete # type: ignore + return cls + + if _cls is None: + return create_dataclass + + return create_dataclass(_cls) + + +__getattr__ = getattr_migration(__name__) + +if (3, 8) <= sys.version_info < (3, 11): + # Monkeypatch dataclasses.InitVar so that typing doesn't error if it occurs as a type when evaluating type hints + # Starting in 3.11, typing.get_type_hints will not raise an error if the retrieved type hints are not callable. + + def _call_initvar(*args: Any, **kwargs: Any) -> NoReturn: + """This function does nothing but raise an error that is as similar as possible to what you'd get + if you were to try calling `InitVar[int]()` without this monkeypatch. The whole purpose is just + to ensure typing._type_check does not error if the type hint evaluates to `InitVar[]`. + """ + raise TypeError("'InitVar' object is not callable") + + dataclasses.InitVar.__call__ = _call_initvar + + +def rebuild_dataclass( + cls: type[PydanticDataclass], + *, + force: bool = False, + raise_errors: bool = True, + _parent_namespace_depth: int = 2, + _types_namespace: dict[str, Any] | None = None, +) -> bool | None: + """Try to rebuild the pydantic-core schema for the dataclass. + + This may be necessary when one of the annotations is a ForwardRef which could not be resolved during + the initial attempt to build the schema, and automatic rebuilding fails. + + This is analogous to `BaseModel.model_rebuild`. + + Args: + cls: The class to rebuild the pydantic-core schema for. + force: Whether to force the rebuilding of the schema, defaults to `False`. + raise_errors: Whether to raise errors, defaults to `True`. + _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. + _types_namespace: The types namespace, defaults to `None`. + + Returns: + Returns `None` if the schema is already "complete" and rebuilding was not required. + If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. + """ + if not force and cls.__pydantic_complete__: + return None + else: + if _types_namespace is not None: + types_namespace: dict[str, Any] | None = _types_namespace.copy() + else: + if _parent_namespace_depth > 0: + frame_parent_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth) or {} + # Note: we may need to add something similar to cls.__pydantic_parent_namespace__ from BaseModel + # here when implementing handling of recursive generics. See BaseModel.model_rebuild for reference. + types_namespace = frame_parent_ns + else: + types_namespace = {} + + types_namespace = _typing_extra.get_cls_types_namespace(cls, types_namespace) + return _pydantic_dataclasses.complete_dataclass( + cls, + _config.ConfigWrapper(cls.__pydantic_config__, check=False), + raise_errors=raise_errors, + types_namespace=types_namespace, + ) + + +def is_pydantic_dataclass(class_: type[Any], /) -> TypeGuard[type[PydanticDataclass]]: + """Whether a class is a pydantic dataclass. + + Args: + class_: The class. + + Returns: + `True` if the class is a pydantic dataclass, `False` otherwise. + """ + try: + return '__pydantic_validator__' in class_.__dict__ and dataclasses.is_dataclass(class_) + except AttributeError: + return False diff --git a/env/Lib/site-packages/pydantic/datetime_parse.py b/env/Lib/site-packages/pydantic/datetime_parse.py new file mode 100644 index 0000000..53d5264 --- /dev/null +++ b/env/Lib/site-packages/pydantic/datetime_parse.py @@ -0,0 +1,5 @@ +"""The `datetime_parse` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/decorator.py b/env/Lib/site-packages/pydantic/decorator.py new file mode 100644 index 0000000..0d97560 --- /dev/null +++ b/env/Lib/site-packages/pydantic/decorator.py @@ -0,0 +1,5 @@ +"""The `decorator` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/deprecated/__init__.py b/env/Lib/site-packages/pydantic/deprecated/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/pydantic/deprecated/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/pydantic/deprecated/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..6f2f20d Binary files /dev/null and b/env/Lib/site-packages/pydantic/deprecated/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/deprecated/__pycache__/class_validators.cpython-311.pyc b/env/Lib/site-packages/pydantic/deprecated/__pycache__/class_validators.cpython-311.pyc new file mode 100644 index 0000000..53b45f8 Binary files /dev/null and b/env/Lib/site-packages/pydantic/deprecated/__pycache__/class_validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/deprecated/__pycache__/config.cpython-311.pyc b/env/Lib/site-packages/pydantic/deprecated/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000..61cbcdf Binary files /dev/null and b/env/Lib/site-packages/pydantic/deprecated/__pycache__/config.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/deprecated/__pycache__/copy_internals.cpython-311.pyc b/env/Lib/site-packages/pydantic/deprecated/__pycache__/copy_internals.cpython-311.pyc new file mode 100644 index 0000000..1ddc4ed Binary files /dev/null and b/env/Lib/site-packages/pydantic/deprecated/__pycache__/copy_internals.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/deprecated/__pycache__/decorator.cpython-311.pyc b/env/Lib/site-packages/pydantic/deprecated/__pycache__/decorator.cpython-311.pyc new file mode 100644 index 0000000..0aa7b16 Binary files /dev/null and b/env/Lib/site-packages/pydantic/deprecated/__pycache__/decorator.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/deprecated/__pycache__/json.cpython-311.pyc b/env/Lib/site-packages/pydantic/deprecated/__pycache__/json.cpython-311.pyc new file mode 100644 index 0000000..87ad4d3 Binary files /dev/null and b/env/Lib/site-packages/pydantic/deprecated/__pycache__/json.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/deprecated/__pycache__/parse.cpython-311.pyc b/env/Lib/site-packages/pydantic/deprecated/__pycache__/parse.cpython-311.pyc new file mode 100644 index 0000000..0285300 Binary files /dev/null and b/env/Lib/site-packages/pydantic/deprecated/__pycache__/parse.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/deprecated/__pycache__/tools.cpython-311.pyc b/env/Lib/site-packages/pydantic/deprecated/__pycache__/tools.cpython-311.pyc new file mode 100644 index 0000000..f03b2c4 Binary files /dev/null and b/env/Lib/site-packages/pydantic/deprecated/__pycache__/tools.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/deprecated/class_validators.py b/env/Lib/site-packages/pydantic/deprecated/class_validators.py new file mode 100644 index 0000000..aae3362 --- /dev/null +++ b/env/Lib/site-packages/pydantic/deprecated/class_validators.py @@ -0,0 +1,256 @@ +"""Old `@validator` and `@root_validator` function validators from V1.""" + +from __future__ import annotations as _annotations + +from functools import partial, partialmethod +from types import FunctionType +from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union, overload +from warnings import warn + +from typing_extensions import Literal, Protocol, TypeAlias, deprecated + +from .._internal import _decorators, _decorators_v1 +from ..errors import PydanticUserError +from ..warnings import PydanticDeprecatedSince20 + +_ALLOW_REUSE_WARNING_MESSAGE = '`allow_reuse` is deprecated and will be ignored; it should no longer be necessary' + + +if TYPE_CHECKING: + + class _OnlyValueValidatorClsMethod(Protocol): + def __call__(self, __cls: Any, __value: Any) -> Any: ... + + class _V1ValidatorWithValuesClsMethod(Protocol): + def __call__(self, __cls: Any, __value: Any, values: dict[str, Any]) -> Any: ... + + class _V1ValidatorWithValuesKwOnlyClsMethod(Protocol): + def __call__(self, __cls: Any, __value: Any, *, values: dict[str, Any]) -> Any: ... + + class _V1ValidatorWithKwargsClsMethod(Protocol): + def __call__(self, __cls: Any, **kwargs: Any) -> Any: ... + + class _V1ValidatorWithValuesAndKwargsClsMethod(Protocol): + def __call__(self, __cls: Any, values: dict[str, Any], **kwargs: Any) -> Any: ... + + class _V1RootValidatorClsMethod(Protocol): + def __call__( + self, __cls: Any, __values: _decorators_v1.RootValidatorValues + ) -> _decorators_v1.RootValidatorValues: ... + + V1Validator = Union[ + _OnlyValueValidatorClsMethod, + _V1ValidatorWithValuesClsMethod, + _V1ValidatorWithValuesKwOnlyClsMethod, + _V1ValidatorWithKwargsClsMethod, + _V1ValidatorWithValuesAndKwargsClsMethod, + _decorators_v1.V1ValidatorWithValues, + _decorators_v1.V1ValidatorWithValuesKwOnly, + _decorators_v1.V1ValidatorWithKwargs, + _decorators_v1.V1ValidatorWithValuesAndKwargs, + ] + + V1RootValidator = Union[ + _V1RootValidatorClsMethod, + _decorators_v1.V1RootValidatorFunction, + ] + + _PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]] + + # Allow both a V1 (assumed pre=False) or V2 (assumed mode='after') validator + # We lie to type checkers and say we return the same thing we get + # but in reality we return a proxy object that _mostly_ behaves like the wrapped thing + _V1ValidatorType = TypeVar('_V1ValidatorType', V1Validator, _PartialClsOrStaticMethod) + _V1RootValidatorFunctionType = TypeVar( + '_V1RootValidatorFunctionType', + _decorators_v1.V1RootValidatorFunction, + _V1RootValidatorClsMethod, + _PartialClsOrStaticMethod, + ) +else: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + + +@deprecated( + 'Pydantic V1 style `@validator` validators are deprecated.' + ' You should migrate to Pydantic V2 style `@field_validator` validators,' + ' see the migration guide for more details', + category=None, +) +def validator( + __field: str, + *fields: str, + pre: bool = False, + each_item: bool = False, + always: bool = False, + check_fields: bool | None = None, + allow_reuse: bool = False, +) -> Callable[[_V1ValidatorType], _V1ValidatorType]: + """Decorate methods on the class indicating that they should be used to validate fields. + + Args: + __field (str): The first field the validator should be called on; this is separate + from `fields` to ensure an error is raised if you don't pass at least one. + *fields (str): Additional field(s) the validator should be called on. + pre (bool, optional): Whether this validator should be called before the standard + validators (else after). Defaults to False. + each_item (bool, optional): For complex objects (sets, lists etc.) whether to validate + individual elements rather than the whole object. Defaults to False. + always (bool, optional): Whether this method and other validators should be called even if + the value is missing. Defaults to False. + check_fields (bool | None, optional): Whether to check that the fields actually exist on the model. + Defaults to None. + allow_reuse (bool, optional): Whether to track and raise an error if another validator refers to + the decorated function. Defaults to False. + + Returns: + Callable: A decorator that can be used to decorate a + function to be used as a validator. + """ + warn( + 'Pydantic V1 style `@validator` validators are deprecated.' + ' You should migrate to Pydantic V2 style `@field_validator` validators,' + ' see the migration guide for more details', + DeprecationWarning, + stacklevel=2, + ) + + if allow_reuse is True: # pragma: no cover + warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning) + fields = tuple((__field, *fields)) + if isinstance(fields[0], FunctionType): + raise PydanticUserError( + '`@validator` should be used with fields and keyword arguments, not bare. ' + "E.g. usage should be `@validator('', ...)`", + code='validator-no-fields', + ) + elif not all(isinstance(field, str) for field in fields): + raise PydanticUserError( + '`@validator` fields should be passed as separate string args. ' + "E.g. usage should be `@validator('', '', ...)`", + code='validator-invalid-fields', + ) + + mode: Literal['before', 'after'] = 'before' if pre is True else 'after' + + def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]: + if _decorators.is_instance_method_from_sig(f): + raise PydanticUserError( + '`@validator` cannot be applied to instance methods', code='validator-instance-method' + ) + # auto apply the @classmethod decorator + f = _decorators.ensure_classmethod_based_on_signature(f) + wrap = _decorators_v1.make_generic_v1_field_validator + validator_wrapper_info = _decorators.ValidatorDecoratorInfo( + fields=fields, + mode=mode, + each_item=each_item, + always=always, + check_fields=check_fields, + ) + return _decorators.PydanticDescriptorProxy(f, validator_wrapper_info, shim=wrap) + + return dec # type: ignore[return-value] + + +@overload +def root_validator( + *, + # if you don't specify `pre` the default is `pre=False` + # which means you need to specify `skip_on_failure=True` + skip_on_failure: Literal[True], + allow_reuse: bool = ..., +) -> Callable[ + [_V1RootValidatorFunctionType], + _V1RootValidatorFunctionType, +]: ... + + +@overload +def root_validator( + *, + # if you specify `pre=True` then you don't need to specify + # `skip_on_failure`, in fact it is not allowed as an argument! + pre: Literal[True], + allow_reuse: bool = ..., +) -> Callable[ + [_V1RootValidatorFunctionType], + _V1RootValidatorFunctionType, +]: ... + + +@overload +def root_validator( + *, + # if you explicitly specify `pre=False` then you + # MUST specify `skip_on_failure=True` + pre: Literal[False], + skip_on_failure: Literal[True], + allow_reuse: bool = ..., +) -> Callable[ + [_V1RootValidatorFunctionType], + _V1RootValidatorFunctionType, +]: ... + + +@deprecated( + 'Pydantic V1 style `@root_validator` validators are deprecated.' + ' You should migrate to Pydantic V2 style `@model_validator` validators,' + ' see the migration guide for more details', + category=None, +) +def root_validator( + *__args, + pre: bool = False, + skip_on_failure: bool = False, + allow_reuse: bool = False, +) -> Any: + """Decorate methods on a model indicating that they should be used to validate (and perhaps + modify) data either before or after standard model parsing/validation is performed. + + Args: + pre (bool, optional): Whether this validator should be called before the standard + validators (else after). Defaults to False. + skip_on_failure (bool, optional): Whether to stop validation and return as soon as a + failure is encountered. Defaults to False. + allow_reuse (bool, optional): Whether to track and raise an error if another validator + refers to the decorated function. Defaults to False. + + Returns: + Any: A decorator that can be used to decorate a function to be used as a root_validator. + """ + warn( + 'Pydantic V1 style `@root_validator` validators are deprecated.' + ' You should migrate to Pydantic V2 style `@model_validator` validators,' + ' see the migration guide for more details', + DeprecationWarning, + stacklevel=2, + ) + + if __args: + # Ensure a nice error is raised if someone attempts to use the bare decorator + return root_validator()(*__args) # type: ignore + + if allow_reuse is True: # pragma: no cover + warn(_ALLOW_REUSE_WARNING_MESSAGE, DeprecationWarning) + mode: Literal['before', 'after'] = 'before' if pre is True else 'after' + if pre is False and skip_on_failure is not True: + raise PydanticUserError( + 'If you use `@root_validator` with pre=False (the default) you MUST specify `skip_on_failure=True`.' + ' Note that `@root_validator` is deprecated and should be replaced with `@model_validator`.', + code='root-validator-pre-skip', + ) + + wrap = partial(_decorators_v1.make_v1_generic_root_validator, pre=pre) + + def dec(f: Callable[..., Any] | classmethod[Any, Any, Any] | staticmethod[Any, Any]) -> Any: + if _decorators.is_instance_method_from_sig(f): + raise TypeError('`@root_validator` cannot be applied to instance methods') + # auto apply the @classmethod decorator + res = _decorators.ensure_classmethod_based_on_signature(f) + dec_info = _decorators.RootValidatorDecoratorInfo(mode=mode) + return _decorators.PydanticDescriptorProxy(res, dec_info, shim=wrap) + + return dec diff --git a/env/Lib/site-packages/pydantic/deprecated/copy_internals.py b/env/Lib/site-packages/pydantic/deprecated/copy_internals.py new file mode 100644 index 0000000..efe5de2 --- /dev/null +++ b/env/Lib/site-packages/pydantic/deprecated/copy_internals.py @@ -0,0 +1,224 @@ +from __future__ import annotations as _annotations + +import typing +from copy import deepcopy +from enum import Enum +from typing import Any, Tuple + +import typing_extensions + +from .._internal import ( + _model_construction, + _typing_extra, + _utils, +) + +if typing.TYPE_CHECKING: + from .. import BaseModel + from .._internal._utils import AbstractSetIntStr, MappingIntStrAny + + AnyClassMethod = classmethod[Any, Any, Any] + TupleGenerator = typing.Generator[Tuple[str, Any], None, None] + Model = typing.TypeVar('Model', bound='BaseModel') + # should be `set[int] | set[str] | dict[int, IncEx] | dict[str, IncEx] | None`, but mypy can't cope + IncEx: typing_extensions.TypeAlias = 'set[int] | set[str] | dict[int, Any] | dict[str, Any] | None' + +_object_setattr = _model_construction.object_setattr + + +def _iter( + self: BaseModel, + to_dict: bool = False, + by_alias: bool = False, + include: AbstractSetIntStr | MappingIntStrAny | None = None, + exclude: AbstractSetIntStr | MappingIntStrAny | None = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, +) -> TupleGenerator: + # Merge field set excludes with explicit exclude parameter with explicit overriding field set options. + # The extra "is not None" guards are not logically necessary but optimizes performance for the simple case. + if exclude is not None: + exclude = _utils.ValueItems.merge( + {k: v.exclude for k, v in self.model_fields.items() if v.exclude is not None}, exclude + ) + + if include is not None: + include = _utils.ValueItems.merge({k: True for k in self.model_fields}, include, intersect=True) + + allowed_keys = _calculate_keys(self, include=include, exclude=exclude, exclude_unset=exclude_unset) # type: ignore + if allowed_keys is None and not (to_dict or by_alias or exclude_unset or exclude_defaults or exclude_none): + # huge boost for plain _iter() + yield from self.__dict__.items() + if self.__pydantic_extra__: + yield from self.__pydantic_extra__.items() + return + + value_exclude = _utils.ValueItems(self, exclude) if exclude is not None else None + value_include = _utils.ValueItems(self, include) if include is not None else None + + if self.__pydantic_extra__ is None: + items = self.__dict__.items() + else: + items = list(self.__dict__.items()) + list(self.__pydantic_extra__.items()) + + for field_key, v in items: + if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None): + continue + + if exclude_defaults: + try: + field = self.model_fields[field_key] + except KeyError: + pass + else: + if not field.is_required() and field.default == v: + continue + + if by_alias and field_key in self.model_fields: + dict_key = self.model_fields[field_key].alias or field_key + else: + dict_key = field_key + + if to_dict or value_include or value_exclude: + v = _get_value( + type(self), + v, + to_dict=to_dict, + by_alias=by_alias, + include=value_include and value_include.for_element(field_key), + exclude=value_exclude and value_exclude.for_element(field_key), + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + yield dict_key, v + + +def _copy_and_set_values( + self: Model, + values: dict[str, Any], + fields_set: set[str], + extra: dict[str, Any] | None = None, + private: dict[str, Any] | None = None, + *, + deep: bool, # UP006 +) -> Model: + if deep: + # chances of having empty dict here are quite low for using smart_deepcopy + values = deepcopy(values) + extra = deepcopy(extra) + private = deepcopy(private) + + cls = self.__class__ + m = cls.__new__(cls) + _object_setattr(m, '__dict__', values) + _object_setattr(m, '__pydantic_extra__', extra) + _object_setattr(m, '__pydantic_fields_set__', fields_set) + _object_setattr(m, '__pydantic_private__', private) + + return m + + +@typing.no_type_check +def _get_value( + cls: type[BaseModel], + v: Any, + to_dict: bool, + by_alias: bool, + include: AbstractSetIntStr | MappingIntStrAny | None, + exclude: AbstractSetIntStr | MappingIntStrAny | None, + exclude_unset: bool, + exclude_defaults: bool, + exclude_none: bool, +) -> Any: + from .. import BaseModel + + if isinstance(v, BaseModel): + if to_dict: + return v.model_dump( + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + include=include, # type: ignore + exclude=exclude, # type: ignore + exclude_none=exclude_none, + ) + else: + return v.copy(include=include, exclude=exclude) + + value_exclude = _utils.ValueItems(v, exclude) if exclude else None + value_include = _utils.ValueItems(v, include) if include else None + + if isinstance(v, dict): + return { + k_: _get_value( + cls, + v_, + to_dict=to_dict, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + include=value_include and value_include.for_element(k_), + exclude=value_exclude and value_exclude.for_element(k_), + exclude_none=exclude_none, + ) + for k_, v_ in v.items() + if (not value_exclude or not value_exclude.is_excluded(k_)) + and (not value_include or value_include.is_included(k_)) + } + + elif _utils.sequence_like(v): + seq_args = ( + _get_value( + cls, + v_, + to_dict=to_dict, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + include=value_include and value_include.for_element(i), + exclude=value_exclude and value_exclude.for_element(i), + exclude_none=exclude_none, + ) + for i, v_ in enumerate(v) + if (not value_exclude or not value_exclude.is_excluded(i)) + and (not value_include or value_include.is_included(i)) + ) + + return v.__class__(*seq_args) if _typing_extra.is_namedtuple(v.__class__) else v.__class__(seq_args) + + elif isinstance(v, Enum) and getattr(cls.model_config, 'use_enum_values', False): + return v.value + + else: + return v + + +def _calculate_keys( + self: BaseModel, + include: MappingIntStrAny | None, + exclude: MappingIntStrAny | None, + exclude_unset: bool, + update: typing.Dict[str, Any] | None = None, # noqa UP006 +) -> typing.AbstractSet[str] | None: + if include is None and exclude is None and exclude_unset is False: + return None + + keys: typing.AbstractSet[str] + if exclude_unset: + keys = self.__pydantic_fields_set__.copy() + else: + keys = set(self.__dict__.keys()) + keys = keys | (self.__pydantic_extra__ or {}).keys() + + if include is not None: + keys &= include.keys() + + if update: + keys -= update.keys() + + if exclude: + keys -= {k for k, v in exclude.items() if _utils.ValueItems.is_true(v)} + + return keys diff --git a/env/Lib/site-packages/pydantic/deprecated/decorator.py b/env/Lib/site-packages/pydantic/deprecated/decorator.py new file mode 100644 index 0000000..0c0ea74 --- /dev/null +++ b/env/Lib/site-packages/pydantic/deprecated/decorator.py @@ -0,0 +1,279 @@ +import warnings +from functools import wraps +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload + +from typing_extensions import deprecated + +from .._internal import _config, _typing_extra +from ..alias_generators import to_pascal +from ..errors import PydanticUserError +from ..functional_validators import field_validator +from ..main import BaseModel, create_model +from ..warnings import PydanticDeprecatedSince20 + +if not TYPE_CHECKING: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + +__all__ = ('validate_arguments',) + +if TYPE_CHECKING: + AnyCallable = Callable[..., Any] + + AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable) + ConfigType = Union[None, Type[Any], Dict[str, Any]] + + +@overload +def validate_arguments( + func: None = None, *, config: 'ConfigType' = None +) -> Callable[['AnyCallableT'], 'AnyCallableT']: ... + + +@overload +def validate_arguments(func: 'AnyCallableT') -> 'AnyCallableT': ... + + +@deprecated( + 'The `validate_arguments` method is deprecated; use `validate_call` instead.', + category=None, +) +def validate_arguments(func: Optional['AnyCallableT'] = None, *, config: 'ConfigType' = None) -> Any: + """Decorator to validate the arguments passed to a function.""" + warnings.warn( + 'The `validate_arguments` method is deprecated; use `validate_call` instead.', + PydanticDeprecatedSince20, + stacklevel=2, + ) + + def validate(_func: 'AnyCallable') -> 'AnyCallable': + vd = ValidatedFunction(_func, config) + + @wraps(_func) + def wrapper_function(*args: Any, **kwargs: Any) -> Any: + return vd.call(*args, **kwargs) + + wrapper_function.vd = vd # type: ignore + wrapper_function.validate = vd.init_model_instance # type: ignore + wrapper_function.raw_function = vd.raw_function # type: ignore + wrapper_function.model = vd.model # type: ignore + return wrapper_function + + if func: + return validate(func) + else: + return validate + + +ALT_V_ARGS = 'v__args' +ALT_V_KWARGS = 'v__kwargs' +V_POSITIONAL_ONLY_NAME = 'v__positional_only' +V_DUPLICATE_KWARGS = 'v__duplicate_kwargs' + + +class ValidatedFunction: + def __init__(self, function: 'AnyCallable', config: 'ConfigType'): + from inspect import Parameter, signature + + parameters: Mapping[str, Parameter] = signature(function).parameters + + if parameters.keys() & {ALT_V_ARGS, ALT_V_KWARGS, V_POSITIONAL_ONLY_NAME, V_DUPLICATE_KWARGS}: + raise PydanticUserError( + f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" ' + f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator', + code=None, + ) + + self.raw_function = function + self.arg_mapping: Dict[int, str] = {} + self.positional_only_args: set[str] = set() + self.v_args_name = 'args' + self.v_kwargs_name = 'kwargs' + + type_hints = _typing_extra.get_type_hints(function, include_extras=True) + takes_args = False + takes_kwargs = False + fields: Dict[str, Tuple[Any, Any]] = {} + for i, (name, p) in enumerate(parameters.items()): + if p.annotation is p.empty: + annotation = Any + else: + annotation = type_hints[name] + + default = ... if p.default is p.empty else p.default + if p.kind == Parameter.POSITIONAL_ONLY: + self.arg_mapping[i] = name + fields[name] = annotation, default + fields[V_POSITIONAL_ONLY_NAME] = List[str], None + self.positional_only_args.add(name) + elif p.kind == Parameter.POSITIONAL_OR_KEYWORD: + self.arg_mapping[i] = name + fields[name] = annotation, default + fields[V_DUPLICATE_KWARGS] = List[str], None + elif p.kind == Parameter.KEYWORD_ONLY: + fields[name] = annotation, default + elif p.kind == Parameter.VAR_POSITIONAL: + self.v_args_name = name + fields[name] = Tuple[annotation, ...], None + takes_args = True + else: + assert p.kind == Parameter.VAR_KEYWORD, p.kind + self.v_kwargs_name = name + fields[name] = Dict[str, annotation], None + takes_kwargs = True + + # these checks avoid a clash between "args" and a field with that name + if not takes_args and self.v_args_name in fields: + self.v_args_name = ALT_V_ARGS + + # same with "kwargs" + if not takes_kwargs and self.v_kwargs_name in fields: + self.v_kwargs_name = ALT_V_KWARGS + + if not takes_args: + # we add the field so validation below can raise the correct exception + fields[self.v_args_name] = List[Any], None + + if not takes_kwargs: + # same with kwargs + fields[self.v_kwargs_name] = Dict[Any, Any], None + + self.create_model(fields, takes_args, takes_kwargs, config) + + def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel: + values = self.build_values(args, kwargs) + return self.model(**values) + + def call(self, *args: Any, **kwargs: Any) -> Any: + m = self.init_model_instance(*args, **kwargs) + return self.execute(m) + + def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[str, Any]: + values: Dict[str, Any] = {} + if args: + arg_iter = enumerate(args) + while True: + try: + i, a = next(arg_iter) + except StopIteration: + break + arg_name = self.arg_mapping.get(i) + if arg_name is not None: + values[arg_name] = a + else: + values[self.v_args_name] = [a] + [a for _, a in arg_iter] + break + + var_kwargs: Dict[str, Any] = {} + wrong_positional_args = [] + duplicate_kwargs = [] + fields_alias = [ + field.alias + for name, field in self.model.model_fields.items() + if name not in (self.v_args_name, self.v_kwargs_name) + ] + non_var_fields = set(self.model.model_fields) - {self.v_args_name, self.v_kwargs_name} + for k, v in kwargs.items(): + if k in non_var_fields or k in fields_alias: + if k in self.positional_only_args: + wrong_positional_args.append(k) + if k in values: + duplicate_kwargs.append(k) + values[k] = v + else: + var_kwargs[k] = v + + if var_kwargs: + values[self.v_kwargs_name] = var_kwargs + if wrong_positional_args: + values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args + if duplicate_kwargs: + values[V_DUPLICATE_KWARGS] = duplicate_kwargs + return values + + def execute(self, m: BaseModel) -> Any: + d = {k: v for k, v in m.__dict__.items() if k in m.__pydantic_fields_set__ or m.model_fields[k].default_factory} + var_kwargs = d.pop(self.v_kwargs_name, {}) + + if self.v_args_name in d: + args_: List[Any] = [] + in_kwargs = False + kwargs = {} + for name, value in d.items(): + if in_kwargs: + kwargs[name] = value + elif name == self.v_args_name: + args_ += value + in_kwargs = True + else: + args_.append(value) + return self.raw_function(*args_, **kwargs, **var_kwargs) + elif self.positional_only_args: + args_ = [] + kwargs = {} + for name, value in d.items(): + if name in self.positional_only_args: + args_.append(value) + else: + kwargs[name] = value + return self.raw_function(*args_, **kwargs, **var_kwargs) + else: + return self.raw_function(**d, **var_kwargs) + + def create_model(self, fields: Dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None: + pos_args = len(self.arg_mapping) + + config_wrapper = _config.ConfigWrapper(config) + + if config_wrapper.alias_generator: + raise PydanticUserError( + 'Setting the "alias_generator" property on custom Config for ' + '@validate_arguments is not yet supported, please remove.', + code=None, + ) + if config_wrapper.extra is None: + config_wrapper.config_dict['extra'] = 'forbid' + + class DecoratorBaseModel(BaseModel): + @field_validator(self.v_args_name, check_fields=False) + @classmethod + def check_args(cls, v: Optional[List[Any]]) -> Optional[List[Any]]: + if takes_args or v is None: + return v + + raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given') + + @field_validator(self.v_kwargs_name, check_fields=False) + @classmethod + def check_kwargs(cls, v: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: + if takes_kwargs or v is None: + return v + + plural = '' if len(v) == 1 else 's' + keys = ', '.join(map(repr, v.keys())) + raise TypeError(f'unexpected keyword argument{plural}: {keys}') + + @field_validator(V_POSITIONAL_ONLY_NAME, check_fields=False) + @classmethod + def check_positional_only(cls, v: Optional[List[str]]) -> None: + if v is None: + return + + plural = '' if len(v) == 1 else 's' + keys = ', '.join(map(repr, v)) + raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}') + + @field_validator(V_DUPLICATE_KWARGS, check_fields=False) + @classmethod + def check_duplicate_kwargs(cls, v: Optional[List[str]]) -> None: + if v is None: + return + + plural = '' if len(v) == 1 else 's' + keys = ', '.join(map(repr, v)) + raise TypeError(f'multiple values for argument{plural}: {keys}') + + model_config = config_wrapper.config_dict + + self.model = create_model(to_pascal(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields) diff --git a/env/Lib/site-packages/pydantic/deprecated/json.py b/env/Lib/site-packages/pydantic/deprecated/json.py new file mode 100644 index 0000000..9ba5256 --- /dev/null +++ b/env/Lib/site-packages/pydantic/deprecated/json.py @@ -0,0 +1,140 @@ +import datetime +import warnings +from collections import deque +from decimal import Decimal +from enum import Enum +from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network +from pathlib import Path +from re import Pattern +from types import GeneratorType +from typing import TYPE_CHECKING, Any, Callable, Dict, Type, Union +from uuid import UUID + +from typing_extensions import deprecated + +from ..color import Color +from ..networks import NameEmail +from ..types import SecretBytes, SecretStr +from ..warnings import PydanticDeprecatedSince20 + +if not TYPE_CHECKING: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + +__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat' + + +def isoformat(o: Union[datetime.date, datetime.time]) -> str: + return o.isoformat() + + +def decimal_encoder(dec_value: Decimal) -> Union[int, float]: + """Encodes a Decimal as int of there's no exponent, otherwise float. + + This is useful when we use ConstrainedDecimal to represent Numeric(x,0) + where a integer (but not int typed) is used. Encoding this as a float + results in failed round-tripping between encode and parse. + Our Id type is a prime example of this. + + >>> decimal_encoder(Decimal("1.0")) + 1.0 + + >>> decimal_encoder(Decimal("1")) + 1 + """ + exponent = dec_value.as_tuple().exponent + if isinstance(exponent, int) and exponent >= 0: + return int(dec_value) + else: + return float(dec_value) + + +ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { + bytes: lambda o: o.decode(), + Color: str, + datetime.date: isoformat, + datetime.datetime: isoformat, + datetime.time: isoformat, + datetime.timedelta: lambda td: td.total_seconds(), + Decimal: decimal_encoder, + Enum: lambda o: o.value, + frozenset: list, + deque: list, + GeneratorType: list, + IPv4Address: str, + IPv4Interface: str, + IPv4Network: str, + IPv6Address: str, + IPv6Interface: str, + IPv6Network: str, + NameEmail: str, + Path: str, + Pattern: lambda o: o.pattern, + SecretBytes: str, + SecretStr: str, + set: list, + UUID: str, +} + + +@deprecated( + '`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.', + category=None, +) +def pydantic_encoder(obj: Any) -> Any: + warnings.warn( + '`pydantic_encoder` is deprecated, use `pydantic_core.to_jsonable_python` instead.', + category=PydanticDeprecatedSince20, + stacklevel=2, + ) + from dataclasses import asdict, is_dataclass + + from ..main import BaseModel + + if isinstance(obj, BaseModel): + return obj.model_dump() + elif is_dataclass(obj): + return asdict(obj) # type: ignore + + # Check the class type and its superclasses for a matching encoder + for base in obj.__class__.__mro__[:-1]: + try: + encoder = ENCODERS_BY_TYPE[base] + except KeyError: + continue + return encoder(obj) + else: # We have exited the for loop without finding a suitable encoder + raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") + + +# TODO: Add a suggested migration path once there is a way to use custom encoders +@deprecated( + '`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.', + category=None, +) +def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any: + warnings.warn( + '`custom_pydantic_encoder` is deprecated, use `BaseModel.model_dump` instead.', + category=PydanticDeprecatedSince20, + stacklevel=2, + ) + # Check the class type and its superclasses for a matching encoder + for base in obj.__class__.__mro__[:-1]: + try: + encoder = type_encoders[base] + except KeyError: + continue + + return encoder(obj) + else: # We have exited the for loop without finding a suitable encoder + return pydantic_encoder(obj) + + +@deprecated('`timedelta_isoformat` is deprecated.', category=None) +def timedelta_isoformat(td: datetime.timedelta) -> str: + """ISO 8601 encoding for Python timedelta object.""" + warnings.warn('`timedelta_isoformat` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2) + minutes, seconds = divmod(td.seconds, 60) + hours, minutes = divmod(minutes, 60) + return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S' diff --git a/env/Lib/site-packages/pydantic/deprecated/parse.py b/env/Lib/site-packages/pydantic/deprecated/parse.py new file mode 100644 index 0000000..2a92e62 --- /dev/null +++ b/env/Lib/site-packages/pydantic/deprecated/parse.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +import json +import pickle +import warnings +from enum import Enum +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable + +from typing_extensions import deprecated + +from ..warnings import PydanticDeprecatedSince20 + +if not TYPE_CHECKING: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + + +class Protocol(str, Enum): + json = 'json' + pickle = 'pickle' + + +@deprecated('`load_str_bytes` is deprecated.', category=None) +def load_str_bytes( + b: str | bytes, + *, + content_type: str | None = None, + encoding: str = 'utf8', + proto: Protocol | None = None, + allow_pickle: bool = False, + json_loads: Callable[[str], Any] = json.loads, +) -> Any: + warnings.warn('`load_str_bytes` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2) + if proto is None and content_type: + if content_type.endswith(('json', 'javascript')): + pass + elif allow_pickle and content_type.endswith('pickle'): + proto = Protocol.pickle + else: + raise TypeError(f'Unknown content-type: {content_type}') + + proto = proto or Protocol.json + + if proto == Protocol.json: + if isinstance(b, bytes): + b = b.decode(encoding) + return json_loads(b) # type: ignore + elif proto == Protocol.pickle: + if not allow_pickle: + raise RuntimeError('Trying to decode with pickle with allow_pickle=False') + bb = b if isinstance(b, bytes) else b.encode() # type: ignore + return pickle.loads(bb) + else: + raise TypeError(f'Unknown protocol: {proto}') + + +@deprecated('`load_file` is deprecated.', category=None) +def load_file( + path: str | Path, + *, + content_type: str | None = None, + encoding: str = 'utf8', + proto: Protocol | None = None, + allow_pickle: bool = False, + json_loads: Callable[[str], Any] = json.loads, +) -> Any: + warnings.warn('`load_file` is deprecated.', category=PydanticDeprecatedSince20, stacklevel=2) + path = Path(path) + b = path.read_bytes() + if content_type is None: + if path.suffix in ('.js', '.json'): + proto = Protocol.json + elif path.suffix == '.pkl': + proto = Protocol.pickle + + return load_str_bytes( + b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads + ) diff --git a/env/Lib/site-packages/pydantic/deprecated/tools.py b/env/Lib/site-packages/pydantic/deprecated/tools.py new file mode 100644 index 0000000..b04eae4 --- /dev/null +++ b/env/Lib/site-packages/pydantic/deprecated/tools.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import json +import warnings +from typing import TYPE_CHECKING, Any, Callable, Type, TypeVar, Union + +from typing_extensions import deprecated + +from ..json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema +from ..type_adapter import TypeAdapter +from ..warnings import PydanticDeprecatedSince20 + +if not TYPE_CHECKING: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + +__all__ = 'parse_obj_as', 'schema_of', 'schema_json_of' + +NameFactory = Union[str, Callable[[Type[Any]], str]] + + +T = TypeVar('T') + + +@deprecated( + '`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.', + category=None, +) +def parse_obj_as(type_: type[T], obj: Any, type_name: NameFactory | None = None) -> T: + warnings.warn( + '`parse_obj_as` is deprecated. Use `pydantic.TypeAdapter.validate_python` instead.', + category=PydanticDeprecatedSince20, + stacklevel=2, + ) + if type_name is not None: # pragma: no cover + warnings.warn( + 'The type_name parameter is deprecated. parse_obj_as no longer creates temporary models', + DeprecationWarning, + stacklevel=2, + ) + return TypeAdapter(type_).validate_python(obj) + + +@deprecated( + '`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.', + category=None, +) +def schema_of( + type_: Any, + *, + title: NameFactory | None = None, + by_alias: bool = True, + ref_template: str = DEFAULT_REF_TEMPLATE, + schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, +) -> dict[str, Any]: + """Generate a JSON schema (as dict) for the passed model or dynamically generated one.""" + warnings.warn( + '`schema_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.', + category=PydanticDeprecatedSince20, + stacklevel=2, + ) + res = TypeAdapter(type_).json_schema( + by_alias=by_alias, + schema_generator=schema_generator, + ref_template=ref_template, + ) + if title is not None: + if isinstance(title, str): + res['title'] = title + else: + warnings.warn( + 'Passing a callable for the `title` parameter is deprecated and no longer supported', + DeprecationWarning, + stacklevel=2, + ) + res['title'] = title(type_) + return res + + +@deprecated( + '`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.', + category=None, +) +def schema_json_of( + type_: Any, + *, + title: NameFactory | None = None, + by_alias: bool = True, + ref_template: str = DEFAULT_REF_TEMPLATE, + schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, + **dumps_kwargs: Any, +) -> str: + """Generate a JSON schema (as JSON) for the passed model or dynamically generated one.""" + warnings.warn( + '`schema_json_of` is deprecated. Use `pydantic.TypeAdapter.json_schema` instead.', + category=PydanticDeprecatedSince20, + stacklevel=2, + ) + return json.dumps( + schema_of(type_, title=title, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator), + **dumps_kwargs, + ) diff --git a/env/Lib/site-packages/pydantic/env_settings.py b/env/Lib/site-packages/pydantic/env_settings.py new file mode 100644 index 0000000..cd0b04e --- /dev/null +++ b/env/Lib/site-packages/pydantic/env_settings.py @@ -0,0 +1,5 @@ +"""The `env_settings` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/error_wrappers.py b/env/Lib/site-packages/pydantic/error_wrappers.py new file mode 100644 index 0000000..2985419 --- /dev/null +++ b/env/Lib/site-packages/pydantic/error_wrappers.py @@ -0,0 +1,5 @@ +"""The `error_wrappers` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/errors.py b/env/Lib/site-packages/pydantic/errors.py new file mode 100644 index 0000000..de2e512 --- /dev/null +++ b/env/Lib/site-packages/pydantic/errors.py @@ -0,0 +1,156 @@ +"""Pydantic-specific errors.""" + +from __future__ import annotations as _annotations + +import re + +from typing_extensions import Literal, Self + +from ._migration import getattr_migration +from .version import version_short + +__all__ = ( + 'PydanticUserError', + 'PydanticUndefinedAnnotation', + 'PydanticImportError', + 'PydanticSchemaGenerationError', + 'PydanticInvalidForJsonSchema', + 'PydanticErrorCodes', +) + +# We use this URL to allow for future flexibility about how we host the docs, while allowing for Pydantic +# code in the while with "old" URLs to still work. +# 'u' refers to "user errors" - e.g. errors caused by developers using pydantic, as opposed to validation errors. +DEV_ERROR_DOCS_URL = f'https://errors.pydantic.dev/{version_short()}/u/' +PydanticErrorCodes = Literal[ + 'class-not-fully-defined', + 'custom-json-schema', + 'decorator-missing-field', + 'discriminator-no-field', + 'discriminator-alias-type', + 'discriminator-needs-literal', + 'discriminator-alias', + 'discriminator-validator', + 'callable-discriminator-no-tag', + 'typed-dict-version', + 'model-field-overridden', + 'model-field-missing-annotation', + 'config-both', + 'removed-kwargs', + 'invalid-for-json-schema', + 'json-schema-already-used', + 'base-model-instantiated', + 'undefined-annotation', + 'schema-for-unknown-type', + 'import-error', + 'create-model-field-definitions', + 'create-model-config-base', + 'validator-no-fields', + 'validator-invalid-fields', + 'validator-instance-method', + 'root-validator-pre-skip', + 'model-serializer-instance-method', + 'validator-field-config-info', + 'validator-v1-signature', + 'validator-signature', + 'field-serializer-signature', + 'model-serializer-signature', + 'multiple-field-serializers', + 'invalid_annotated_type', + 'type-adapter-config-unused', + 'root-model-extra', + 'unevaluable-type-annotation', + 'dataclass-init-false-extra-allow', + 'clashing-init-and-init-var', + 'model-config-invalid-field-name', + 'with-config-on-model', + 'dataclass-on-model', +] + + +class PydanticErrorMixin: + """A mixin class for common functionality shared by all Pydantic-specific errors. + + Attributes: + message: A message describing the error. + code: An optional error code from PydanticErrorCodes enum. + """ + + def __init__(self, message: str, *, code: PydanticErrorCodes | None) -> None: + self.message = message + self.code = code + + def __str__(self) -> str: + if self.code is None: + return self.message + else: + return f'{self.message}\n\nFor further information visit {DEV_ERROR_DOCS_URL}{self.code}' + + +class PydanticUserError(PydanticErrorMixin, TypeError): + """An error raised due to incorrect use of Pydantic.""" + + +class PydanticUndefinedAnnotation(PydanticErrorMixin, NameError): + """A subclass of `NameError` raised when handling undefined annotations during `CoreSchema` generation. + + Attributes: + name: Name of the error. + message: Description of the error. + """ + + def __init__(self, name: str, message: str) -> None: + self.name = name + super().__init__(message=message, code='undefined-annotation') + + @classmethod + def from_name_error(cls, name_error: NameError) -> Self: + """Convert a `NameError` to a `PydanticUndefinedAnnotation` error. + + Args: + name_error: `NameError` to be converted. + + Returns: + Converted `PydanticUndefinedAnnotation` error. + """ + try: + name = name_error.name # type: ignore # python > 3.10 + except AttributeError: + name = re.search(r".*'(.+?)'", str(name_error)).group(1) # type: ignore[union-attr] + return cls(name=name, message=str(name_error)) + + +class PydanticImportError(PydanticErrorMixin, ImportError): + """An error raised when an import fails due to module changes between V1 and V2. + + Attributes: + message: Description of the error. + """ + + def __init__(self, message: str) -> None: + super().__init__(message, code='import-error') + + +class PydanticSchemaGenerationError(PydanticUserError): + """An error raised during failures to generate a `CoreSchema` for some type. + + Attributes: + message: Description of the error. + """ + + def __init__(self, message: str) -> None: + super().__init__(message, code='schema-for-unknown-type') + + +class PydanticInvalidForJsonSchema(PydanticUserError): + """An error raised during failures to generate a JSON schema for some `CoreSchema`. + + Attributes: + message: Description of the error. + """ + + def __init__(self, message: str) -> None: + super().__init__(message, code='invalid-for-json-schema') + + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/experimental/__init__.py b/env/Lib/site-packages/pydantic/experimental/__init__.py new file mode 100644 index 0000000..4aa58c6 --- /dev/null +++ b/env/Lib/site-packages/pydantic/experimental/__init__.py @@ -0,0 +1,10 @@ +"""The "experimental" module of pydantic contains potential new features that are subject to change.""" + +import warnings + +from pydantic.warnings import PydanticExperimentalWarning + +warnings.warn( + 'This module is experimental, its contents are subject to change and deprecation.', + category=PydanticExperimentalWarning, +) diff --git a/env/Lib/site-packages/pydantic/experimental/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/pydantic/experimental/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..a818f6a Binary files /dev/null and b/env/Lib/site-packages/pydantic/experimental/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/experimental/__pycache__/pipeline.cpython-311.pyc b/env/Lib/site-packages/pydantic/experimental/__pycache__/pipeline.cpython-311.pyc new file mode 100644 index 0000000..f9ba03b Binary files /dev/null and b/env/Lib/site-packages/pydantic/experimental/__pycache__/pipeline.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/experimental/pipeline.py b/env/Lib/site-packages/pydantic/experimental/pipeline.py new file mode 100644 index 0000000..29da979 --- /dev/null +++ b/env/Lib/site-packages/pydantic/experimental/pipeline.py @@ -0,0 +1,669 @@ +"""Experimental pipeline API functionality. Be careful with this API, it's subject to change.""" + +from __future__ import annotations + +import datetime +import operator +import re +import sys +from collections import deque +from collections.abc import Container +from dataclasses import dataclass +from decimal import Decimal +from functools import cached_property, partial +from typing import TYPE_CHECKING, Any, Callable, Generic, Pattern, Protocol, TypeVar, Union, overload + +import annotated_types +from typing_extensions import Annotated + +if TYPE_CHECKING: + from pydantic_core import core_schema as cs + + from pydantic import GetCoreSchemaHandler + +from pydantic._internal._internal_dataclass import slots_true as _slots_true + +if sys.version_info < (3, 10): + EllipsisType = type(Ellipsis) +else: + from types import EllipsisType + +__all__ = ['validate_as', 'validate_as_deferred', 'transform'] + +_slots_frozen = {**_slots_true, 'frozen': True} + + +@dataclass(**_slots_frozen) +class _ValidateAs: + tp: type[Any] + strict: bool = False + + +@dataclass +class _ValidateAsDefer: + func: Callable[[], type[Any]] + + @cached_property + def tp(self) -> type[Any]: + return self.func() + + +@dataclass(**_slots_frozen) +class _Transform: + func: Callable[[Any], Any] + + +@dataclass(**_slots_frozen) +class _PipelineOr: + left: _Pipeline[Any, Any] + right: _Pipeline[Any, Any] + + +@dataclass(**_slots_frozen) +class _PipelineAnd: + left: _Pipeline[Any, Any] + right: _Pipeline[Any, Any] + + +@dataclass(**_slots_frozen) +class _Eq: + value: Any + + +@dataclass(**_slots_frozen) +class _NotEq: + value: Any + + +@dataclass(**_slots_frozen) +class _In: + values: Container[Any] + + +@dataclass(**_slots_frozen) +class _NotIn: + values: Container[Any] + + +_ConstraintAnnotation = Union[ + annotated_types.Le, + annotated_types.Ge, + annotated_types.Lt, + annotated_types.Gt, + annotated_types.Len, + annotated_types.MultipleOf, + annotated_types.Timezone, + annotated_types.Interval, + annotated_types.Predicate, + # common predicates not included in annotated_types + _Eq, + _NotEq, + _In, + _NotIn, + # regular expressions + Pattern[str], +] + + +@dataclass(**_slots_frozen) +class _Constraint: + constraint: _ConstraintAnnotation + + +_Step = Union[_ValidateAs, _ValidateAsDefer, _Transform, _PipelineOr, _PipelineAnd, _Constraint] + +_InT = TypeVar('_InT') +_OutT = TypeVar('_OutT') +_NewOutT = TypeVar('_NewOutT') + + +class _FieldTypeMarker: + pass + + +# TODO: ultimately, make this public, see https://github.com/pydantic/pydantic/pull/9459#discussion_r1628197626 +# Also, make this frozen eventually, but that doesn't work right now because of the generic base +# Which attempts to modify __orig_base__ and such. +# We could go with a manual freeze, but that seems overkill for now. +@dataclass(**_slots_true) +class _Pipeline(Generic[_InT, _OutT]): + """Abstract representation of a chain of validation, transformation, and parsing steps.""" + + _steps: tuple[_Step, ...] + + def transform( + self, + func: Callable[[_OutT], _NewOutT], + ) -> _Pipeline[_InT, _NewOutT]: + """Transform the output of the previous step. + + If used as the first step in a pipeline, the type of the field is used. + That is, the transformation is applied to after the value is parsed to the field's type. + """ + return _Pipeline[_InT, _NewOutT](self._steps + (_Transform(func),)) + + @overload + def validate_as(self, tp: type[_NewOutT], *, strict: bool = ...) -> _Pipeline[_InT, _NewOutT]: ... + + @overload + def validate_as(self, tp: EllipsisType, *, strict: bool = ...) -> _Pipeline[_InT, Any]: # type: ignore + ... + + def validate_as(self, tp: type[_NewOutT] | EllipsisType, *, strict: bool = False) -> _Pipeline[_InT, Any]: # type: ignore + """Validate / parse the input into a new type. + + If no type is provided, the type of the field is used. + + Types are parsed in Pydantic's `lax` mode by default, + but you can enable `strict` mode by passing `strict=True`. + """ + if isinstance(tp, EllipsisType): + return _Pipeline[_InT, Any](self._steps + (_ValidateAs(_FieldTypeMarker, strict=strict),)) + return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAs(tp, strict=strict),)) + + def validate_as_deferred(self, func: Callable[[], type[_NewOutT]]) -> _Pipeline[_InT, _NewOutT]: + """Parse the input into a new type, deferring resolution of the type until the current class + is fully defined. + + This is useful when you need to reference the class in it's own type annotations. + """ + return _Pipeline[_InT, _NewOutT](self._steps + (_ValidateAsDefer(func),)) + + # constraints + @overload + def constrain(self: _Pipeline[_InT, _NewOutGe], constraint: annotated_types.Ge) -> _Pipeline[_InT, _NewOutGe]: ... + + @overload + def constrain(self: _Pipeline[_InT, _NewOutGt], constraint: annotated_types.Gt) -> _Pipeline[_InT, _NewOutGt]: ... + + @overload + def constrain(self: _Pipeline[_InT, _NewOutLe], constraint: annotated_types.Le) -> _Pipeline[_InT, _NewOutLe]: ... + + @overload + def constrain(self: _Pipeline[_InT, _NewOutLt], constraint: annotated_types.Lt) -> _Pipeline[_InT, _NewOutLt]: ... + + @overload + def constrain( + self: _Pipeline[_InT, _NewOutLen], constraint: annotated_types.Len + ) -> _Pipeline[_InT, _NewOutLen]: ... + + @overload + def constrain( + self: _Pipeline[_InT, _NewOutT], constraint: annotated_types.MultipleOf + ) -> _Pipeline[_InT, _NewOutT]: ... + + @overload + def constrain( + self: _Pipeline[_InT, _NewOutDatetime], constraint: annotated_types.Timezone + ) -> _Pipeline[_InT, _NewOutDatetime]: ... + + @overload + def constrain(self: _Pipeline[_InT, _OutT], constraint: annotated_types.Predicate) -> _Pipeline[_InT, _OutT]: ... + + @overload + def constrain( + self: _Pipeline[_InT, _NewOutInterval], constraint: annotated_types.Interval + ) -> _Pipeline[_InT, _NewOutInterval]: ... + + @overload + def constrain(self: _Pipeline[_InT, _OutT], constraint: _Eq) -> _Pipeline[_InT, _OutT]: ... + + @overload + def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotEq) -> _Pipeline[_InT, _OutT]: ... + + @overload + def constrain(self: _Pipeline[_InT, _OutT], constraint: _In) -> _Pipeline[_InT, _OutT]: ... + + @overload + def constrain(self: _Pipeline[_InT, _OutT], constraint: _NotIn) -> _Pipeline[_InT, _OutT]: ... + + @overload + def constrain(self: _Pipeline[_InT, _NewOutT], constraint: Pattern[str]) -> _Pipeline[_InT, _NewOutT]: ... + + def constrain(self, constraint: _ConstraintAnnotation) -> Any: + """Constrain a value to meet a certain condition. + + We support most conditions from `annotated_types`, as well as regular expressions. + + Most of the time you'll be calling a shortcut method like `gt`, `lt`, `len`, etc + so you don't need to call this directly. + """ + return _Pipeline[_InT, _OutT](self._steps + (_Constraint(constraint),)) + + def predicate(self: _Pipeline[_InT, _NewOutT], func: Callable[[_NewOutT], bool]) -> _Pipeline[_InT, _NewOutT]: + """Constrain a value to meet a certain predicate.""" + return self.constrain(annotated_types.Predicate(func)) + + def gt(self: _Pipeline[_InT, _NewOutGt], gt: _NewOutGt) -> _Pipeline[_InT, _NewOutGt]: + """Constrain a value to be greater than a certain value.""" + return self.constrain(annotated_types.Gt(gt)) + + def lt(self: _Pipeline[_InT, _NewOutLt], lt: _NewOutLt) -> _Pipeline[_InT, _NewOutLt]: + """Constrain a value to be less than a certain value.""" + return self.constrain(annotated_types.Lt(lt)) + + def ge(self: _Pipeline[_InT, _NewOutGe], ge: _NewOutGe) -> _Pipeline[_InT, _NewOutGe]: + """Constrain a value to be greater than or equal to a certain value.""" + return self.constrain(annotated_types.Ge(ge)) + + def le(self: _Pipeline[_InT, _NewOutLe], le: _NewOutLe) -> _Pipeline[_InT, _NewOutLe]: + """Constrain a value to be less than or equal to a certain value.""" + return self.constrain(annotated_types.Le(le)) + + def len(self: _Pipeline[_InT, _NewOutLen], min_len: int, max_len: int | None = None) -> _Pipeline[_InT, _NewOutLen]: + """Constrain a value to have a certain length.""" + return self.constrain(annotated_types.Len(min_len, max_len)) + + @overload + def multiple_of(self: _Pipeline[_InT, _NewOutDiv], multiple_of: _NewOutDiv) -> _Pipeline[_InT, _NewOutDiv]: ... + + @overload + def multiple_of(self: _Pipeline[_InT, _NewOutMod], multiple_of: _NewOutMod) -> _Pipeline[_InT, _NewOutMod]: ... + + def multiple_of(self: _Pipeline[_InT, Any], multiple_of: Any) -> _Pipeline[_InT, Any]: + """Constrain a value to be a multiple of a certain number.""" + return self.constrain(annotated_types.MultipleOf(multiple_of)) + + def eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]: + """Constrain a value to be equal to a certain value.""" + return self.constrain(_Eq(value)) + + def not_eq(self: _Pipeline[_InT, _OutT], value: _OutT) -> _Pipeline[_InT, _OutT]: + """Constrain a value to not be equal to a certain value.""" + return self.constrain(_NotEq(value)) + + def in_(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]: + """Constrain a value to be in a certain set.""" + return self.constrain(_In(values)) + + def not_in(self: _Pipeline[_InT, _OutT], values: Container[_OutT]) -> _Pipeline[_InT, _OutT]: + """Constrain a value to not be in a certain set.""" + return self.constrain(_NotIn(values)) + + # timezone methods + def datetime_tz_naive(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]: + return self.constrain(annotated_types.Timezone(None)) + + def datetime_tz_aware(self: _Pipeline[_InT, datetime.datetime]) -> _Pipeline[_InT, datetime.datetime]: + return self.constrain(annotated_types.Timezone(...)) + + def datetime_tz( + self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo + ) -> _Pipeline[_InT, datetime.datetime]: + return self.constrain(annotated_types.Timezone(tz)) # type: ignore + + def datetime_with_tz( + self: _Pipeline[_InT, datetime.datetime], tz: datetime.tzinfo | None + ) -> _Pipeline[_InT, datetime.datetime]: + return self.transform(partial(datetime.datetime.replace, tzinfo=tz)) + + # string methods + def str_lower(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]: + return self.transform(str.lower) + + def str_upper(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]: + return self.transform(str.upper) + + def str_title(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]: + return self.transform(str.title) + + def str_strip(self: _Pipeline[_InT, str]) -> _Pipeline[_InT, str]: + return self.transform(str.strip) + + def str_pattern(self: _Pipeline[_InT, str], pattern: str) -> _Pipeline[_InT, str]: + return self.constrain(re.compile(pattern)) + + def str_contains(self: _Pipeline[_InT, str], substring: str) -> _Pipeline[_InT, str]: + return self.predicate(lambda v: substring in v) + + def str_starts_with(self: _Pipeline[_InT, str], prefix: str) -> _Pipeline[_InT, str]: + return self.predicate(lambda v: v.startswith(prefix)) + + def str_ends_with(self: _Pipeline[_InT, str], suffix: str) -> _Pipeline[_InT, str]: + return self.predicate(lambda v: v.endswith(suffix)) + + # operators + def otherwise(self, other: _Pipeline[_OtherIn, _OtherOut]) -> _Pipeline[_InT | _OtherIn, _OutT | _OtherOut]: + """Combine two validation chains, returning the result of the first chain if it succeeds, and the second chain if it fails.""" + return _Pipeline((_PipelineOr(self, other),)) + + __or__ = otherwise + + def then(self, other: _Pipeline[_OutT, _OtherOut]) -> _Pipeline[_InT, _OtherOut]: + """Pipe the result of one validation chain into another.""" + return _Pipeline((_PipelineAnd(self, other),)) + + __and__ = then + + def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> cs.CoreSchema: + from pydantic_core import core_schema as cs + + queue = deque(self._steps) + + s = None + + while queue: + step = queue.popleft() + s = _apply_step(step, s, handler, source_type) + + s = s or cs.any_schema() + return s + + def __supports_type__(self, _: _OutT) -> bool: + raise NotImplementedError + + +validate_as = _Pipeline[Any, Any](()).validate_as +validate_as_deferred = _Pipeline[Any, Any](()).validate_as_deferred +transform = _Pipeline[Any, Any]((_ValidateAs(_FieldTypeMarker),)).transform + + +def _check_func( + func: Callable[[Any], bool], predicate_err: str | Callable[[], str], s: cs.CoreSchema | None +) -> cs.CoreSchema: + from pydantic_core import core_schema as cs + + def handler(v: Any) -> Any: + if func(v): + return v + raise ValueError(f'Expected {predicate_err if isinstance(predicate_err, str) else predicate_err()}') + + if s is None: + return cs.no_info_plain_validator_function(handler) + else: + return cs.no_info_after_validator_function(handler, s) + + +def _apply_step(step: _Step, s: cs.CoreSchema | None, handler: GetCoreSchemaHandler, source_type: Any) -> cs.CoreSchema: + from pydantic_core import core_schema as cs + + if isinstance(step, _ValidateAs): + s = _apply_parse(s, step.tp, step.strict, handler, source_type) + elif isinstance(step, _ValidateAsDefer): + s = _apply_parse(s, step.tp, False, handler, source_type) + elif isinstance(step, _Transform): + s = _apply_transform(s, step.func, handler) + elif isinstance(step, _Constraint): + s = _apply_constraint(s, step.constraint) + elif isinstance(step, _PipelineOr): + s = cs.union_schema([handler(step.left), handler(step.right)]) + else: + assert isinstance(step, _PipelineAnd) + s = cs.chain_schema([handler(step.left), handler(step.right)]) + return s + + +def _apply_parse( + s: cs.CoreSchema | None, + tp: type[Any], + strict: bool, + handler: GetCoreSchemaHandler, + source_type: Any, +) -> cs.CoreSchema: + from pydantic_core import core_schema as cs + + from pydantic import Strict + + if tp is _FieldTypeMarker: + return handler(source_type) + + if strict: + tp = Annotated[tp, Strict()] # type: ignore + + if s and s['type'] == 'any': + return handler(tp) + else: + return cs.chain_schema([s, handler(tp)]) if s else handler(tp) + + +def _apply_transform( + s: cs.CoreSchema | None, func: Callable[[Any], Any], handler: GetCoreSchemaHandler +) -> cs.CoreSchema: + from pydantic_core import core_schema as cs + + if s is None: + return cs.no_info_plain_validator_function(func) + + if s['type'] == 'str': + if func is str.strip: + s = s.copy() + s['strip_whitespace'] = True + return s + elif func is str.lower: + s = s.copy() + s['to_lower'] = True + return s + elif func is str.upper: + s = s.copy() + s['to_upper'] = True + return s + + return cs.no_info_after_validator_function(func, s) + + +def _apply_constraint( # noqa: C901 + s: cs.CoreSchema | None, constraint: _ConstraintAnnotation +) -> cs.CoreSchema: + """Apply a single constraint to a schema.""" + if isinstance(constraint, annotated_types.Gt): + gt = constraint.gt + if s and s['type'] in {'int', 'float', 'decimal'}: + s = s.copy() + if s['type'] == 'int' and isinstance(gt, int): + s['gt'] = gt + elif s['type'] == 'float' and isinstance(gt, float): + s['gt'] = gt + elif s['type'] == 'decimal' and isinstance(gt, Decimal): + s['gt'] = gt + else: + + def check_gt(v: Any) -> bool: + return v > gt + + s = _check_func(check_gt, f'> {gt}', s) + elif isinstance(constraint, annotated_types.Ge): + ge = constraint.ge + if s and s['type'] in {'int', 'float', 'decimal'}: + s = s.copy() + if s['type'] == 'int' and isinstance(ge, int): + s['ge'] = ge + elif s['type'] == 'float' and isinstance(ge, float): + s['ge'] = ge + elif s['type'] == 'decimal' and isinstance(ge, Decimal): + s['ge'] = ge + + def check_ge(v: Any) -> bool: + return v >= ge + + s = _check_func(check_ge, f'>= {ge}', s) + elif isinstance(constraint, annotated_types.Lt): + lt = constraint.lt + if s and s['type'] in {'int', 'float', 'decimal'}: + s = s.copy() + if s['type'] == 'int' and isinstance(lt, int): + s['lt'] = lt + elif s['type'] == 'float' and isinstance(lt, float): + s['lt'] = lt + elif s['type'] == 'decimal' and isinstance(lt, Decimal): + s['lt'] = lt + + def check_lt(v: Any) -> bool: + return v < lt + + s = _check_func(check_lt, f'< {lt}', s) + elif isinstance(constraint, annotated_types.Le): + le = constraint.le + if s and s['type'] in {'int', 'float', 'decimal'}: + s = s.copy() + if s['type'] == 'int' and isinstance(le, int): + s['le'] = le + elif s['type'] == 'float' and isinstance(le, float): + s['le'] = le + elif s['type'] == 'decimal' and isinstance(le, Decimal): + s['le'] = le + + def check_le(v: Any) -> bool: + return v <= le + + s = _check_func(check_le, f'<= {le}', s) + elif isinstance(constraint, annotated_types.Len): + min_len = constraint.min_length + max_len = constraint.max_length + + if s and s['type'] in {'str', 'list', 'tuple', 'set', 'frozenset', 'dict'}: + assert ( + s['type'] == 'str' + or s['type'] == 'list' + or s['type'] == 'tuple' + or s['type'] == 'set' + or s['type'] == 'dict' + or s['type'] == 'frozenset' + ) + s = s.copy() + if min_len != 0: + s['min_length'] = min_len + if max_len is not None: + s['max_length'] = max_len + + def check_len(v: Any) -> bool: + if max_len is not None: + return (min_len <= len(v)) and (len(v) <= max_len) + return min_len <= len(v) + + s = _check_func(check_len, f'length >= {min_len} and length <= {max_len}', s) + elif isinstance(constraint, annotated_types.MultipleOf): + multiple_of = constraint.multiple_of + if s and s['type'] in {'int', 'float', 'decimal'}: + s = s.copy() + if s['type'] == 'int' and isinstance(multiple_of, int): + s['multiple_of'] = multiple_of + elif s['type'] == 'float' and isinstance(multiple_of, float): + s['multiple_of'] = multiple_of + elif s['type'] == 'decimal' and isinstance(multiple_of, Decimal): + s['multiple_of'] = multiple_of + + def check_multiple_of(v: Any) -> bool: + return v % multiple_of == 0 + + s = _check_func(check_multiple_of, f'% {multiple_of} == 0', s) + elif isinstance(constraint, annotated_types.Timezone): + tz = constraint.tz + + if tz is ...: + if s and s['type'] == 'datetime': + s = s.copy() + s['tz_constraint'] = 'aware' + else: + + def check_tz_aware(v: object) -> bool: + assert isinstance(v, datetime.datetime) + return v.tzinfo is not None + + s = _check_func(check_tz_aware, 'timezone aware', s) + elif tz is None: + if s and s['type'] == 'datetime': + s = s.copy() + s['tz_constraint'] = 'naive' + else: + + def check_tz_naive(v: object) -> bool: + assert isinstance(v, datetime.datetime) + return v.tzinfo is None + + s = _check_func(check_tz_naive, 'timezone naive', s) + else: + raise NotImplementedError('Constraining to a specific timezone is not yet supported') + elif isinstance(constraint, annotated_types.Interval): + if constraint.ge: + s = _apply_constraint(s, annotated_types.Ge(constraint.ge)) + if constraint.gt: + s = _apply_constraint(s, annotated_types.Gt(constraint.gt)) + if constraint.le: + s = _apply_constraint(s, annotated_types.Le(constraint.le)) + if constraint.lt: + s = _apply_constraint(s, annotated_types.Lt(constraint.lt)) + assert s is not None + elif isinstance(constraint, annotated_types.Predicate): + func = constraint.func + + if func.__name__ == '': + # attempt to extract the source code for a lambda function + # to use as the function name in error messages + # TODO: is there a better way? should we just not do this? + import inspect + + try: + # remove ')' suffix, can use removesuffix once we drop 3.8 + source = inspect.getsource(func).strip() + if source.endswith(')'): + source = source[:-1] + lambda_source_code = '`' + ''.join(''.join(source.split('lambda ')[1:]).split(':')[1:]).strip() + '`' + except OSError: + # stringified annotations + lambda_source_code = 'lambda' + + s = _check_func(func, lambda_source_code, s) + else: + s = _check_func(func, func.__name__, s) + elif isinstance(constraint, _NotEq): + value = constraint.value + + def check_not_eq(v: Any) -> bool: + return operator.__ne__(v, value) + + s = _check_func(check_not_eq, f'!= {value}', s) + elif isinstance(constraint, _Eq): + value = constraint.value + + def check_eq(v: Any) -> bool: + return operator.__eq__(v, value) + + s = _check_func(check_eq, f'== {value}', s) + elif isinstance(constraint, _In): + values = constraint.values + + def check_in(v: Any) -> bool: + return operator.__contains__(values, v) + + s = _check_func(check_in, f'in {values}', s) + elif isinstance(constraint, _NotIn): + values = constraint.values + + def check_not_in(v: Any) -> bool: + return operator.__not__(operator.__contains__(values, v)) + + s = _check_func(check_not_in, f'not in {values}', s) + else: + assert isinstance(constraint, Pattern) + if s and s['type'] == 'str': + s = s.copy() + s['pattern'] = constraint.pattern + else: + + def check_pattern(v: object) -> bool: + assert isinstance(v, str) + return constraint.match(v) is not None + + s = _check_func(check_pattern, f'~ {constraint.pattern}', s) + return s + + +class _SupportsRange(annotated_types.SupportsLe, annotated_types.SupportsGe, Protocol): + pass + + +class _SupportsLen(Protocol): + def __len__(self) -> int: ... + + +_NewOutGt = TypeVar('_NewOutGt', bound=annotated_types.SupportsGt) +_NewOutGe = TypeVar('_NewOutGe', bound=annotated_types.SupportsGe) +_NewOutLt = TypeVar('_NewOutLt', bound=annotated_types.SupportsLt) +_NewOutLe = TypeVar('_NewOutLe', bound=annotated_types.SupportsLe) +_NewOutLen = TypeVar('_NewOutLen', bound=_SupportsLen) +_NewOutDiv = TypeVar('_NewOutDiv', bound=annotated_types.SupportsDiv) +_NewOutMod = TypeVar('_NewOutMod', bound=annotated_types.SupportsMod) +_NewOutDatetime = TypeVar('_NewOutDatetime', bound=datetime.datetime) +_NewOutInterval = TypeVar('_NewOutInterval', bound=_SupportsRange) +_OtherIn = TypeVar('_OtherIn') +_OtherOut = TypeVar('_OtherOut') diff --git a/env/Lib/site-packages/pydantic/fields.py b/env/Lib/site-packages/pydantic/fields.py new file mode 100644 index 0000000..7b41a4d --- /dev/null +++ b/env/Lib/site-packages/pydantic/fields.py @@ -0,0 +1,1255 @@ +"""Defining fields on models.""" + +from __future__ import annotations as _annotations + +import dataclasses +import inspect +import sys +import typing +from copy import copy +from dataclasses import Field as DataclassField +from functools import cached_property +from typing import Any, ClassVar +from warnings import warn + +import annotated_types +import typing_extensions +from pydantic_core import PydanticUndefined +from typing_extensions import Literal, TypeAlias, Unpack, deprecated + +from . import types +from ._internal import _decorators, _fields, _generics, _internal_dataclass, _repr, _typing_extra, _utils +from .aliases import AliasChoices, AliasPath +from .config import JsonDict +from .errors import PydanticUserError +from .warnings import PydanticDeprecatedSince20 + +if typing.TYPE_CHECKING: + from ._internal._repr import ReprArgs +else: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + +__all__ = 'Field', 'PrivateAttr', 'computed_field' + + +_Unset: Any = PydanticUndefined + +if sys.version_info >= (3, 13): + import warnings + + Deprecated: TypeAlias = warnings.deprecated | deprecated +else: + Deprecated: TypeAlias = deprecated + + +class _FromFieldInfoInputs(typing_extensions.TypedDict, total=False): + """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.from_field`.""" + + annotation: type[Any] | None + default_factory: typing.Callable[[], Any] | None + alias: str | None + alias_priority: int | None + validation_alias: str | AliasPath | AliasChoices | None + serialization_alias: str | None + title: str | None + field_title_generator: typing_extensions.Callable[[str, FieldInfo], str] | None + description: str | None + examples: list[Any] | None + exclude: bool | None + gt: annotated_types.SupportsGt | None + ge: annotated_types.SupportsGe | None + lt: annotated_types.SupportsLt | None + le: annotated_types.SupportsLe | None + multiple_of: float | None + strict: bool | None + min_length: int | None + max_length: int | None + pattern: str | typing.Pattern[str] | None + allow_inf_nan: bool | None + max_digits: int | None + decimal_places: int | None + union_mode: Literal['smart', 'left_to_right'] | None + discriminator: str | types.Discriminator | None + deprecated: Deprecated | str | bool | None + json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None + frozen: bool | None + validate_default: bool | None + repr: bool + init: bool | None + init_var: bool | None + kw_only: bool | None + coerce_numbers_to_str: bool | None + fail_fast: bool | None + + +class _FieldInfoInputs(_FromFieldInfoInputs, total=False): + """This class exists solely to add type checking for the `**kwargs` in `FieldInfo.__init__`.""" + + default: Any + + +class FieldInfo(_repr.Representation): + """This class holds information about a field. + + `FieldInfo` is used for any field definition regardless of whether the [`Field()`][pydantic.fields.Field] + function is explicitly used. + + !!! warning + You generally shouldn't be creating `FieldInfo` directly, you'll only need to use it when accessing + [`BaseModel`][pydantic.main.BaseModel] `.model_fields` internals. + + Attributes: + annotation: The type annotation of the field. + default: The default value of the field. + default_factory: The factory function used to construct the default for the field. + alias: The alias name of the field. + alias_priority: The priority of the field's alias. + validation_alias: The validation alias of the field. + serialization_alias: The serialization alias of the field. + title: The title of the field. + field_title_generator: A callable that takes a field name and returns title for it. + description: The description of the field. + examples: List of examples of the field. + exclude: Whether to exclude the field from the model serialization. + discriminator: Field name or Discriminator for discriminating the type in a tagged union. + deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, + or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. + json_schema_extra: A dict or callable to provide extra JSON schema properties. + frozen: Whether the field is frozen. + validate_default: Whether to validate the default value of the field. + repr: Whether to include the field in representation of the model. + init: Whether the field should be included in the constructor of the dataclass. + init_var: Whether the field should _only_ be included in the constructor of the dataclass, and not stored. + kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass. + metadata: List of metadata constraints. + """ + + annotation: type[Any] | None + default: Any + default_factory: typing.Callable[[], Any] | None + alias: str | None + alias_priority: int | None + validation_alias: str | AliasPath | AliasChoices | None + serialization_alias: str | None + title: str | None + field_title_generator: typing.Callable[[str, FieldInfo], str] | None + description: str | None + examples: list[Any] | None + exclude: bool | None + discriminator: str | types.Discriminator | None + deprecated: Deprecated | str | bool | None + json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None + frozen: bool | None + validate_default: bool | None + repr: bool + init: bool | None + init_var: bool | None + kw_only: bool | None + metadata: list[Any] + + __slots__ = ( + 'annotation', + 'default', + 'default_factory', + 'alias', + 'alias_priority', + 'validation_alias', + 'serialization_alias', + 'title', + 'field_title_generator', + 'description', + 'examples', + 'exclude', + 'discriminator', + 'deprecated', + 'json_schema_extra', + 'frozen', + 'validate_default', + 'repr', + 'init', + 'init_var', + 'kw_only', + 'metadata', + '_attributes_set', + ) + + # used to convert kwargs to metadata/constraints, + # None has a special meaning - these items are collected into a `PydanticGeneralMetadata` + metadata_lookup: ClassVar[dict[str, typing.Callable[[Any], Any] | None]] = { + 'strict': types.Strict, + 'gt': annotated_types.Gt, + 'ge': annotated_types.Ge, + 'lt': annotated_types.Lt, + 'le': annotated_types.Le, + 'multiple_of': annotated_types.MultipleOf, + 'min_length': annotated_types.MinLen, + 'max_length': annotated_types.MaxLen, + 'pattern': None, + 'allow_inf_nan': None, + 'max_digits': None, + 'decimal_places': None, + 'union_mode': None, + 'coerce_numbers_to_str': None, + 'fail_fast': types.FailFast, + } + + def __init__(self, **kwargs: Unpack[_FieldInfoInputs]) -> None: + """This class should generally not be initialized directly; instead, use the `pydantic.fields.Field` function + or one of the constructor classmethods. + + See the signature of `pydantic.fields.Field` for more details about the expected arguments. + """ + self._attributes_set = {k: v for k, v in kwargs.items() if v is not _Unset} + kwargs = {k: _DefaultValues.get(k) if v is _Unset else v for k, v in kwargs.items()} # type: ignore + self.annotation, annotation_metadata = self._extract_metadata(kwargs.get('annotation')) + + default = kwargs.pop('default', PydanticUndefined) + if default is Ellipsis: + self.default = PydanticUndefined + else: + self.default = default + + self.default_factory = kwargs.pop('default_factory', None) + + if self.default is not PydanticUndefined and self.default_factory is not None: + raise TypeError('cannot specify both default and default_factory') + + self.alias = kwargs.pop('alias', None) + self.validation_alias = kwargs.pop('validation_alias', None) + self.serialization_alias = kwargs.pop('serialization_alias', None) + alias_is_set = any(alias is not None for alias in (self.alias, self.validation_alias, self.serialization_alias)) + self.alias_priority = kwargs.pop('alias_priority', None) or 2 if alias_is_set else None + self.title = kwargs.pop('title', None) + self.field_title_generator = kwargs.pop('field_title_generator', None) + self.description = kwargs.pop('description', None) + self.examples = kwargs.pop('examples', None) + self.exclude = kwargs.pop('exclude', None) + self.discriminator = kwargs.pop('discriminator', None) + # For compatibility with FastAPI<=0.110.0, we preserve the existing value if it is not overridden + self.deprecated = kwargs.pop('deprecated', getattr(self, 'deprecated', None)) + self.repr = kwargs.pop('repr', True) + self.json_schema_extra = kwargs.pop('json_schema_extra', None) + self.validate_default = kwargs.pop('validate_default', None) + self.frozen = kwargs.pop('frozen', None) + # currently only used on dataclasses + self.init = kwargs.pop('init', None) + self.init_var = kwargs.pop('init_var', None) + self.kw_only = kwargs.pop('kw_only', None) + + self.metadata = self._collect_metadata(kwargs) + annotation_metadata # type: ignore + + @staticmethod + def from_field(default: Any = PydanticUndefined, **kwargs: Unpack[_FromFieldInfoInputs]) -> FieldInfo: + """Create a new `FieldInfo` object with the `Field` function. + + Args: + default: The default value for the field. Defaults to Undefined. + **kwargs: Additional arguments dictionary. + + Raises: + TypeError: If 'annotation' is passed as a keyword argument. + + Returns: + A new FieldInfo object with the given parameters. + + Example: + This is how you can create a field with default value like this: + + ```python + import pydantic + + class MyModel(pydantic.BaseModel): + foo: int = pydantic.Field(4) + ``` + """ + if 'annotation' in kwargs: + raise TypeError('"annotation" is not permitted as a Field keyword argument') + return FieldInfo(default=default, **kwargs) + + @staticmethod + def from_annotation(annotation: type[Any]) -> FieldInfo: + """Creates a `FieldInfo` instance from a bare annotation. + + This function is used internally to create a `FieldInfo` from a bare annotation like this: + + ```python + import pydantic + + class MyModel(pydantic.BaseModel): + foo: int # <-- like this + ``` + + We also account for the case where the annotation can be an instance of `Annotated` and where + one of the (not first) arguments in `Annotated` is an instance of `FieldInfo`, e.g.: + + ```python + import annotated_types + from typing_extensions import Annotated + + import pydantic + + class MyModel(pydantic.BaseModel): + foo: Annotated[int, annotated_types.Gt(42)] + bar: Annotated[int, pydantic.Field(gt=42)] + ``` + + Args: + annotation: An annotation object. + + Returns: + An instance of the field metadata. + """ + final = False + if _typing_extra.is_finalvar(annotation): + final = True + if annotation is not typing_extensions.Final: + annotation = typing_extensions.get_args(annotation)[0] + + if _typing_extra.is_annotated(annotation): + first_arg, *extra_args = typing_extensions.get_args(annotation) + if _typing_extra.is_finalvar(first_arg): + final = True + field_info_annotations = [a for a in extra_args if isinstance(a, FieldInfo)] + field_info = FieldInfo.merge_field_infos(*field_info_annotations, annotation=first_arg) + if field_info: + new_field_info = copy(field_info) + new_field_info.annotation = first_arg + new_field_info.frozen = final or field_info.frozen + metadata: list[Any] = [] + for a in extra_args: + if _typing_extra.is_deprecated_instance(a): + new_field_info.deprecated = a.message + elif not isinstance(a, FieldInfo): + metadata.append(a) + else: + metadata.extend(a.metadata) + new_field_info.metadata = metadata + return new_field_info + + return FieldInfo(annotation=annotation, frozen=final or None) # pyright: ignore[reportArgumentType] + + @staticmethod + def from_annotated_attribute(annotation: type[Any], default: Any) -> FieldInfo: + """Create `FieldInfo` from an annotation with a default value. + + This is used in cases like the following: + + ```python + import annotated_types + from typing_extensions import Annotated + + import pydantic + + class MyModel(pydantic.BaseModel): + foo: int = 4 # <-- like this + bar: Annotated[int, annotated_types.Gt(4)] = 4 # <-- or this + spam: Annotated[int, pydantic.Field(gt=4)] = 4 # <-- or this + ``` + + Args: + annotation: The type annotation of the field. + default: The default value of the field. + + Returns: + A field object with the passed values. + """ + if annotation is default: + raise PydanticUserError( + 'Error when building FieldInfo from annotated attribute. ' + "Make sure you don't have any field name clashing with a type annotation ", + code='unevaluable-type-annotation', + ) + + final = False + if _typing_extra.is_finalvar(annotation): + final = True + if annotation is not typing_extensions.Final: + annotation = typing_extensions.get_args(annotation)[0] + + if isinstance(default, FieldInfo): + default.annotation, annotation_metadata = FieldInfo._extract_metadata(annotation) # pyright: ignore[reportArgumentType] + default.metadata += annotation_metadata + default = default.merge_field_infos( + *[x for x in annotation_metadata if isinstance(x, FieldInfo)], default, annotation=default.annotation + ) + default.frozen = final or default.frozen + return default + elif isinstance(default, dataclasses.Field): + init_var = False + if annotation is dataclasses.InitVar: + init_var = True + annotation = typing.cast(Any, Any) + elif isinstance(annotation, dataclasses.InitVar): + init_var = True + annotation = annotation.type + pydantic_field = FieldInfo._from_dataclass_field(default) + pydantic_field.annotation, annotation_metadata = FieldInfo._extract_metadata(annotation) # pyright: ignore[reportArgumentType] + pydantic_field.metadata += annotation_metadata + pydantic_field = pydantic_field.merge_field_infos( + *[x for x in annotation_metadata if isinstance(x, FieldInfo)], + pydantic_field, + annotation=pydantic_field.annotation, + ) + pydantic_field.frozen = final or pydantic_field.frozen + pydantic_field.init_var = init_var + pydantic_field.init = getattr(default, 'init', None) + pydantic_field.kw_only = getattr(default, 'kw_only', None) + return pydantic_field + else: + if _typing_extra.is_annotated(annotation): + first_arg, *extra_args = typing_extensions.get_args(annotation) + field_infos = [a for a in extra_args if isinstance(a, FieldInfo)] + field_info = FieldInfo.merge_field_infos(*field_infos, annotation=first_arg, default=default) + metadata: list[Any] = [] + for a in extra_args: + if _typing_extra.is_deprecated_instance(a): + field_info.deprecated = a.message + elif not isinstance(a, FieldInfo): + metadata.append(a) + else: + metadata.extend(a.metadata) + field_info.metadata = metadata + return field_info + + return FieldInfo(annotation=annotation, default=default, frozen=final or None) # pyright: ignore[reportArgumentType] + + @staticmethod + def merge_field_infos(*field_infos: FieldInfo, **overrides: Any) -> FieldInfo: + """Merge `FieldInfo` instances keeping only explicitly set attributes. + + Later `FieldInfo` instances override earlier ones. + + Returns: + FieldInfo: A merged FieldInfo instance. + """ + flattened_field_infos: list[FieldInfo] = [] + for field_info in field_infos: + flattened_field_infos.extend(x for x in field_info.metadata if isinstance(x, FieldInfo)) + flattened_field_infos.append(field_info) + field_infos = tuple(flattened_field_infos) + if len(field_infos) == 1: + # No merging necessary, but we still need to make a copy and apply the overrides + field_info = copy(field_infos[0]) + field_info._attributes_set.update(overrides) + + default_override = overrides.pop('default', PydanticUndefined) + if default_override is Ellipsis: + default_override = PydanticUndefined + if default_override is not PydanticUndefined: + field_info.default = default_override + + for k, v in overrides.items(): + setattr(field_info, k, v) + return field_info # type: ignore + + new_kwargs: dict[str, Any] = {} + metadata = {} + for field_info in field_infos: + new_kwargs.update(field_info._attributes_set) + for x in field_info.metadata: + if not isinstance(x, FieldInfo): + metadata[type(x)] = x + new_kwargs.update(overrides) + field_info = FieldInfo(**new_kwargs) + field_info.metadata = list(metadata.values()) + return field_info + + @staticmethod + def _from_dataclass_field(dc_field: DataclassField[Any]) -> FieldInfo: + """Return a new `FieldInfo` instance from a `dataclasses.Field` instance. + + Args: + dc_field: The `dataclasses.Field` instance to convert. + + Returns: + The corresponding `FieldInfo` instance. + + Raises: + TypeError: If any of the `FieldInfo` kwargs does not match the `dataclass.Field` kwargs. + """ + default = dc_field.default + if default is dataclasses.MISSING: + default = PydanticUndefined + + if dc_field.default_factory is dataclasses.MISSING: + default_factory: typing.Callable[[], Any] | None = None + else: + default_factory = dc_field.default_factory + + # use the `Field` function so in correct kwargs raise the correct `TypeError` + dc_field_metadata = {k: v for k, v in dc_field.metadata.items() if k in _FIELD_ARG_NAMES} + return Field(default=default, default_factory=default_factory, repr=dc_field.repr, **dc_field_metadata) + + @staticmethod + def _extract_metadata(annotation: type[Any] | None) -> tuple[type[Any] | None, list[Any]]: + """Tries to extract metadata/constraints from an annotation if it uses `Annotated`. + + Args: + annotation: The type hint annotation for which metadata has to be extracted. + + Returns: + A tuple containing the extracted metadata type and the list of extra arguments. + """ + if annotation is not None: + if _typing_extra.is_annotated(annotation): + first_arg, *extra_args = typing_extensions.get_args(annotation) + return first_arg, list(extra_args) + + return annotation, [] + + @staticmethod + def _collect_metadata(kwargs: dict[str, Any]) -> list[Any]: + """Collect annotations from kwargs. + + Args: + kwargs: Keyword arguments passed to the function. + + Returns: + A list of metadata objects - a combination of `annotated_types.BaseMetadata` and + `PydanticMetadata`. + """ + metadata: list[Any] = [] + general_metadata = {} + for key, value in list(kwargs.items()): + try: + marker = FieldInfo.metadata_lookup[key] + except KeyError: + continue + + del kwargs[key] + if value is not None: + if marker is None: + general_metadata[key] = value + else: + metadata.append(marker(value)) + if general_metadata: + metadata.append(_fields.pydantic_general_metadata(**general_metadata)) + return metadata + + @property + def deprecation_message(self) -> str | None: + """The deprecation message to be emitted, or `None` if not set.""" + if self.deprecated is None: + return None + if isinstance(self.deprecated, bool): + return 'deprecated' if self.deprecated else None + return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message + + def get_default(self, *, call_default_factory: bool = False) -> Any: + """Get the default value. + + We expose an option for whether to call the default_factory (if present), as calling it may + result in side effects that we want to avoid. However, there are times when it really should + be called (namely, when instantiating a model via `model_construct`). + + Args: + call_default_factory: Whether to call the default_factory or not. Defaults to `False`. + + Returns: + The default value, calling the default factory if requested or `None` if not set. + """ + if self.default_factory is None: + return _utils.smart_deepcopy(self.default) + elif call_default_factory: + return self.default_factory() + else: + return None + + def is_required(self) -> bool: + """Check if the field is required (i.e., does not have a default value or factory). + + Returns: + `True` if the field is required, `False` otherwise. + """ + return self.default is PydanticUndefined and self.default_factory is None + + def rebuild_annotation(self) -> Any: + """Attempts to rebuild the original annotation for use in function signatures. + + If metadata is present, it adds it to the original annotation using + `Annotated`. Otherwise, it returns the original annotation as-is. + + Note that because the metadata has been flattened, the original annotation + may not be reconstructed exactly as originally provided, e.g. if the original + type had unrecognized annotations, or was annotated with a call to `pydantic.Field`. + + Returns: + The rebuilt annotation. + """ + if not self.metadata: + return self.annotation + else: + # Annotated arguments must be a tuple + return typing_extensions.Annotated[(self.annotation, *self.metadata)] # type: ignore + + def apply_typevars_map(self, typevars_map: dict[Any, Any] | None, types_namespace: dict[str, Any] | None) -> None: + """Apply a `typevars_map` to the annotation. + + This method is used when analyzing parametrized generic types to replace typevars with their concrete types. + + This method applies the `typevars_map` to the annotation in place. + + Args: + typevars_map: A dictionary mapping type variables to their concrete types. + types_namespace (dict | None): A dictionary containing related types to the annotated type. + + See Also: + pydantic._internal._generics.replace_types is used for replacing the typevars with + their concrete types. + """ + annotation = _typing_extra.eval_type_lenient(self.annotation, types_namespace) + self.annotation = _generics.replace_types(annotation, typevars_map) + + def __repr_args__(self) -> ReprArgs: + yield 'annotation', _repr.PlainRepr(_repr.display_as_type(self.annotation)) + yield 'required', self.is_required() + + for s in self.__slots__: + if s == '_attributes_set': + continue + if s == 'annotation': + continue + elif s == 'metadata' and not self.metadata: + continue + elif s == 'repr' and self.repr is True: + continue + if s == 'frozen' and self.frozen is False: + continue + if s == 'validation_alias' and self.validation_alias == self.alias: + continue + if s == 'serialization_alias' and self.serialization_alias == self.alias: + continue + if s == 'default' and self.default is not PydanticUndefined: + yield 'default', self.default + elif s == 'default_factory' and self.default_factory is not None: + yield 'default_factory', _repr.PlainRepr(_repr.display_as_type(self.default_factory)) + else: + value = getattr(self, s) + if value is not None and value is not PydanticUndefined: + yield s, value + + +class _EmptyKwargs(typing_extensions.TypedDict): + """This class exists solely to ensure that type checking warns about passing `**extra` in `Field`.""" + + +_DefaultValues = dict( + default=..., + default_factory=None, + alias=None, + alias_priority=None, + validation_alias=None, + serialization_alias=None, + title=None, + description=None, + examples=None, + exclude=None, + discriminator=None, + json_schema_extra=None, + frozen=None, + validate_default=None, + repr=True, + init=None, + init_var=None, + kw_only=None, + pattern=None, + strict=None, + gt=None, + ge=None, + lt=None, + le=None, + multiple_of=None, + allow_inf_nan=None, + max_digits=None, + decimal_places=None, + min_length=None, + max_length=None, + coerce_numbers_to_str=None, +) + + +def Field( # noqa: C901 + default: Any = PydanticUndefined, + *, + default_factory: typing.Callable[[], Any] | None = _Unset, + alias: str | None = _Unset, + alias_priority: int | None = _Unset, + validation_alias: str | AliasPath | AliasChoices | None = _Unset, + serialization_alias: str | None = _Unset, + title: str | None = _Unset, + field_title_generator: typing_extensions.Callable[[str, FieldInfo], str] | None = _Unset, + description: str | None = _Unset, + examples: list[Any] | None = _Unset, + exclude: bool | None = _Unset, + discriminator: str | types.Discriminator | None = _Unset, + deprecated: Deprecated | str | bool | None = _Unset, + json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = _Unset, + frozen: bool | None = _Unset, + validate_default: bool | None = _Unset, + repr: bool = _Unset, + init: bool | None = _Unset, + init_var: bool | None = _Unset, + kw_only: bool | None = _Unset, + pattern: str | typing.Pattern[str] | None = _Unset, + strict: bool | None = _Unset, + coerce_numbers_to_str: bool | None = _Unset, + gt: annotated_types.SupportsGt | None = _Unset, + ge: annotated_types.SupportsGe | None = _Unset, + lt: annotated_types.SupportsLt | None = _Unset, + le: annotated_types.SupportsLe | None = _Unset, + multiple_of: float | None = _Unset, + allow_inf_nan: bool | None = _Unset, + max_digits: int | None = _Unset, + decimal_places: int | None = _Unset, + min_length: int | None = _Unset, + max_length: int | None = _Unset, + union_mode: Literal['smart', 'left_to_right'] = _Unset, + fail_fast: bool | None = _Unset, + **extra: Unpack[_EmptyKwargs], +) -> Any: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/fields + + Create a field for objects that can be configured. + + Used to provide extra information about a field, either for the model schema or complex validation. Some arguments + apply only to number fields (`int`, `float`, `Decimal`) and some apply only to `str`. + + Note: + - Any `_Unset` objects will be replaced by the corresponding value defined in the `_DefaultValues` dictionary. If a key for the `_Unset` object is not found in the `_DefaultValues` dictionary, it will default to `None` + + Args: + default: Default value if the field is not set. + default_factory: A callable to generate the default value, such as :func:`~datetime.utcnow`. + alias: The name to use for the attribute when validating or serializing by alias. + This is often used for things like converting between snake and camel case. + alias_priority: Priority of the alias. This affects whether an alias generator is used. + validation_alias: Like `alias`, but only affects validation, not serialization. + serialization_alias: Like `alias`, but only affects serialization, not validation. + title: Human-readable title. + field_title_generator: A callable that takes a field name and returns title for it. + description: Human-readable description. + examples: Example values for this field. + exclude: Whether to exclude the field from the model serialization. + discriminator: Field name or Discriminator for discriminating the type in a tagged union. + deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, + or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. + json_schema_extra: A dict or callable to provide extra JSON schema properties. + frozen: Whether the field is frozen. If true, attempts to change the value on an instance will raise an error. + validate_default: If `True`, apply validation to the default value every time you create an instance. + Otherwise, for performance reasons, the default value of the field is trusted and not validated. + repr: A boolean indicating whether to include the field in the `__repr__` output. + init: Whether the field should be included in the constructor of the dataclass. + (Only applies to dataclasses.) + init_var: Whether the field should _only_ be included in the constructor of the dataclass. + (Only applies to dataclasses.) + kw_only: Whether the field should be a keyword-only argument in the constructor of the dataclass. + (Only applies to dataclasses.) + coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). + strict: If `True`, strict validation is applied to the field. + See [Strict Mode](../concepts/strict_mode.md) for details. + gt: Greater than. If set, value must be greater than this. Only applicable to numbers. + ge: Greater than or equal. If set, value must be greater than or equal to this. Only applicable to numbers. + lt: Less than. If set, value must be less than this. Only applicable to numbers. + le: Less than or equal. If set, value must be less than or equal to this. Only applicable to numbers. + multiple_of: Value must be a multiple of this. Only applicable to numbers. + min_length: Minimum length for iterables. + max_length: Maximum length for iterables. + pattern: Pattern for strings (a regular expression). + allow_inf_nan: Allow `inf`, `-inf`, `nan`. Only applicable to numbers. + max_digits: Maximum number of allow digits for strings. + decimal_places: Maximum number of decimal places allowed for numbers. + union_mode: The strategy to apply when validating a union. Can be `smart` (the default), or `left_to_right`. + See [Union Mode](../concepts/unions.md#union-modes) for details. + fail_fast: If `True`, validation will stop on the first error. If `False`, all validation errors will be collected. + This option can be applied only to iterable types (list, tuple, set, and frozenset). + extra: (Deprecated) Extra fields that will be included in the JSON schema. + + !!! warning Deprecated + The `extra` kwargs is deprecated. Use `json_schema_extra` instead. + + Returns: + A new [`FieldInfo`][pydantic.fields.FieldInfo]. The return annotation is `Any` so `Field` can be used on + type-annotated fields without causing a type error. + """ + # Check deprecated and removed params from V1. This logic should eventually be removed. + const = extra.pop('const', None) # type: ignore + if const is not None: + raise PydanticUserError('`const` is removed, use `Literal` instead', code='removed-kwargs') + + min_items = extra.pop('min_items', None) # type: ignore + if min_items is not None: + warn('`min_items` is deprecated and will be removed, use `min_length` instead', DeprecationWarning) + if min_length in (None, _Unset): + min_length = min_items # type: ignore + + max_items = extra.pop('max_items', None) # type: ignore + if max_items is not None: + warn('`max_items` is deprecated and will be removed, use `max_length` instead', DeprecationWarning) + if max_length in (None, _Unset): + max_length = max_items # type: ignore + + unique_items = extra.pop('unique_items', None) # type: ignore + if unique_items is not None: + raise PydanticUserError( + ( + '`unique_items` is removed, use `Set` instead' + '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)' + ), + code='removed-kwargs', + ) + + allow_mutation = extra.pop('allow_mutation', None) # type: ignore + if allow_mutation is not None: + warn('`allow_mutation` is deprecated and will be removed. use `frozen` instead', DeprecationWarning) + if allow_mutation is False: + frozen = True + + regex = extra.pop('regex', None) # type: ignore + if regex is not None: + raise PydanticUserError('`regex` is removed. use `pattern` instead', code='removed-kwargs') + + if extra: + warn( + 'Using extra keyword arguments on `Field` is deprecated and will be removed.' + ' Use `json_schema_extra` instead.' + f' (Extra keys: {", ".join(k.__repr__() for k in extra.keys())})', + DeprecationWarning, + ) + if not json_schema_extra or json_schema_extra is _Unset: + json_schema_extra = extra # type: ignore + + if ( + validation_alias + and validation_alias is not _Unset + and not isinstance(validation_alias, (str, AliasChoices, AliasPath)) + ): + raise TypeError('Invalid `validation_alias` type. it should be `str`, `AliasChoices`, or `AliasPath`') + + if serialization_alias in (_Unset, None) and isinstance(alias, str): + serialization_alias = alias + + if validation_alias in (_Unset, None): + validation_alias = alias + + include = extra.pop('include', None) # type: ignore + if include is not None: + warn('`include` is deprecated and does nothing. It will be removed, use `exclude` instead', DeprecationWarning) + + return FieldInfo.from_field( + default, + default_factory=default_factory, + alias=alias, + alias_priority=alias_priority, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + title=title, + field_title_generator=field_title_generator, + description=description, + examples=examples, + exclude=exclude, + discriminator=discriminator, + deprecated=deprecated, + json_schema_extra=json_schema_extra, + frozen=frozen, + pattern=pattern, + validate_default=validate_default, + repr=repr, + init=init, + init_var=init_var, + kw_only=kw_only, + coerce_numbers_to_str=coerce_numbers_to_str, + strict=strict, + gt=gt, + ge=ge, + lt=lt, + le=le, + multiple_of=multiple_of, + min_length=min_length, + max_length=max_length, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + union_mode=union_mode, + fail_fast=fail_fast, + ) + + +_FIELD_ARG_NAMES = set(inspect.signature(Field).parameters) +_FIELD_ARG_NAMES.remove('extra') # do not include the varkwargs parameter + + +class ModelPrivateAttr(_repr.Representation): + """A descriptor for private attributes in class models. + + !!! warning + You generally shouldn't be creating `ModelPrivateAttr` instances directly, instead use + `pydantic.fields.PrivateAttr`. (This is similar to `FieldInfo` vs. `Field`.) + + Attributes: + default: The default value of the attribute if not provided. + default_factory: A callable function that generates the default value of the + attribute if not provided. + """ + + __slots__ = 'default', 'default_factory' + + def __init__( + self, default: Any = PydanticUndefined, *, default_factory: typing.Callable[[], Any] | None = None + ) -> None: + self.default = default + self.default_factory = default_factory + + if not typing.TYPE_CHECKING: + # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access + + def __getattr__(self, item: str) -> Any: + """This function improves compatibility with custom descriptors by ensuring delegation happens + as expected when the default value of a private attribute is a descriptor. + """ + if item in {'__get__', '__set__', '__delete__'}: + if hasattr(self.default, item): + return getattr(self.default, item) + raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') + + def __set_name__(self, cls: type[Any], name: str) -> None: + """Preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487.""" + if self.default is PydanticUndefined: + return + if not hasattr(self.default, '__set_name__'): + return + set_name = self.default.__set_name__ + if callable(set_name): + set_name(cls, name) + + def get_default(self) -> Any: + """Retrieve the default value of the object. + + If `self.default_factory` is `None`, the method will return a deep copy of the `self.default` object. + + If `self.default_factory` is not `None`, it will call `self.default_factory` and return the value returned. + + Returns: + The default value of the object. + """ + return _utils.smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() + + def __eq__(self, other: Any) -> bool: + return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( + other.default, + other.default_factory, + ) + + +def PrivateAttr( + default: Any = PydanticUndefined, + *, + default_factory: typing.Callable[[], Any] | None = None, + init: Literal[False] = False, +) -> Any: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/models/#private-model-attributes + + Indicates that an attribute is intended for private use and not handled during normal validation/serialization. + + Private attributes are not validated by Pydantic, so it's up to you to ensure they are used in a type-safe manner. + + Private attributes are stored in `__private_attributes__` on the model. + + Args: + default: The attribute's default value. Defaults to Undefined. + default_factory: Callable that will be + called when a default value is needed for this attribute. + If both `default` and `default_factory` are set, an error will be raised. + init: Whether the attribute should be included in the constructor of the dataclass. Always `False`. + + Returns: + An instance of [`ModelPrivateAttr`][pydantic.fields.ModelPrivateAttr] class. + + Raises: + ValueError: If both `default` and `default_factory` are set. + """ + if default is not PydanticUndefined and default_factory is not None: + raise TypeError('cannot specify both default and default_factory') + + return ModelPrivateAttr( + default, + default_factory=default_factory, + ) + + +@dataclasses.dataclass(**_internal_dataclass.slots_true) +class ComputedFieldInfo: + """A container for data from `@computed_field` so that we can access it while building the pydantic-core schema. + + Attributes: + decorator_repr: A class variable representing the decorator string, '@computed_field'. + wrapped_property: The wrapped computed field property. + return_type: The type of the computed field property's return value. + alias: The alias of the property to be used during serialization. + alias_priority: The priority of the alias. This affects whether an alias generator is used. + title: Title of the computed field to include in the serialization JSON schema. + field_title_generator: A callable that takes a field name and returns title for it. + description: Description of the computed field to include in the serialization JSON schema. + deprecated: A deprecation message, an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport, + or a boolean. If `True`, a default deprecation message will be emitted when accessing the field. + examples: Example values of the computed field to include in the serialization JSON schema. + json_schema_extra: A dict or callable to provide extra JSON schema properties. + repr: A boolean indicating whether to include the field in the __repr__ output. + """ + + decorator_repr: ClassVar[str] = '@computed_field' + wrapped_property: property + return_type: Any + alias: str | None + alias_priority: int | None + title: str | None + field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None + description: str | None + deprecated: Deprecated | str | bool | None + examples: list[Any] | None + json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None + repr: bool + + @property + def deprecation_message(self) -> str | None: + """The deprecation message to be emitted, or `None` if not set.""" + if self.deprecated is None: + return None + if isinstance(self.deprecated, bool): + return 'deprecated' if self.deprecated else None + return self.deprecated if isinstance(self.deprecated, str) else self.deprecated.message + + +def _wrapped_property_is_private(property_: cached_property | property) -> bool: # type: ignore + """Returns true if provided property is private, False otherwise.""" + wrapped_name: str = '' + + if isinstance(property_, property): + wrapped_name = getattr(property_.fget, '__name__', '') + elif isinstance(property_, cached_property): # type: ignore + wrapped_name = getattr(property_.func, '__name__', '') # type: ignore + + return wrapped_name.startswith('_') and not wrapped_name.startswith('__') + + +# this should really be `property[T], cached_property[T]` but property is not generic unlike cached_property +# See https://github.com/python/typing/issues/985 and linked issues +PropertyT = typing.TypeVar('PropertyT') + + +@typing.overload +def computed_field( + *, + alias: str | None = None, + alias_priority: int | None = None, + title: str | None = None, + field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None, + description: str | None = None, + deprecated: Deprecated | str | bool | None = None, + examples: list[Any] | None = None, + json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, + repr: bool = True, + return_type: Any = PydanticUndefined, +) -> typing.Callable[[PropertyT], PropertyT]: ... + + +@typing.overload +def computed_field(__func: PropertyT) -> PropertyT: ... + + +def computed_field( + func: PropertyT | None = None, + /, + *, + alias: str | None = None, + alias_priority: int | None = None, + title: str | None = None, + field_title_generator: typing.Callable[[str, ComputedFieldInfo], str] | None = None, + description: str | None = None, + deprecated: Deprecated | str | bool | None = None, + examples: list[Any] | None = None, + json_schema_extra: JsonDict | typing.Callable[[JsonDict], None] | None = None, + repr: bool | None = None, + return_type: Any = PydanticUndefined, +) -> PropertyT | typing.Callable[[PropertyT], PropertyT]: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/fields#the-computed_field-decorator + + Decorator to include `property` and `cached_property` when serializing models or dataclasses. + + This is useful for fields that are computed from other fields, or for fields that are expensive to compute and should be cached. + + ```py + from pydantic import BaseModel, computed_field + + class Rectangle(BaseModel): + width: int + length: int + + @computed_field + @property + def area(self) -> int: + return self.width * self.length + + print(Rectangle(width=3, length=2).model_dump()) + #> {'width': 3, 'length': 2, 'area': 6} + ``` + + If applied to functions not yet decorated with `@property` or `@cached_property`, the function is + automatically wrapped with `property`. Although this is more concise, you will lose IntelliSense in your IDE, + and confuse static type checkers, thus explicit use of `@property` is recommended. + + !!! warning "Mypy Warning" + Even with the `@property` or `@cached_property` applied to your function before `@computed_field`, + mypy may throw a `Decorated property not supported` error. + See [mypy issue #1362](https://github.com/python/mypy/issues/1362), for more information. + To avoid this error message, add `# type: ignore[misc]` to the `@computed_field` line. + + [pyright](https://github.com/microsoft/pyright) supports `@computed_field` without error. + + ```py + import random + + from pydantic import BaseModel, computed_field + + class Square(BaseModel): + width: float + + @computed_field + def area(self) -> float: # converted to a `property` by `computed_field` + return round(self.width**2, 2) + + @area.setter + def area(self, new_area: float) -> None: + self.width = new_area**0.5 + + @computed_field(alias='the magic number', repr=False) + def random_number(self) -> int: + return random.randint(0, 1_000) + + square = Square(width=1.3) + + # `random_number` does not appear in representation + print(repr(square)) + #> Square(width=1.3, area=1.69) + + print(square.random_number) + #> 3 + + square.area = 4 + + print(square.model_dump_json(by_alias=True)) + #> {"width":2.0,"area":4.0,"the magic number":3} + ``` + + !!! warning "Overriding with `computed_field`" + You can't override a field from a parent class with a `computed_field` in the child class. + `mypy` complains about this behavior if allowed, and `dataclasses` doesn't allow this pattern either. + See the example below: + + ```py + from pydantic import BaseModel, computed_field + + class Parent(BaseModel): + a: str + + try: + + class Child(Parent): + @computed_field + @property + def a(self) -> str: + return 'new a' + + except ValueError as e: + print(repr(e)) + #> ValueError("you can't override a field with a computed field") + ``` + + Private properties decorated with `@computed_field` have `repr=False` by default. + + ```py + from functools import cached_property + + from pydantic import BaseModel, computed_field + + class Model(BaseModel): + foo: int + + @computed_field + @cached_property + def _private_cached_property(self) -> int: + return -self.foo + + @computed_field + @property + def _private_property(self) -> int: + return -self.foo + + m = Model(foo=1) + print(repr(m)) + #> M(foo=1) + ``` + + Args: + func: the function to wrap. + alias: alias to use when serializing this computed field, only used when `by_alias=True` + alias_priority: priority of the alias. This affects whether an alias generator is used + title: Title to use when including this computed field in JSON Schema + field_title_generator: A callable that takes a field name and returns title for it. + description: Description to use when including this computed field in JSON Schema, defaults to the function's + docstring + deprecated: A deprecation message (or an instance of `warnings.deprecated` or the `typing_extensions.deprecated` backport). + to be emitted when accessing the field. Or a boolean. This will automatically be set if the property is decorated with the + `deprecated` decorator. + examples: Example values to use when including this computed field in JSON Schema + json_schema_extra: A dict or callable to provide extra JSON schema properties. + repr: whether to include this computed field in model repr. + Default is `False` for private properties and `True` for public properties. + return_type: optional return for serialization logic to expect when serializing to JSON, if included + this must be correct, otherwise a `TypeError` is raised. + If you don't include a return type Any is used, which does runtime introspection to handle arbitrary + objects. + + Returns: + A proxy wrapper for the property. + """ + + def dec(f: Any) -> Any: + nonlocal description, deprecated, return_type, alias_priority + unwrapped = _decorators.unwrap_wrapped_function(f) + + if description is None and unwrapped.__doc__: + description = inspect.cleandoc(unwrapped.__doc__) + + if deprecated is None and hasattr(unwrapped, '__deprecated__'): + deprecated = unwrapped.__deprecated__ + + # if the function isn't already decorated with `@property` (or another descriptor), then we wrap it now + f = _decorators.ensure_property(f) + alias_priority = (alias_priority or 2) if alias is not None else None + + if repr is None: + repr_: bool = not _wrapped_property_is_private(property_=f) + else: + repr_ = repr + + dec_info = ComputedFieldInfo( + f, + return_type, + alias, + alias_priority, + title, + field_title_generator, + description, + deprecated, + examples, + json_schema_extra, + repr_, + ) + return _decorators.PydanticDescriptorProxy(f, dec_info) + + if func is None: + return dec + else: + return dec(func) diff --git a/env/Lib/site-packages/pydantic/functional_serializers.py b/env/Lib/site-packages/pydantic/functional_serializers.py new file mode 100644 index 0000000..478c4a9 --- /dev/null +++ b/env/Lib/site-packages/pydantic/functional_serializers.py @@ -0,0 +1,395 @@ +"""This module contains related classes and functions for serialization.""" + +from __future__ import annotations + +import dataclasses +from functools import partialmethod +from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union, overload + +from pydantic_core import PydanticUndefined, core_schema +from pydantic_core import core_schema as _core_schema +from typing_extensions import Annotated, Literal, TypeAlias + +from . import PydanticUndefinedAnnotation +from ._internal import _decorators, _internal_dataclass +from .annotated_handlers import GetCoreSchemaHandler + + +@dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True) +class PlainSerializer: + """Plain serializers use a function to modify the output of serialization. + + This is particularly helpful when you want to customize the serialization for annotated types. + Consider an input of `list`, which will be serialized into a space-delimited string. + + ```python + from typing import List + + from typing_extensions import Annotated + + from pydantic import BaseModel, PlainSerializer + + CustomStr = Annotated[ + List, PlainSerializer(lambda x: ' '.join(x), return_type=str) + ] + + class StudentModel(BaseModel): + courses: CustomStr + + student = StudentModel(courses=['Math', 'Chemistry', 'English']) + print(student.model_dump()) + #> {'courses': 'Math Chemistry English'} + ``` + + Attributes: + func: The serializer function. + return_type: The return type for the function. If omitted it will be inferred from the type annotation. + when_used: Determines when this serializer should be used. Accepts a string with values `'always'`, + `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'. + """ + + func: core_schema.SerializerFunction + return_type: Any = PydanticUndefined + when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always' + + def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + """Gets the Pydantic core schema. + + Args: + source_type: The source type. + handler: The `GetCoreSchemaHandler` instance. + + Returns: + The Pydantic core schema. + """ + schema = handler(source_type) + try: + return_type = _decorators.get_function_return_type( + self.func, self.return_type, handler._get_types_namespace() + ) + except NameError as e: + raise PydanticUndefinedAnnotation.from_name_error(e) from e + return_schema = None if return_type is PydanticUndefined else handler.generate_schema(return_type) + schema['serialization'] = core_schema.plain_serializer_function_ser_schema( + function=self.func, + info_arg=_decorators.inspect_annotated_serializer(self.func, 'plain'), + return_schema=return_schema, + when_used=self.when_used, + ) + return schema + + +@dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True) +class WrapSerializer: + """Wrap serializers receive the raw inputs along with a handler function that applies the standard serialization + logic, and can modify the resulting value before returning it as the final output of serialization. + + For example, here's a scenario in which a wrap serializer transforms timezones to UTC **and** utilizes the existing `datetime` serialization logic. + + ```python + from datetime import datetime, timezone + from typing import Any, Dict + + from typing_extensions import Annotated + + from pydantic import BaseModel, WrapSerializer + + class EventDatetime(BaseModel): + start: datetime + end: datetime + + def convert_to_utc(value: Any, handler, info) -> Dict[str, datetime]: + # Note that `helper` can actually help serialize the `value` for further custom serialization in case it's a subclass. + partial_result = handler(value, info) + if info.mode == 'json': + return { + k: datetime.fromisoformat(v).astimezone(timezone.utc) + for k, v in partial_result.items() + } + return {k: v.astimezone(timezone.utc) for k, v in partial_result.items()} + + UTCEventDatetime = Annotated[EventDatetime, WrapSerializer(convert_to_utc)] + + class EventModel(BaseModel): + event_datetime: UTCEventDatetime + + dt = EventDatetime( + start='2024-01-01T07:00:00-08:00', end='2024-01-03T20:00:00+06:00' + ) + event = EventModel(event_datetime=dt) + print(event.model_dump()) + ''' + { + 'event_datetime': { + 'start': datetime.datetime( + 2024, 1, 1, 15, 0, tzinfo=datetime.timezone.utc + ), + 'end': datetime.datetime( + 2024, 1, 3, 14, 0, tzinfo=datetime.timezone.utc + ), + } + } + ''' + + print(event.model_dump_json()) + ''' + {"event_datetime":{"start":"2024-01-01T15:00:00Z","end":"2024-01-03T14:00:00Z"}} + ''' + ``` + + Attributes: + func: The serializer function to be wrapped. + return_type: The return type for the function. If omitted it will be inferred from the type annotation. + when_used: Determines when this serializer should be used. Accepts a string with values `'always'`, + `'unless-none'`, `'json'`, and `'json-unless-none'`. Defaults to 'always'. + """ + + func: core_schema.WrapSerializerFunction + return_type: Any = PydanticUndefined + when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always' + + def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + """This method is used to get the Pydantic core schema of the class. + + Args: + source_type: Source type. + handler: Core schema handler. + + Returns: + The generated core schema of the class. + """ + schema = handler(source_type) + try: + return_type = _decorators.get_function_return_type( + self.func, self.return_type, handler._get_types_namespace() + ) + except NameError as e: + raise PydanticUndefinedAnnotation.from_name_error(e) from e + return_schema = None if return_type is PydanticUndefined else handler.generate_schema(return_type) + schema['serialization'] = core_schema.wrap_serializer_function_ser_schema( + function=self.func, + info_arg=_decorators.inspect_annotated_serializer(self.func, 'wrap'), + return_schema=return_schema, + when_used=self.when_used, + ) + return schema + + +if TYPE_CHECKING: + _PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]] + _PlainSerializationFunction = Union[_core_schema.SerializerFunction, _PartialClsOrStaticMethod] + _WrapSerializationFunction = Union[_core_schema.WrapSerializerFunction, _PartialClsOrStaticMethod] + _PlainSerializeMethodType = TypeVar('_PlainSerializeMethodType', bound=_PlainSerializationFunction) + _WrapSerializeMethodType = TypeVar('_WrapSerializeMethodType', bound=_WrapSerializationFunction) + + +@overload +def field_serializer( + field: str, + /, + *fields: str, + return_type: Any = ..., + when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = ..., + check_fields: bool | None = ..., +) -> Callable[[_PlainSerializeMethodType], _PlainSerializeMethodType]: ... + + +@overload +def field_serializer( + field: str, + /, + *fields: str, + mode: Literal['plain'], + return_type: Any = ..., + when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = ..., + check_fields: bool | None = ..., +) -> Callable[[_PlainSerializeMethodType], _PlainSerializeMethodType]: ... + + +@overload +def field_serializer( + field: str, + /, + *fields: str, + mode: Literal['wrap'], + return_type: Any = ..., + when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = ..., + check_fields: bool | None = ..., +) -> Callable[[_WrapSerializeMethodType], _WrapSerializeMethodType]: ... + + +def field_serializer( + *fields: str, + mode: Literal['plain', 'wrap'] = 'plain', + return_type: Any = PydanticUndefined, + when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always', + check_fields: bool | None = None, +) -> Callable[[Any], Any]: + """Decorator that enables custom field serialization. + + In the below example, a field of type `set` is used to mitigate duplication. A `field_serializer` is used to serialize the data as a sorted list. + + ```python + from typing import Set + + from pydantic import BaseModel, field_serializer + + class StudentModel(BaseModel): + name: str = 'Jane' + courses: Set[str] + + @field_serializer('courses', when_used='json') + def serialize_courses_in_order(courses: Set[str]): + return sorted(courses) + + student = StudentModel(courses={'Math', 'Chemistry', 'English'}) + print(student.model_dump_json()) + #> {"name":"Jane","courses":["Chemistry","English","Math"]} + ``` + + See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information. + + Four signatures are supported: + + - `(self, value: Any, info: FieldSerializationInfo)` + - `(self, value: Any, nxt: SerializerFunctionWrapHandler, info: FieldSerializationInfo)` + - `(value: Any, info: SerializationInfo)` + - `(value: Any, nxt: SerializerFunctionWrapHandler, info: SerializationInfo)` + + Args: + fields: Which field(s) the method should be called on. + mode: The serialization mode. + + - `plain` means the function will be called instead of the default serialization logic, + - `wrap` means the function will be called with an argument to optionally call the + default serialization logic. + return_type: Optional return type for the function, if omitted it will be inferred from the type annotation. + when_used: Determines the serializer will be used for serialization. + check_fields: Whether to check that the fields actually exist on the model. + + Returns: + The decorator function. + """ + + def dec( + f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any], + ) -> _decorators.PydanticDescriptorProxy[Any]: + dec_info = _decorators.FieldSerializerDecoratorInfo( + fields=fields, + mode=mode, + return_type=return_type, + when_used=when_used, + check_fields=check_fields, + ) + return _decorators.PydanticDescriptorProxy(f, dec_info) + + return dec + + +FuncType = TypeVar('FuncType', bound=Callable[..., Any]) + + +@overload +def model_serializer(__f: FuncType) -> FuncType: ... + + +@overload +def model_serializer( + *, + mode: Literal['plain', 'wrap'] = ..., + when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always', + return_type: Any = ..., +) -> Callable[[FuncType], FuncType]: ... + + +def model_serializer( + f: Callable[..., Any] | None = None, + /, + *, + mode: Literal['plain', 'wrap'] = 'plain', + when_used: Literal['always', 'unless-none', 'json', 'json-unless-none'] = 'always', + return_type: Any = PydanticUndefined, +) -> Callable[[Any], Any]: + """Decorator that enables custom model serialization. + + This is useful when a model need to be serialized in a customized manner, allowing for flexibility beyond just specific fields. + + An example would be to serialize temperature to the same temperature scale, such as degrees Celsius. + + ```python + from typing import Literal + + from pydantic import BaseModel, model_serializer + + class TemperatureModel(BaseModel): + unit: Literal['C', 'F'] + value: int + + @model_serializer() + def serialize_model(self): + if self.unit == 'F': + return {'unit': 'C', 'value': int((self.value - 32) / 1.8)} + return {'unit': self.unit, 'value': self.value} + + temperature = TemperatureModel(unit='F', value=212) + print(temperature.model_dump()) + #> {'unit': 'C', 'value': 100} + ``` + + See [Custom serializers](../concepts/serialization.md#custom-serializers) for more information. + + Args: + f: The function to be decorated. + mode: The serialization mode. + + - `'plain'` means the function will be called instead of the default serialization logic + - `'wrap'` means the function will be called with an argument to optionally call the default + serialization logic. + when_used: Determines when this serializer should be used. + return_type: The return type for the function. If omitted it will be inferred from the type annotation. + + Returns: + The decorator function. + """ + + def dec(f: Callable[..., Any]) -> _decorators.PydanticDescriptorProxy[Any]: + dec_info = _decorators.ModelSerializerDecoratorInfo(mode=mode, return_type=return_type, when_used=when_used) + return _decorators.PydanticDescriptorProxy(f, dec_info) + + if f is None: + return dec + else: + return dec(f) # type: ignore + + +AnyType = TypeVar('AnyType') + + +if TYPE_CHECKING: + SerializeAsAny = Annotated[AnyType, ...] # SerializeAsAny[list[str]] will be treated by type checkers as list[str] + """Force serialization to ignore whatever is defined in the schema and instead ask the object + itself how it should be serialized. + In particular, this means that when model subclasses are serialized, fields present in the subclass + but not in the original schema will be included. + """ +else: + + @dataclasses.dataclass(**_internal_dataclass.slots_true) + class SerializeAsAny: # noqa: D101 + def __class_getitem__(cls, item: Any) -> Any: + return Annotated[item, SerializeAsAny()] + + def __get_pydantic_core_schema__( + self, source_type: Any, handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + schema = handler(source_type) + schema_to_update = schema + while schema_to_update['type'] == 'definitions': + schema_to_update = schema_to_update.copy() + schema_to_update = schema_to_update['schema'] + schema_to_update['serialization'] = core_schema.wrap_serializer_function_ser_schema( + lambda x, h: h(x), schema=core_schema.any_schema() + ) + return schema + + __hash__ = object.__hash__ diff --git a/env/Lib/site-packages/pydantic/functional_validators.py b/env/Lib/site-packages/pydantic/functional_validators.py new file mode 100644 index 0000000..b29880f --- /dev/null +++ b/env/Lib/site-packages/pydantic/functional_validators.py @@ -0,0 +1,697 @@ +"""This module contains related classes and functions for validation.""" + +from __future__ import annotations as _annotations + +import dataclasses +import sys +from functools import partialmethod +from types import FunctionType +from typing import TYPE_CHECKING, Any, Callable, TypeVar, Union, cast, overload + +from pydantic_core import core_schema +from pydantic_core import core_schema as _core_schema +from typing_extensions import Annotated, Literal, TypeAlias + +from . import GetCoreSchemaHandler as _GetCoreSchemaHandler +from ._internal import _core_metadata, _decorators, _generics, _internal_dataclass +from .annotated_handlers import GetCoreSchemaHandler +from .errors import PydanticUserError + +if sys.version_info < (3, 11): + from typing_extensions import Protocol +else: + from typing import Protocol + +_inspect_validator = _decorators.inspect_validator + + +@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true) +class AfterValidator: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/validators/#annotated-validators + + A metadata class that indicates that a validation should be applied **after** the inner validation logic. + + Attributes: + func: The validator function. + + Example: + ```py + from typing_extensions import Annotated + + from pydantic import AfterValidator, BaseModel, ValidationError + + MyInt = Annotated[int, AfterValidator(lambda v: v + 1)] + + class Model(BaseModel): + a: MyInt + + print(Model(a=1).a) + #> 2 + + try: + Model(a='a') + except ValidationError as e: + print(e.json(indent=2)) + ''' + [ + { + "type": "int_parsing", + "loc": [ + "a" + ], + "msg": "Input should be a valid integer, unable to parse string as an integer", + "input": "a", + "url": "https://errors.pydantic.dev/2/v/int_parsing" + } + ] + ''' + ``` + """ + + func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction + + def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchemaHandler) -> core_schema.CoreSchema: + schema = handler(source_type) + info_arg = _inspect_validator(self.func, 'after') + if info_arg: + func = cast(core_schema.WithInfoValidatorFunction, self.func) + return core_schema.with_info_after_validator_function(func, schema=schema, field_name=handler.field_name) + else: + func = cast(core_schema.NoInfoValidatorFunction, self.func) + return core_schema.no_info_after_validator_function(func, schema=schema) + + +@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true) +class BeforeValidator: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/validators/#annotated-validators + + A metadata class that indicates that a validation should be applied **before** the inner validation logic. + + Attributes: + func: The validator function. + + Example: + ```py + from typing_extensions import Annotated + + from pydantic import BaseModel, BeforeValidator + + MyInt = Annotated[int, BeforeValidator(lambda v: v + 1)] + + class Model(BaseModel): + a: MyInt + + print(Model(a=1).a) + #> 2 + + try: + Model(a='a') + except TypeError as e: + print(e) + #> can only concatenate str (not "int") to str + ``` + """ + + func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction + + def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchemaHandler) -> core_schema.CoreSchema: + schema = handler(source_type) + info_arg = _inspect_validator(self.func, 'before') + if info_arg: + func = cast(core_schema.WithInfoValidatorFunction, self.func) + return core_schema.with_info_before_validator_function(func, schema=schema, field_name=handler.field_name) + else: + func = cast(core_schema.NoInfoValidatorFunction, self.func) + return core_schema.no_info_before_validator_function(func, schema=schema) + + +@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true) +class PlainValidator: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/validators/#annotated-validators + + A metadata class that indicates that a validation should be applied **instead** of the inner validation logic. + + Attributes: + func: The validator function. + + Example: + ```py + from typing_extensions import Annotated + + from pydantic import BaseModel, PlainValidator + + MyInt = Annotated[int, PlainValidator(lambda v: int(v) + 1)] + + class Model(BaseModel): + a: MyInt + + print(Model(a='1').a) + #> 2 + ``` + """ + + func: core_schema.NoInfoValidatorFunction | core_schema.WithInfoValidatorFunction + + def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchemaHandler) -> core_schema.CoreSchema: + # Note that for some valid uses of PlainValidator, it is not possible to generate a core schema for the + # source_type, so calling `handler(source_type)` will error, which prevents us from generating a proper + # serialization schema. To work around this for use cases that will not involve serialization, we simply + # catch any PydanticSchemaGenerationError that may be raised while attempting to build the serialization schema + # and abort any attempts to handle special serialization. + from pydantic import PydanticSchemaGenerationError + + try: + schema = handler(source_type) + serialization = core_schema.wrap_serializer_function_ser_schema(function=lambda v, h: h(v), schema=schema) + except PydanticSchemaGenerationError: + serialization = None + + info_arg = _inspect_validator(self.func, 'plain') + if info_arg: + func = cast(core_schema.WithInfoValidatorFunction, self.func) + return core_schema.with_info_plain_validator_function( + func, field_name=handler.field_name, serialization=serialization + ) + else: + func = cast(core_schema.NoInfoValidatorFunction, self.func) + return core_schema.no_info_plain_validator_function(func, serialization=serialization) + + +@dataclasses.dataclass(frozen=True, **_internal_dataclass.slots_true) +class WrapValidator: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/validators/#annotated-validators + + A metadata class that indicates that a validation should be applied **around** the inner validation logic. + + Attributes: + func: The validator function. + + ```py + from datetime import datetime + + from typing_extensions import Annotated + + from pydantic import BaseModel, ValidationError, WrapValidator + + def validate_timestamp(v, handler): + if v == 'now': + # we don't want to bother with further validation, just return the new value + return datetime.now() + try: + return handler(v) + except ValidationError: + # validation failed, in this case we want to return a default value + return datetime(2000, 1, 1) + + MyTimestamp = Annotated[datetime, WrapValidator(validate_timestamp)] + + class Model(BaseModel): + a: MyTimestamp + + print(Model(a='now').a) + #> 2032-01-02 03:04:05.000006 + print(Model(a='invalid').a) + #> 2000-01-01 00:00:00 + ``` + """ + + func: core_schema.NoInfoWrapValidatorFunction | core_schema.WithInfoWrapValidatorFunction + + def __get_pydantic_core_schema__(self, source_type: Any, handler: _GetCoreSchemaHandler) -> core_schema.CoreSchema: + schema = handler(source_type) + info_arg = _inspect_validator(self.func, 'wrap') + if info_arg: + func = cast(core_schema.WithInfoWrapValidatorFunction, self.func) + return core_schema.with_info_wrap_validator_function(func, schema=schema, field_name=handler.field_name) + else: + func = cast(core_schema.NoInfoWrapValidatorFunction, self.func) + return core_schema.no_info_wrap_validator_function(func, schema=schema) + + +if TYPE_CHECKING: + + class _OnlyValueValidatorClsMethod(Protocol): + def __call__(self, cls: Any, value: Any, /) -> Any: ... + + class _V2ValidatorClsMethod(Protocol): + def __call__(self, cls: Any, value: Any, info: _core_schema.ValidationInfo, /) -> Any: ... + + class _V2WrapValidatorClsMethod(Protocol): + def __call__( + self, + cls: Any, + value: Any, + handler: _core_schema.ValidatorFunctionWrapHandler, + info: _core_schema.ValidationInfo, + /, + ) -> Any: ... + + _V2Validator = Union[ + _V2ValidatorClsMethod, + _core_schema.WithInfoValidatorFunction, + _OnlyValueValidatorClsMethod, + _core_schema.NoInfoValidatorFunction, + ] + + _V2WrapValidator = Union[ + _V2WrapValidatorClsMethod, + _core_schema.WithInfoWrapValidatorFunction, + ] + + _PartialClsOrStaticMethod: TypeAlias = Union[classmethod[Any, Any, Any], staticmethod[Any, Any], partialmethod[Any]] + + _V2BeforeAfterOrPlainValidatorType = TypeVar( + '_V2BeforeAfterOrPlainValidatorType', + _V2Validator, + _PartialClsOrStaticMethod, + ) + _V2WrapValidatorType = TypeVar('_V2WrapValidatorType', _V2WrapValidator, _PartialClsOrStaticMethod) + + +@overload +def field_validator( + field: str, + /, + *fields: str, + mode: Literal['before', 'after', 'plain'] = ..., + check_fields: bool | None = ..., +) -> Callable[[_V2BeforeAfterOrPlainValidatorType], _V2BeforeAfterOrPlainValidatorType]: ... + + +@overload +def field_validator( + field: str, + /, + *fields: str, + mode: Literal['wrap'], + check_fields: bool | None = ..., +) -> Callable[[_V2WrapValidatorType], _V2WrapValidatorType]: ... + + +FieldValidatorModes: TypeAlias = Literal['before', 'after', 'wrap', 'plain'] + + +def field_validator( + field: str, + /, + *fields: str, + mode: FieldValidatorModes = 'after', + check_fields: bool | None = None, +) -> Callable[[Any], Any]: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/validators/#field-validators + + Decorate methods on the class indicating that they should be used to validate fields. + + Example usage: + ```py + from typing import Any + + from pydantic import ( + BaseModel, + ValidationError, + field_validator, + ) + + class Model(BaseModel): + a: str + + @field_validator('a') + @classmethod + def ensure_foobar(cls, v: Any): + if 'foobar' not in v: + raise ValueError('"foobar" not found in a') + return v + + print(repr(Model(a='this is foobar good'))) + #> Model(a='this is foobar good') + + try: + Model(a='snap') + except ValidationError as exc_info: + print(exc_info) + ''' + 1 validation error for Model + a + Value error, "foobar" not found in a [type=value_error, input_value='snap', input_type=str] + ''' + ``` + + For more in depth examples, see [Field Validators](../concepts/validators.md#field-validators). + + Args: + field: The first field the `field_validator` should be called on; this is separate + from `fields` to ensure an error is raised if you don't pass at least one. + *fields: Additional field(s) the `field_validator` should be called on. + mode: Specifies whether to validate the fields before or after validation. + check_fields: Whether to check that the fields actually exist on the model. + + Returns: + A decorator that can be used to decorate a function to be used as a field_validator. + + Raises: + PydanticUserError: + - If `@field_validator` is used bare (with no fields). + - If the args passed to `@field_validator` as fields are not strings. + - If `@field_validator` applied to instance methods. + """ + if isinstance(field, FunctionType): + raise PydanticUserError( + '`@field_validator` should be used with fields and keyword arguments, not bare. ' + "E.g. usage should be `@validator('', ...)`", + code='validator-no-fields', + ) + fields = field, *fields + if not all(isinstance(field, str) for field in fields): + raise PydanticUserError( + '`@field_validator` fields should be passed as separate string args. ' + "E.g. usage should be `@validator('', '', ...)`", + code='validator-invalid-fields', + ) + + def dec( + f: Callable[..., Any] | staticmethod[Any, Any] | classmethod[Any, Any, Any], + ) -> _decorators.PydanticDescriptorProxy[Any]: + if _decorators.is_instance_method_from_sig(f): + raise PydanticUserError( + '`@field_validator` cannot be applied to instance methods', code='validator-instance-method' + ) + + # auto apply the @classmethod decorator + f = _decorators.ensure_classmethod_based_on_signature(f) + + dec_info = _decorators.FieldValidatorDecoratorInfo(fields=fields, mode=mode, check_fields=check_fields) + return _decorators.PydanticDescriptorProxy(f, dec_info) + + return dec + + +_ModelType = TypeVar('_ModelType') +_ModelTypeCo = TypeVar('_ModelTypeCo', covariant=True) + + +class ModelWrapValidatorHandler(_core_schema.ValidatorFunctionWrapHandler, Protocol[_ModelTypeCo]): + """@model_validator decorated function handler argument type. This is used when `mode='wrap'`.""" + + def __call__( # noqa: D102 + self, + value: Any, + outer_location: str | int | None = None, + /, + ) -> _ModelTypeCo: # pragma: no cover + ... + + +class ModelWrapValidatorWithoutInfo(Protocol[_ModelType]): + """A @model_validator decorated function signature. + This is used when `mode='wrap'` and the function does not have info argument. + """ + + def __call__( # noqa: D102 + self, + cls: type[_ModelType], + # this can be a dict, a model instance + # or anything else that gets passed to validate_python + # thus validators _must_ handle all cases + value: Any, + handler: ModelWrapValidatorHandler[_ModelType], + /, + ) -> _ModelType: ... + + +class ModelWrapValidator(Protocol[_ModelType]): + """A @model_validator decorated function signature. This is used when `mode='wrap'`.""" + + def __call__( # noqa: D102 + self, + cls: type[_ModelType], + # this can be a dict, a model instance + # or anything else that gets passed to validate_python + # thus validators _must_ handle all cases + value: Any, + handler: ModelWrapValidatorHandler[_ModelType], + info: _core_schema.ValidationInfo, + /, + ) -> _ModelType: ... + + +class FreeModelBeforeValidatorWithoutInfo(Protocol): + """A @model_validator decorated function signature. + This is used when `mode='before'` and the function does not have info argument. + """ + + def __call__( # noqa: D102 + self, + # this can be a dict, a model instance + # or anything else that gets passed to validate_python + # thus validators _must_ handle all cases + value: Any, + /, + ) -> Any: ... + + +class ModelBeforeValidatorWithoutInfo(Protocol): + """A @model_validator decorated function signature. + This is used when `mode='before'` and the function does not have info argument. + """ + + def __call__( # noqa: D102 + self, + cls: Any, + # this can be a dict, a model instance + # or anything else that gets passed to validate_python + # thus validators _must_ handle all cases + value: Any, + /, + ) -> Any: ... + + +class FreeModelBeforeValidator(Protocol): + """A `@model_validator` decorated function signature. This is used when `mode='before'`.""" + + def __call__( # noqa: D102 + self, + # this can be a dict, a model instance + # or anything else that gets passed to validate_python + # thus validators _must_ handle all cases + value: Any, + info: _core_schema.ValidationInfo, + /, + ) -> Any: ... + + +class ModelBeforeValidator(Protocol): + """A `@model_validator` decorated function signature. This is used when `mode='before'`.""" + + def __call__( # noqa: D102 + self, + cls: Any, + # this can be a dict, a model instance + # or anything else that gets passed to validate_python + # thus validators _must_ handle all cases + value: Any, + info: _core_schema.ValidationInfo, + /, + ) -> Any: ... + + +ModelAfterValidatorWithoutInfo = Callable[[_ModelType], _ModelType] +"""A `@model_validator` decorated function signature. This is used when `mode='after'` and the function does not +have info argument. +""" + +ModelAfterValidator = Callable[[_ModelType, _core_schema.ValidationInfo], _ModelType] +"""A `@model_validator` decorated function signature. This is used when `mode='after'`.""" + +_AnyModelWrapValidator = Union[ModelWrapValidator[_ModelType], ModelWrapValidatorWithoutInfo[_ModelType]] +_AnyModeBeforeValidator = Union[ + FreeModelBeforeValidator, ModelBeforeValidator, FreeModelBeforeValidatorWithoutInfo, ModelBeforeValidatorWithoutInfo +] +_AnyModelAfterValidator = Union[ModelAfterValidator[_ModelType], ModelAfterValidatorWithoutInfo[_ModelType]] + + +@overload +def model_validator( + *, + mode: Literal['wrap'], +) -> Callable[ + [_AnyModelWrapValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo] +]: ... + + +@overload +def model_validator( + *, + mode: Literal['before'], +) -> Callable[ + [_AnyModeBeforeValidator], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo] +]: ... + + +@overload +def model_validator( + *, + mode: Literal['after'], +) -> Callable[ + [_AnyModelAfterValidator[_ModelType]], _decorators.PydanticDescriptorProxy[_decorators.ModelValidatorDecoratorInfo] +]: ... + + +def model_validator( + *, + mode: Literal['wrap', 'before', 'after'], +) -> Any: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/validators/#model-validators + + Decorate model methods for validation purposes. + + Example usage: + ```py + from typing_extensions import Self + + from pydantic import BaseModel, ValidationError, model_validator + + class Square(BaseModel): + width: float + height: float + + @model_validator(mode='after') + def verify_square(self) -> Self: + if self.width != self.height: + raise ValueError('width and height do not match') + return self + + s = Square(width=1, height=1) + print(repr(s)) + #> Square(width=1.0, height=1.0) + + try: + Square(width=1, height=2) + except ValidationError as e: + print(e) + ''' + 1 validation error for Square + Value error, width and height do not match [type=value_error, input_value={'width': 1, 'height': 2}, input_type=dict] + ''' + ``` + + For more in depth examples, see [Model Validators](../concepts/validators.md#model-validators). + + Args: + mode: A required string literal that specifies the validation mode. + It can be one of the following: 'wrap', 'before', or 'after'. + + Returns: + A decorator that can be used to decorate a function to be used as a model validator. + """ + + def dec(f: Any) -> _decorators.PydanticDescriptorProxy[Any]: + # auto apply the @classmethod decorator + f = _decorators.ensure_classmethod_based_on_signature(f) + dec_info = _decorators.ModelValidatorDecoratorInfo(mode=mode) + return _decorators.PydanticDescriptorProxy(f, dec_info) + + return dec + + +AnyType = TypeVar('AnyType') + + +if TYPE_CHECKING: + # If we add configurable attributes to IsInstance, we'd probably need to stop hiding it from type checkers like this + InstanceOf = Annotated[AnyType, ...] # `IsInstance[Sequence]` will be recognized by type checkers as `Sequence` + +else: + + @dataclasses.dataclass(**_internal_dataclass.slots_true) + class InstanceOf: + '''Generic type for annotating a type that is an instance of a given class. + + Example: + ```py + from pydantic import BaseModel, InstanceOf + + class Foo: + ... + + class Bar(BaseModel): + foo: InstanceOf[Foo] + + Bar(foo=Foo()) + try: + Bar(foo=42) + except ValidationError as e: + print(e) + """ + [ + │ { + │ │ 'type': 'is_instance_of', + │ │ 'loc': ('foo',), + │ │ 'msg': 'Input should be an instance of Foo', + │ │ 'input': 42, + │ │ 'ctx': {'class': 'Foo'}, + │ │ 'url': 'https://errors.pydantic.dev/0.38.0/v/is_instance_of' + │ } + ] + """ + ``` + ''' + + @classmethod + def __class_getitem__(cls, item: AnyType) -> AnyType: + return Annotated[item, cls()] + + @classmethod + def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + from pydantic import PydanticSchemaGenerationError + + # use the generic _origin_ as the second argument to isinstance when appropriate + instance_of_schema = core_schema.is_instance_schema(_generics.get_origin(source) or source) + + try: + # Try to generate the "standard" schema, which will be used when loading from JSON + original_schema = handler(source) + except PydanticSchemaGenerationError: + # If that fails, just produce a schema that can validate from python + return instance_of_schema + else: + # Use the "original" approach to serialization + instance_of_schema['serialization'] = core_schema.wrap_serializer_function_ser_schema( + function=lambda v, h: h(v), schema=original_schema + ) + return core_schema.json_or_python_schema(python_schema=instance_of_schema, json_schema=original_schema) + + __hash__ = object.__hash__ + + +if TYPE_CHECKING: + SkipValidation = Annotated[AnyType, ...] # SkipValidation[list[str]] will be treated by type checkers as list[str] +else: + + @dataclasses.dataclass(**_internal_dataclass.slots_true) + class SkipValidation: + """If this is applied as an annotation (e.g., via `x: Annotated[int, SkipValidation]`), validation will be + skipped. You can also use `SkipValidation[int]` as a shorthand for `Annotated[int, SkipValidation]`. + + This can be useful if you want to use a type annotation for documentation/IDE/type-checking purposes, + and know that it is safe to skip validation for one or more of the fields. + + Because this converts the validation schema to `any_schema`, subsequent annotation-applied transformations + may not have the expected effects. Therefore, when used, this annotation should generally be the final + annotation applied to a type. + """ + + def __class_getitem__(cls, item: Any) -> Any: + return Annotated[item, SkipValidation()] + + @classmethod + def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + original_schema = handler(source) + metadata = _core_metadata.build_metadata_dict(js_annotation_functions=[lambda _c, h: h(original_schema)]) + return core_schema.any_schema( + metadata=metadata, + serialization=core_schema.wrap_serializer_function_ser_schema( + function=lambda v, h: h(v), schema=original_schema + ), + ) + + __hash__ = object.__hash__ diff --git a/env/Lib/site-packages/pydantic/generics.py b/env/Lib/site-packages/pydantic/generics.py new file mode 100644 index 0000000..3f1070d --- /dev/null +++ b/env/Lib/site-packages/pydantic/generics.py @@ -0,0 +1,5 @@ +"""The `generics` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/json.py b/env/Lib/site-packages/pydantic/json.py new file mode 100644 index 0000000..bcaff9f --- /dev/null +++ b/env/Lib/site-packages/pydantic/json.py @@ -0,0 +1,5 @@ +"""The `json` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/json_schema.py b/env/Lib/site-packages/pydantic/json_schema.py new file mode 100644 index 0000000..63dcde7 --- /dev/null +++ b/env/Lib/site-packages/pydantic/json_schema.py @@ -0,0 +1,2520 @@ +""" +Usage docs: https://docs.pydantic.dev/2.5/concepts/json_schema/ + +The `json_schema` module contains classes and functions to allow the way [JSON Schema](https://json-schema.org/) +is generated to be customized. + +In general you shouldn't need to use this module directly; instead, you can use +[`BaseModel.model_json_schema`][pydantic.BaseModel.model_json_schema] and +[`TypeAdapter.json_schema`][pydantic.TypeAdapter.json_schema]. +""" + +from __future__ import annotations as _annotations + +import dataclasses +import inspect +import math +import re +import warnings +from collections import defaultdict +from copy import deepcopy +from dataclasses import is_dataclass +from enum import Enum +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Counter, + Dict, + Hashable, + Iterable, + NewType, + Pattern, + Sequence, + Tuple, + TypeVar, + Union, + cast, +) + +import pydantic_core +from pydantic_core import CoreSchema, PydanticOmit, core_schema, to_jsonable_python +from pydantic_core.core_schema import ComputedField +from typing_extensions import Annotated, Literal, TypeAlias, assert_never, deprecated, final + +from pydantic.warnings import PydanticDeprecatedSince26 + +from ._internal import ( + _config, + _core_metadata, + _core_utils, + _decorators, + _internal_dataclass, + _mock_val_ser, + _schema_generation_shared, + _typing_extra, +) +from .annotated_handlers import GetJsonSchemaHandler +from .config import JsonDict, JsonSchemaExtraCallable, JsonValue +from .errors import PydanticInvalidForJsonSchema, PydanticSchemaGenerationError, PydanticUserError + +if TYPE_CHECKING: + from . import ConfigDict + from ._internal._core_utils import CoreSchemaField, CoreSchemaOrField + from ._internal._dataclasses import PydanticDataclass + from ._internal._schema_generation_shared import GetJsonSchemaFunction + from .main import BaseModel + + +CoreSchemaOrFieldType = Literal[core_schema.CoreSchemaType, core_schema.CoreSchemaFieldType] +""" +A type alias for defined schema types that represents a union of +`core_schema.CoreSchemaType` and +`core_schema.CoreSchemaFieldType`. +""" + +JsonSchemaValue = Dict[str, Any] +""" +A type alias for a JSON schema value. This is a dictionary of string keys to arbitrary JSON values. +""" + +JsonSchemaMode = Literal['validation', 'serialization'] +""" +A type alias that represents the mode of a JSON schema; either 'validation' or 'serialization'. + +For some types, the inputs to validation differ from the outputs of serialization. For example, +computed fields will only be present when serializing, and should not be provided when +validating. This flag provides a way to indicate whether you want the JSON schema required +for validation inputs, or that will be matched by serialization outputs. +""" + +_MODE_TITLE_MAPPING: dict[JsonSchemaMode, str] = {'validation': 'Input', 'serialization': 'Output'} + + +@deprecated( + '`update_json_schema` is deprecated, use a simple `my_dict.update(update_dict)` call instead.', + category=None, +) +def update_json_schema(schema: JsonSchemaValue, updates: dict[str, Any]) -> JsonSchemaValue: + """Update a JSON schema in-place by providing a dictionary of updates. + + This function sets the provided key-value pairs in the schema and returns the updated schema. + + Args: + schema: The JSON schema to update. + updates: A dictionary of key-value pairs to set in the schema. + + Returns: + The updated JSON schema. + """ + schema.update(updates) + return schema + + +JsonSchemaWarningKind = Literal['skipped-choice', 'non-serializable-default'] +""" +A type alias representing the kinds of warnings that can be emitted during JSON schema generation. + +See [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message] +for more details. +""" + + +class PydanticJsonSchemaWarning(UserWarning): + """This class is used to emit warnings produced during JSON schema generation. + See the [`GenerateJsonSchema.emit_warning`][pydantic.json_schema.GenerateJsonSchema.emit_warning] and + [`GenerateJsonSchema.render_warning_message`][pydantic.json_schema.GenerateJsonSchema.render_warning_message] + methods for more details; these can be overridden to control warning behavior. + """ + + +# ##### JSON Schema Generation ##### +DEFAULT_REF_TEMPLATE = '#/$defs/{model}' +"""The default format string used to generate reference names.""" + +# There are three types of references relevant to building JSON schemas: +# 1. core_schema "ref" values; these are not exposed as part of the JSON schema +# * these might look like the fully qualified path of a model, its id, or something similar +CoreRef = NewType('CoreRef', str) +# 2. keys of the "definitions" object that will eventually go into the JSON schema +# * by default, these look like "MyModel", though may change in the presence of collisions +# * eventually, we may want to make it easier to modify the way these names are generated +DefsRef = NewType('DefsRef', str) +# 3. the values corresponding to the "$ref" key in the schema +# * By default, these look like "#/$defs/MyModel", as in {"$ref": "#/$defs/MyModel"} +JsonRef = NewType('JsonRef', str) + +CoreModeRef = Tuple[CoreRef, JsonSchemaMode] +JsonSchemaKeyT = TypeVar('JsonSchemaKeyT', bound=Hashable) + + +@dataclasses.dataclass(**_internal_dataclass.slots_true) +class _DefinitionsRemapping: + defs_remapping: dict[DefsRef, DefsRef] + json_remapping: dict[JsonRef, JsonRef] + + @staticmethod + def from_prioritized_choices( + prioritized_choices: dict[DefsRef, list[DefsRef]], + defs_to_json: dict[DefsRef, JsonRef], + definitions: dict[DefsRef, JsonSchemaValue], + ) -> _DefinitionsRemapping: + """ + This function should produce a remapping that replaces complex DefsRef with the simpler ones from the + prioritized_choices such that applying the name remapping would result in an equivalent JSON schema. + """ + # We need to iteratively simplify the definitions until we reach a fixed point. + # The reason for this is that outer definitions may reference inner definitions that get simplified + # into an equivalent reference, and the outer definitions won't be equivalent until we've simplified + # the inner definitions. + copied_definitions = deepcopy(definitions) + definitions_schema = {'$defs': copied_definitions} + for _iter in range(100): # prevent an infinite loop in the case of a bug, 100 iterations should be enough + # For every possible remapped DefsRef, collect all schemas that that DefsRef might be used for: + schemas_for_alternatives: dict[DefsRef, list[JsonSchemaValue]] = defaultdict(list) + for defs_ref in copied_definitions: + alternatives = prioritized_choices[defs_ref] + for alternative in alternatives: + schemas_for_alternatives[alternative].append(copied_definitions[defs_ref]) + + # Deduplicate the schemas for each alternative; the idea is that we only want to remap to a new DefsRef + # if it introduces no ambiguity, i.e., there is only one distinct schema for that DefsRef. + for defs_ref, schemas in schemas_for_alternatives.items(): + schemas_for_alternatives[defs_ref] = _deduplicate_schemas(schemas_for_alternatives[defs_ref]) + + # Build the remapping + defs_remapping: dict[DefsRef, DefsRef] = {} + json_remapping: dict[JsonRef, JsonRef] = {} + for original_defs_ref in definitions: + alternatives = prioritized_choices[original_defs_ref] + # Pick the first alternative that has only one schema, since that means there is no collision + remapped_defs_ref = next(x for x in alternatives if len(schemas_for_alternatives[x]) == 1) + defs_remapping[original_defs_ref] = remapped_defs_ref + json_remapping[defs_to_json[original_defs_ref]] = defs_to_json[remapped_defs_ref] + remapping = _DefinitionsRemapping(defs_remapping, json_remapping) + new_definitions_schema = remapping.remap_json_schema({'$defs': copied_definitions}) + if definitions_schema == new_definitions_schema: + # We've reached the fixed point + return remapping + definitions_schema = new_definitions_schema + + raise PydanticInvalidForJsonSchema('Failed to simplify the JSON schema definitions') + + def remap_defs_ref(self, ref: DefsRef) -> DefsRef: + return self.defs_remapping.get(ref, ref) + + def remap_json_ref(self, ref: JsonRef) -> JsonRef: + return self.json_remapping.get(ref, ref) + + def remap_json_schema(self, schema: Any) -> Any: + """ + Recursively update the JSON schema replacing all $refs + """ + if isinstance(schema, str): + # Note: this may not really be a JsonRef; we rely on having no collisions between JsonRefs and other strings + return self.remap_json_ref(JsonRef(schema)) + elif isinstance(schema, list): + return [self.remap_json_schema(item) for item in schema] + elif isinstance(schema, dict): + for key, value in schema.items(): + if key == '$ref' and isinstance(value, str): + schema['$ref'] = self.remap_json_ref(JsonRef(value)) + elif key == '$defs': + schema['$defs'] = { + self.remap_defs_ref(DefsRef(key)): self.remap_json_schema(value) + for key, value in schema['$defs'].items() + } + else: + schema[key] = self.remap_json_schema(value) + return schema + + +class GenerateJsonSchema: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/json_schema/#customizing-the-json-schema-generation-process + + A class for generating JSON schemas. + + This class generates JSON schemas based on configured parameters. The default schema dialect + is [https://json-schema.org/draft/2020-12/schema](https://json-schema.org/draft/2020-12/schema). + The class uses `by_alias` to configure how fields with + multiple names are handled and `ref_template` to format reference names. + + Attributes: + schema_dialect: The JSON schema dialect used to generate the schema. See + [Declaring a Dialect](https://json-schema.org/understanding-json-schema/reference/schema.html#id4) + in the JSON Schema documentation for more information about dialects. + ignored_warning_kinds: Warnings to ignore when generating the schema. `self.render_warning_message` will + do nothing if its argument `kind` is in `ignored_warning_kinds`; + this value can be modified on subclasses to easily control which warnings are emitted. + by_alias: Whether to use field aliases when generating the schema. + ref_template: The format string used when generating reference names. + core_to_json_refs: A mapping of core refs to JSON refs. + core_to_defs_refs: A mapping of core refs to definition refs. + defs_to_core_refs: A mapping of definition refs to core refs. + json_to_defs_refs: A mapping of JSON refs to definition refs. + definitions: Definitions in the schema. + + Args: + by_alias: Whether to use field aliases in the generated schemas. + ref_template: The format string to use when generating reference names. + + Raises: + JsonSchemaError: If the instance of the class is inadvertently re-used after generating a schema. + """ + + schema_dialect = 'https://json-schema.org/draft/2020-12/schema' + + # `self.render_warning_message` will do nothing if its argument `kind` is in `ignored_warning_kinds`; + # this value can be modified on subclasses to easily control which warnings are emitted + ignored_warning_kinds: set[JsonSchemaWarningKind] = {'skipped-choice'} + + def __init__(self, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE): + self.by_alias = by_alias + self.ref_template = ref_template + + self.core_to_json_refs: dict[CoreModeRef, JsonRef] = {} + self.core_to_defs_refs: dict[CoreModeRef, DefsRef] = {} + self.defs_to_core_refs: dict[DefsRef, CoreModeRef] = {} + self.json_to_defs_refs: dict[JsonRef, DefsRef] = {} + + self.definitions: dict[DefsRef, JsonSchemaValue] = {} + self._config_wrapper_stack = _config.ConfigWrapperStack(_config.ConfigWrapper({})) + + self._mode: JsonSchemaMode = 'validation' + + # The following includes a mapping of a fully-unique defs ref choice to a list of preferred + # alternatives, which are generally simpler, such as only including the class name. + # At the end of schema generation, we use these to produce a JSON schema with more human-readable + # definitions, which would also work better in a generated OpenAPI client, etc. + self._prioritized_defsref_choices: dict[DefsRef, list[DefsRef]] = {} + self._collision_counter: dict[str, int] = defaultdict(int) + self._collision_index: dict[str, int] = {} + + self._schema_type_to_method = self.build_schema_type_to_method() + + # When we encounter definitions we need to try to build them immediately + # so that they are available schemas that reference them + # But it's possible that CoreSchema was never going to be used + # (e.g. because the CoreSchema that references short circuits is JSON schema generation without needing + # the reference) so instead of failing altogether if we can't build a definition we + # store the error raised and re-throw it if we end up needing that def + self._core_defs_invalid_for_json_schema: dict[DefsRef, PydanticInvalidForJsonSchema] = {} + + # This changes to True after generating a schema, to prevent issues caused by accidental re-use + # of a single instance of a schema generator + self._used = False + + @property + def _config(self) -> _config.ConfigWrapper: + return self._config_wrapper_stack.tail + + @property + def mode(self) -> JsonSchemaMode: + if self._config.json_schema_mode_override is not None: + return self._config.json_schema_mode_override + else: + return self._mode + + def build_schema_type_to_method( + self, + ) -> dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]]: + """Builds a dictionary mapping fields to methods for generating JSON schemas. + + Returns: + A dictionary containing the mapping of `CoreSchemaOrFieldType` to a handler method. + + Raises: + TypeError: If no method has been defined for generating a JSON schema for a given pydantic core schema type. + """ + mapping: dict[CoreSchemaOrFieldType, Callable[[CoreSchemaOrField], JsonSchemaValue]] = {} + core_schema_types: list[CoreSchemaOrFieldType] = _typing_extra.all_literal_values( + CoreSchemaOrFieldType # type: ignore + ) + for key in core_schema_types: + method_name = f"{key.replace('-', '_')}_schema" + try: + mapping[key] = getattr(self, method_name) + except AttributeError as e: # pragma: no cover + raise TypeError( + f'No method for generating JsonSchema for core_schema.type={key!r} ' + f'(expected: {type(self).__name__}.{method_name})' + ) from e + return mapping + + def generate_definitions( + self, inputs: Sequence[tuple[JsonSchemaKeyT, JsonSchemaMode, core_schema.CoreSchema]] + ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], dict[DefsRef, JsonSchemaValue]]: + """Generates JSON schema definitions from a list of core schemas, pairing the generated definitions with a + mapping that links the input keys to the definition references. + + Args: + inputs: A sequence of tuples, where: + + - The first element is a JSON schema key type. + - The second element is the JSON mode: either 'validation' or 'serialization'. + - The third element is a core schema. + + Returns: + A tuple where: + + - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and + whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have + JsonRef references to definitions that are defined in the second returned element.) + - The second element is a dictionary whose keys are definition references for the JSON schemas + from the first returned element, and whose values are the actual JSON schema definitions. + + Raises: + PydanticUserError: Raised if the JSON schema generator has already been used to generate a JSON schema. + """ + if self._used: + raise PydanticUserError( + 'This JSON schema generator has already been used to generate a JSON schema. ' + f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.', + code='json-schema-already-used', + ) + + for key, mode, schema in inputs: + self._mode = mode + self.generate_inner(schema) + + definitions_remapping = self._build_definitions_remapping() + + json_schemas_map: dict[tuple[JsonSchemaKeyT, JsonSchemaMode], DefsRef] = {} + for key, mode, schema in inputs: + self._mode = mode + json_schema = self.generate_inner(schema) + json_schemas_map[(key, mode)] = definitions_remapping.remap_json_schema(json_schema) + + json_schema = {'$defs': self.definitions} + json_schema = definitions_remapping.remap_json_schema(json_schema) + self._used = True + return json_schemas_map, _sort_json_schema(json_schema['$defs']) # type: ignore + + def generate(self, schema: CoreSchema, mode: JsonSchemaMode = 'validation') -> JsonSchemaValue: + """Generates a JSON schema for a specified schema in a specified mode. + + Args: + schema: A Pydantic model. + mode: The mode in which to generate the schema. Defaults to 'validation'. + + Returns: + A JSON schema representing the specified schema. + + Raises: + PydanticUserError: If the JSON schema generator has already been used to generate a JSON schema. + """ + self._mode = mode + if self._used: + raise PydanticUserError( + 'This JSON schema generator has already been used to generate a JSON schema. ' + f'You must create a new instance of {type(self).__name__} to generate a new JSON schema.', + code='json-schema-already-used', + ) + + json_schema: JsonSchemaValue = self.generate_inner(schema) + json_ref_counts = self.get_json_ref_counts(json_schema) + + # Remove the top-level $ref if present; note that the _generate method already ensures there are no sibling keys + ref = cast(JsonRef, json_schema.get('$ref')) + while ref is not None: # may need to unpack multiple levels + ref_json_schema = self.get_schema_from_definitions(ref) + if json_ref_counts[ref] > 1 or ref_json_schema is None: + # Keep the ref, but use an allOf to remove the top level $ref + json_schema = {'allOf': [{'$ref': ref}]} + else: + # "Unpack" the ref since this is the only reference + json_schema = ref_json_schema.copy() # copy to prevent recursive dict reference + json_ref_counts[ref] -= 1 + ref = cast(JsonRef, json_schema.get('$ref')) + + self._garbage_collect_definitions(json_schema) + definitions_remapping = self._build_definitions_remapping() + + if self.definitions: + json_schema['$defs'] = self.definitions + + json_schema = definitions_remapping.remap_json_schema(json_schema) + + # For now, we will not set the $schema key. However, if desired, this can be easily added by overriding + # this method and adding the following line after a call to super().generate(schema): + # json_schema['$schema'] = self.schema_dialect + + self._used = True + return _sort_json_schema(json_schema) + + def generate_inner(self, schema: CoreSchemaOrField) -> JsonSchemaValue: # noqa: C901 + """Generates a JSON schema for a given core schema. + + Args: + schema: The given core schema. + + Returns: + The generated JSON schema. + """ + # If a schema with the same CoreRef has been handled, just return a reference to it + # Note that this assumes that it will _never_ be the case that the same CoreRef is used + # on types that should have different JSON schemas + if 'ref' in schema: + core_ref = CoreRef(schema['ref']) # type: ignore[typeddict-item] + core_mode_ref = (core_ref, self.mode) + if core_mode_ref in self.core_to_defs_refs and self.core_to_defs_refs[core_mode_ref] in self.definitions: + return {'$ref': self.core_to_json_refs[core_mode_ref]} + + # Generate the JSON schema, accounting for the json_schema_override and core_schema_override + metadata_handler = _core_metadata.CoreMetadataHandler(schema) + + def populate_defs(core_schema: CoreSchema, json_schema: JsonSchemaValue) -> JsonSchemaValue: + if 'ref' in core_schema: + core_ref = CoreRef(core_schema['ref']) # type: ignore[typeddict-item] + defs_ref, ref_json_schema = self.get_cache_defs_ref_schema(core_ref) + json_ref = JsonRef(ref_json_schema['$ref']) + self.json_to_defs_refs[json_ref] = defs_ref + # Replace the schema if it's not a reference to itself + # What we want to avoid is having the def be just a ref to itself + # which is what would happen if we blindly assigned any + if json_schema.get('$ref', None) != json_ref: + self.definitions[defs_ref] = json_schema + self._core_defs_invalid_for_json_schema.pop(defs_ref, None) + json_schema = ref_json_schema + return json_schema + + def convert_to_all_of(json_schema: JsonSchemaValue) -> JsonSchemaValue: + if '$ref' in json_schema and len(json_schema.keys()) > 1: + # technically you can't have any other keys next to a "$ref" + # but it's an easy mistake to make and not hard to correct automatically here + json_schema = json_schema.copy() + ref = json_schema.pop('$ref') + json_schema = {'allOf': [{'$ref': ref}], **json_schema} + return json_schema + + def handler_func(schema_or_field: CoreSchemaOrField) -> JsonSchemaValue: + """Generate a JSON schema based on the input schema. + + Args: + schema_or_field: The core schema to generate a JSON schema from. + + Returns: + The generated JSON schema. + + Raises: + TypeError: If an unexpected schema type is encountered. + """ + # Generate the core-schema-type-specific bits of the schema generation: + json_schema: JsonSchemaValue | None = None + if self.mode == 'serialization' and 'serialization' in schema_or_field: + ser_schema = schema_or_field['serialization'] # type: ignore + json_schema = self.ser_schema(ser_schema) + if json_schema is None: + if _core_utils.is_core_schema(schema_or_field) or _core_utils.is_core_schema_field(schema_or_field): + generate_for_schema_type = self._schema_type_to_method[schema_or_field['type']] + json_schema = generate_for_schema_type(schema_or_field) + else: + raise TypeError(f'Unexpected schema type: schema={schema_or_field}') + if _core_utils.is_core_schema(schema_or_field): + json_schema = populate_defs(schema_or_field, json_schema) + json_schema = convert_to_all_of(json_schema) + return json_schema + + current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, handler_func) + + for js_modify_function in metadata_handler.metadata.get('pydantic_js_functions', ()): + + def new_handler_func( + schema_or_field: CoreSchemaOrField, + current_handler: GetJsonSchemaHandler = current_handler, + js_modify_function: GetJsonSchemaFunction = js_modify_function, + ) -> JsonSchemaValue: + json_schema = js_modify_function(schema_or_field, current_handler) + if _core_utils.is_core_schema(schema_or_field): + json_schema = populate_defs(schema_or_field, json_schema) + original_schema = current_handler.resolve_ref_schema(json_schema) + ref = json_schema.pop('$ref', None) + if ref and json_schema: + original_schema.update(json_schema) + return original_schema + + current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func) + + for js_modify_function in metadata_handler.metadata.get('pydantic_js_annotation_functions', ()): + + def new_handler_func( + schema_or_field: CoreSchemaOrField, + current_handler: GetJsonSchemaHandler = current_handler, + js_modify_function: GetJsonSchemaFunction = js_modify_function, + ) -> JsonSchemaValue: + json_schema = js_modify_function(schema_or_field, current_handler) + if _core_utils.is_core_schema(schema_or_field): + json_schema = populate_defs(schema_or_field, json_schema) + json_schema = convert_to_all_of(json_schema) + return json_schema + + current_handler = _schema_generation_shared.GenerateJsonSchemaHandler(self, new_handler_func) + + json_schema = current_handler(schema) + if _core_utils.is_core_schema(schema): + json_schema = populate_defs(schema, json_schema) + json_schema = convert_to_all_of(json_schema) + return json_schema + + # ### Schema generation methods + def any_schema(self, schema: core_schema.AnySchema) -> JsonSchemaValue: + """Generates a JSON schema that matches any value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return {} + + def none_schema(self, schema: core_schema.NoneSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches `None`. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return {'type': 'null'} + + def bool_schema(self, schema: core_schema.BoolSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a bool value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return {'type': 'boolean'} + + def int_schema(self, schema: core_schema.IntSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches an int value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema: dict[str, Any] = {'type': 'integer'} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric) + json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}} + return json_schema + + def float_schema(self, schema: core_schema.FloatSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a float value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema: dict[str, Any] = {'type': 'number'} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.numeric) + json_schema = {k: v for k, v in json_schema.items() if v not in {math.inf, -math.inf}} + return json_schema + + def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a decimal value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema = self.str_schema(core_schema.str_schema()) + if self.mode == 'validation': + multiple_of = schema.get('multiple_of') + le = schema.get('le') + ge = schema.get('ge') + lt = schema.get('lt') + gt = schema.get('gt') + json_schema = { + 'anyOf': [ + self.float_schema( + core_schema.float_schema( + allow_inf_nan=schema.get('allow_inf_nan'), + multiple_of=None if multiple_of is None else float(multiple_of), + le=None if le is None else float(le), + ge=None if ge is None else float(ge), + lt=None if lt is None else float(lt), + gt=None if gt is None else float(gt), + ) + ), + json_schema, + ], + } + return json_schema + + def str_schema(self, schema: core_schema.StringSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a string value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema = {'type': 'string'} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.string) + if isinstance(json_schema.get('pattern'), Pattern): + # TODO: should we add regex flags to the pattern? + json_schema['pattern'] = json_schema.get('pattern').pattern # type: ignore + return json_schema + + def bytes_schema(self, schema: core_schema.BytesSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a bytes value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema = {'type': 'string', 'format': 'base64url' if self._config.ser_json_bytes == 'base64' else 'binary'} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.bytes) + return json_schema + + def date_schema(self, schema: core_schema.DateSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a date value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema = {'type': 'string', 'format': 'date'} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.date) + return json_schema + + def time_schema(self, schema: core_schema.TimeSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a time value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return {'type': 'string', 'format': 'time'} + + def datetime_schema(self, schema: core_schema.DatetimeSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a datetime value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return {'type': 'string', 'format': 'date-time'} + + def timedelta_schema(self, schema: core_schema.TimedeltaSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a timedelta value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + if self._config.ser_json_timedelta == 'float': + return {'type': 'number'} + return {'type': 'string', 'format': 'duration'} + + def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a literal value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + expected = [v.value if isinstance(v, Enum) else v for v in schema['expected']] + # jsonify the expected values + expected = [to_jsonable_python(v) for v in expected] + + result: dict[str, Any] = {'enum': expected} + if len(expected) == 1: + result['const'] = expected[0] + + types = {type(e) for e in expected} + if types == {str}: + result['type'] = 'string' + elif types == {int}: + result['type'] = 'integer' + elif types == {float}: + result['type'] = 'numeric' + elif types == {bool}: + result['type'] = 'boolean' + elif types == {list}: + result['type'] = 'array' + elif types == {type(None)}: + result['type'] = 'null' + return result + + def enum_schema(self, schema: core_schema.EnumSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches an Enum value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + enum_type = schema['cls'] + description = None if not enum_type.__doc__ else inspect.cleandoc(enum_type.__doc__) + if ( + description == 'An enumeration.' + ): # This is the default value provided by enum.EnumMeta.__new__; don't use it + description = None + result: dict[str, Any] = {'title': enum_type.__name__, 'description': description} + result = {k: v for k, v in result.items() if v is not None} + + expected = [to_jsonable_python(v.value) for v in schema['members']] + + result['enum'] = expected + if len(expected) == 1: + result['const'] = expected[0] + + types = {type(e) for e in expected} + if isinstance(enum_type, str) or types == {str}: + result['type'] = 'string' + elif isinstance(enum_type, int) or types == {int}: + result['type'] = 'integer' + elif isinstance(enum_type, float) or types == {float}: + result['type'] = 'numeric' + elif types == {bool}: + result['type'] = 'boolean' + elif types == {list}: + result['type'] = 'array' + + return result + + def is_instance_schema(self, schema: core_schema.IsInstanceSchema) -> JsonSchemaValue: + """Handles JSON schema generation for a core schema that checks if a value is an instance of a class. + + Unless overridden in a subclass, this raises an error. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.handle_invalid_for_json_schema(schema, f'core_schema.IsInstanceSchema ({schema["cls"]})') + + def is_subclass_schema(self, schema: core_schema.IsSubclassSchema) -> JsonSchemaValue: + """Handles JSON schema generation for a core schema that checks if a value is a subclass of a class. + + For backwards compatibility with v1, this does not raise an error, but can be overridden to change this. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + # Note: This is for compatibility with V1; you can override if you want different behavior. + return {} + + def callable_schema(self, schema: core_schema.CallableSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a callable value. + + Unless overridden in a subclass, this raises an error. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.handle_invalid_for_json_schema(schema, 'core_schema.CallableSchema') + + def list_schema(self, schema: core_schema.ListSchema) -> JsonSchemaValue: + """Returns a schema that matches a list schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema']) + json_schema = {'type': 'array', 'items': items_schema} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) + return json_schema + + @deprecated('`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.', category=None) + @final + def tuple_positional_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue: + """Replaced by `tuple_schema`.""" + warnings.warn( + '`tuple_positional_schema` is deprecated. Use `tuple_schema` instead.', + PydanticDeprecatedSince26, + stacklevel=2, + ) + return self.tuple_schema(schema) + + @deprecated('`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.', category=None) + @final + def tuple_variable_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue: + """Replaced by `tuple_schema`.""" + warnings.warn( + '`tuple_variable_schema` is deprecated. Use `tuple_schema` instead.', + PydanticDeprecatedSince26, + stacklevel=2, + ) + return self.tuple_schema(schema) + + def tuple_schema(self, schema: core_schema.TupleSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a tuple schema e.g. `Tuple[int, + str, bool]` or `Tuple[int, ...]`. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema: JsonSchemaValue = {'type': 'array'} + if 'variadic_item_index' in schema: + variadic_item_index = schema['variadic_item_index'] + if variadic_item_index > 0: + json_schema['minItems'] = variadic_item_index + json_schema['prefixItems'] = [ + self.generate_inner(item) for item in schema['items_schema'][:variadic_item_index] + ] + if variadic_item_index + 1 == len(schema['items_schema']): + # if the variadic item is the last item, then represent it faithfully + json_schema['items'] = self.generate_inner(schema['items_schema'][variadic_item_index]) + else: + # otherwise, 'items' represents the schema for the variadic + # item plus the suffix, so just allow anything for simplicity + # for now + json_schema['items'] = True + else: + prefixItems = [self.generate_inner(item) for item in schema['items_schema']] + if prefixItems: + json_schema['prefixItems'] = prefixItems + json_schema['minItems'] = len(prefixItems) + json_schema['maxItems'] = len(prefixItems) + self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) + return json_schema + + def set_schema(self, schema: core_schema.SetSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a set schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self._common_set_schema(schema) + + def frozenset_schema(self, schema: core_schema.FrozenSetSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a frozenset schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self._common_set_schema(schema) + + def _common_set_schema(self, schema: core_schema.SetSchema | core_schema.FrozenSetSchema) -> JsonSchemaValue: + items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema']) + json_schema = {'type': 'array', 'uniqueItems': True, 'items': items_schema} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) + return json_schema + + def generator_schema(self, schema: core_schema.GeneratorSchema) -> JsonSchemaValue: + """Returns a JSON schema that represents the provided GeneratorSchema. + + Args: + schema: The schema. + + Returns: + The generated JSON schema. + """ + items_schema = {} if 'items_schema' not in schema else self.generate_inner(schema['items_schema']) + json_schema = {'type': 'array', 'items': items_schema} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.array) + return json_schema + + def dict_schema(self, schema: core_schema.DictSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a dict schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema: JsonSchemaValue = {'type': 'object'} + + keys_schema = self.generate_inner(schema['keys_schema']).copy() if 'keys_schema' in schema else {} + keys_pattern = keys_schema.pop('pattern', None) + + values_schema = self.generate_inner(schema['values_schema']).copy() if 'values_schema' in schema else {} + values_schema.pop('title', None) # don't give a title to the additionalProperties + if values_schema or keys_pattern is not None: # don't add additionalProperties if it's empty + if keys_pattern is None: + json_schema['additionalProperties'] = values_schema + else: + json_schema['patternProperties'] = {keys_pattern: values_schema} + + self.update_with_validations(json_schema, schema, self.ValidationsMapping.object) + return json_schema + + def _function_schema( + self, + schema: _core_utils.AnyFunctionSchema, + ) -> JsonSchemaValue: + if _core_utils.is_function_with_inner_schema(schema): + # This could be wrong if the function's mode is 'before', but in practice will often be right, and when it + # isn't, I think it would be hard to automatically infer what the desired schema should be. + return self.generate_inner(schema['schema']) + + # function-plain + return self.handle_invalid_for_json_schema( + schema, f'core_schema.PlainValidatorFunctionSchema ({schema["function"]})' + ) + + def function_before_schema(self, schema: core_schema.BeforeValidatorFunctionSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a function-before schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self._function_schema(schema) + + def function_after_schema(self, schema: core_schema.AfterValidatorFunctionSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a function-after schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self._function_schema(schema) + + def function_plain_schema(self, schema: core_schema.PlainValidatorFunctionSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a function-plain schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self._function_schema(schema) + + def function_wrap_schema(self, schema: core_schema.WrapValidatorFunctionSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a function-wrap schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self._function_schema(schema) + + def default_schema(self, schema: core_schema.WithDefaultSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema with a default value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema = self.generate_inner(schema['schema']) + + if 'default' not in schema: + return json_schema + default = schema['default'] + # Note: if you want to include the value returned by the default_factory, + # override this method and replace the code above with: + # if 'default' in schema: + # default = schema['default'] + # elif 'default_factory' in schema: + # default = schema['default_factory']() + # else: + # return json_schema + + # we reflect the application of custom plain, no-info serializers to defaults for + # json schemas viewed in serialization mode + # TODO: improvements along with https://github.com/pydantic/pydantic/issues/8208 + # TODO: improve type safety here + if self.mode == 'serialization': + if ( + (ser_schema := schema['schema'].get('serialization', {})) + and (ser_func := ser_schema.get('function')) + and ser_schema.get('type') == 'function-plain' # type: ignore + and ser_schema.get('info_arg') is False # type: ignore + ): + default = ser_func(default) # type: ignore + + try: + encoded_default = self.encode_default(default) + except pydantic_core.PydanticSerializationError: + self.emit_warning( + 'non-serializable-default', + f'Default value {default} is not JSON serializable; excluding default from JSON schema', + ) + # Return the inner schema, as though there was no default + return json_schema + + if '$ref' in json_schema: + # Since reference schemas do not support child keys, we wrap the reference schema in a single-case allOf: + return {'allOf': [json_schema], 'default': encoded_default} + else: + json_schema['default'] = encoded_default + return json_schema + + def nullable_schema(self, schema: core_schema.NullableSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that allows null values. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + null_schema = {'type': 'null'} + inner_json_schema = self.generate_inner(schema['schema']) + + if inner_json_schema == null_schema: + return null_schema + else: + # Thanks to the equality check against `null_schema` above, I think 'oneOf' would also be valid here; + # I'll use 'anyOf' for now, but it could be changed it if it would work better with some external tooling + return self.get_flattened_anyof([inner_json_schema, null_schema]) + + def union_schema(self, schema: core_schema.UnionSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that allows values matching any of the given schemas. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + generated: list[JsonSchemaValue] = [] + + choices = schema['choices'] + for choice in choices: + # choice will be a tuple if an explicit label was provided + choice_schema = choice[0] if isinstance(choice, tuple) else choice + try: + generated.append(self.generate_inner(choice_schema)) + except PydanticOmit: + continue + except PydanticInvalidForJsonSchema as exc: + self.emit_warning('skipped-choice', exc.message) + if len(generated) == 1: + return generated[0] + return self.get_flattened_anyof(generated) + + def tagged_union_schema(self, schema: core_schema.TaggedUnionSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that allows values matching any of the given schemas, where + the schemas are tagged with a discriminator field that indicates which schema should be used to validate + the value. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + generated: dict[str, JsonSchemaValue] = {} + for k, v in schema['choices'].items(): + if isinstance(k, Enum): + k = k.value + try: + # Use str(k) since keys must be strings for json; while not technically correct, + # it's the closest that can be represented in valid JSON + generated[str(k)] = self.generate_inner(v).copy() + except PydanticOmit: + continue + except PydanticInvalidForJsonSchema as exc: + self.emit_warning('skipped-choice', exc.message) + + one_of_choices = _deduplicate_schemas(generated.values()) + json_schema: JsonSchemaValue = {'oneOf': one_of_choices} + + # This reflects the v1 behavior; TODO: we should make it possible to exclude OpenAPI stuff from the JSON schema + openapi_discriminator = self._extract_discriminator(schema, one_of_choices) + if openapi_discriminator is not None: + json_schema['discriminator'] = { + 'propertyName': openapi_discriminator, + 'mapping': {k: v.get('$ref', v) for k, v in generated.items()}, + } + + return json_schema + + def _extract_discriminator( + self, schema: core_schema.TaggedUnionSchema, one_of_choices: list[JsonDict] + ) -> str | None: + """Extract a compatible OpenAPI discriminator from the schema and one_of choices that end up in the final + schema.""" + openapi_discriminator: str | None = None + + if isinstance(schema['discriminator'], str): + return schema['discriminator'] + + if isinstance(schema['discriminator'], list): + # If the discriminator is a single item list containing a string, that is equivalent to the string case + if len(schema['discriminator']) == 1 and isinstance(schema['discriminator'][0], str): + return schema['discriminator'][0] + # When an alias is used that is different from the field name, the discriminator will be a list of single + # str lists, one for the attribute and one for the actual alias. The logic here will work even if there is + # more than one possible attribute, and looks for whether a single alias choice is present as a documented + # property on all choices. If so, that property will be used as the OpenAPI discriminator. + for alias_path in schema['discriminator']: + if not isinstance(alias_path, list): + break # this means that the discriminator is not a list of alias paths + if len(alias_path) != 1: + continue # this means that the "alias" does not represent a single field + alias = alias_path[0] + if not isinstance(alias, str): + continue # this means that the "alias" does not represent a field + alias_is_present_on_all_choices = True + for choice in one_of_choices: + while '$ref' in choice: + assert isinstance(choice['$ref'], str) + choice = self.get_schema_from_definitions(JsonRef(choice['$ref'])) or {} + properties = choice.get('properties', {}) + if not isinstance(properties, dict) or alias not in properties: + alias_is_present_on_all_choices = False + break + if alias_is_present_on_all_choices: + openapi_discriminator = alias + break + return openapi_discriminator + + def chain_schema(self, schema: core_schema.ChainSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a core_schema.ChainSchema. + + When generating a schema for validation, we return the validation JSON schema for the first step in the chain. + For serialization, we return the serialization JSON schema for the last step in the chain. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + step_index = 0 if self.mode == 'validation' else -1 # use first step for validation, last for serialization + return self.generate_inner(schema['steps'][step_index]) + + def lax_or_strict_schema(self, schema: core_schema.LaxOrStrictSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that allows values matching either the lax schema or the + strict schema. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + # TODO: Need to read the default value off of model config or whatever + use_strict = schema.get('strict', False) # TODO: replace this default False + # If your JSON schema fails to generate it is probably + # because one of the following two branches failed. + if use_strict: + return self.generate_inner(schema['strict_schema']) + else: + return self.generate_inner(schema['lax_schema']) + + def json_or_python_schema(self, schema: core_schema.JsonOrPythonSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that allows values matching either the JSON schema or the + Python schema. + + The JSON schema is used instead of the Python schema. If you want to use the Python schema, you should override + this method. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.generate_inner(schema['json_schema']) + + def typed_dict_schema(self, schema: core_schema.TypedDictSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a typed dict. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + total = schema.get('total', True) + named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [ + (name, self.field_is_required(field, total), field) + for name, field in schema['fields'].items() + if self.field_is_present(field) + ] + if self.mode == 'serialization': + named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', []))) + cls = _get_typed_dict_cls(schema) + config = _get_typed_dict_config(cls) + with self._config_wrapper_stack.push(config): + json_schema = self._named_required_fields_schema(named_required_fields) + + json_schema_extra = config.get('json_schema_extra') + extra = schema.get('extra_behavior') + if extra is None: + extra = config.get('extra', 'ignore') + + if cls is not None: + title = config.get('title') or cls.__name__ + json_schema = self._update_class_schema(json_schema, title, extra, cls, json_schema_extra) + else: + if extra == 'forbid': + json_schema['additionalProperties'] = False + elif extra == 'allow': + json_schema['additionalProperties'] = True + + return json_schema + + @staticmethod + def _name_required_computed_fields( + computed_fields: list[ComputedField], + ) -> list[tuple[str, bool, core_schema.ComputedField]]: + return [(field['property_name'], True, field) for field in computed_fields] + + def _named_required_fields_schema( + self, named_required_fields: Sequence[tuple[str, bool, CoreSchemaField]] + ) -> JsonSchemaValue: + properties: dict[str, JsonSchemaValue] = {} + required_fields: list[str] = [] + for name, required, field in named_required_fields: + if self.by_alias: + name = self._get_alias_name(field, name) + try: + field_json_schema = self.generate_inner(field).copy() + except PydanticOmit: + continue + if 'title' not in field_json_schema and self.field_title_should_be_set(field): + title = self.get_title_from_name(name) + field_json_schema['title'] = title + field_json_schema = self.handle_ref_overrides(field_json_schema) + properties[name] = field_json_schema + if required: + required_fields.append(name) + + json_schema = {'type': 'object', 'properties': properties} + if required_fields: + json_schema['required'] = required_fields + return json_schema + + def _get_alias_name(self, field: CoreSchemaField, name: str) -> str: + if field['type'] == 'computed-field': + alias: Any = field.get('alias', name) + elif self.mode == 'validation': + alias = field.get('validation_alias', name) + else: + alias = field.get('serialization_alias', name) + if isinstance(alias, str): + name = alias + elif isinstance(alias, list): + alias = cast('list[str] | str', alias) + for path in alias: + if isinstance(path, list) and len(path) == 1 and isinstance(path[0], str): + # Use the first valid single-item string path; the code that constructs the alias array + # should ensure the first such item is what belongs in the JSON schema + name = path[0] + break + else: + assert_never(alias) + return name + + def typed_dict_field_schema(self, schema: core_schema.TypedDictField) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a typed dict field. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.generate_inner(schema['schema']) + + def dataclass_field_schema(self, schema: core_schema.DataclassField) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a dataclass field. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.generate_inner(schema['schema']) + + def model_field_schema(self, schema: core_schema.ModelField) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a model field. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.generate_inner(schema['schema']) + + def computed_field_schema(self, schema: core_schema.ComputedField) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a computed field. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.generate_inner(schema['return_schema']) + + def model_schema(self, schema: core_schema.ModelSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a model. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + # We do not use schema['model'].model_json_schema() here + # because it could lead to inconsistent refs handling, etc. + cls = cast('type[BaseModel]', schema['cls']) + config = cls.model_config + title = config.get('title') + + with self._config_wrapper_stack.push(config): + json_schema = self.generate_inner(schema['schema']) + + json_schema_extra = config.get('json_schema_extra') + if cls.__pydantic_root_model__: + root_json_schema_extra = cls.model_fields['root'].json_schema_extra + if json_schema_extra and root_json_schema_extra: + raise ValueError( + '"model_config[\'json_schema_extra\']" and "Field.json_schema_extra" on "RootModel.root"' + ' field must not be set simultaneously' + ) + if root_json_schema_extra: + json_schema_extra = root_json_schema_extra + + json_schema = self._update_class_schema(json_schema, title, config.get('extra', None), cls, json_schema_extra) + + return json_schema + + def _update_class_schema( + self, + json_schema: JsonSchemaValue, + title: str | None, + extra: Literal['allow', 'ignore', 'forbid'] | None, + cls: type[Any], + json_schema_extra: JsonDict | JsonSchemaExtraCallable | None, + ) -> JsonSchemaValue: + if '$ref' in json_schema: + schema_to_update = self.get_schema_from_definitions(JsonRef(json_schema['$ref'])) or json_schema + else: + schema_to_update = json_schema + + if title is not None: + # referenced_schema['title'] = title + schema_to_update.setdefault('title', title) + + if 'additionalProperties' not in schema_to_update: + if extra == 'allow': + schema_to_update['additionalProperties'] = True + elif extra == 'forbid': + schema_to_update['additionalProperties'] = False + + if isinstance(json_schema_extra, (staticmethod, classmethod)): + # In older versions of python, this is necessary to ensure staticmethod/classmethods are callable + json_schema_extra = json_schema_extra.__get__(cls) + + if isinstance(json_schema_extra, dict): + schema_to_update.update(json_schema_extra) + elif callable(json_schema_extra): + if len(inspect.signature(json_schema_extra).parameters) > 1: + json_schema_extra(schema_to_update, cls) # type: ignore + else: + json_schema_extra(schema_to_update) # type: ignore + elif json_schema_extra is not None: + raise ValueError( + f"model_config['json_schema_extra']={json_schema_extra} should be a dict, callable, or None" + ) + + if hasattr(cls, '__deprecated__'): + json_schema['deprecated'] = True + + return json_schema + + def resolve_schema_to_update(self, json_schema: JsonSchemaValue) -> JsonSchemaValue: + """Resolve a JsonSchemaValue to the non-ref schema if it is a $ref schema. + + Args: + json_schema: The schema to resolve. + + Returns: + The resolved schema. + """ + if '$ref' in json_schema: + schema_to_update = self.get_schema_from_definitions(JsonRef(json_schema['$ref'])) + if schema_to_update is None: + raise RuntimeError(f'Cannot update undefined schema for $ref={json_schema["$ref"]}') + return self.resolve_schema_to_update(schema_to_update) + else: + schema_to_update = json_schema + return schema_to_update + + def model_fields_schema(self, schema: core_schema.ModelFieldsSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a model's fields. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [ + (name, self.field_is_required(field, total=True), field) + for name, field in schema['fields'].items() + if self.field_is_present(field) + ] + if self.mode == 'serialization': + named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', []))) + json_schema = self._named_required_fields_schema(named_required_fields) + extras_schema = schema.get('extras_schema', None) + if extras_schema is not None: + schema_to_update = self.resolve_schema_to_update(json_schema) + schema_to_update['additionalProperties'] = self.generate_inner(extras_schema) + return json_schema + + def field_is_present(self, field: CoreSchemaField) -> bool: + """Whether the field should be included in the generated JSON schema. + + Args: + field: The schema for the field itself. + + Returns: + `True` if the field should be included in the generated JSON schema, `False` otherwise. + """ + if self.mode == 'serialization': + # If you still want to include the field in the generated JSON schema, + # override this method and return True + return not field.get('serialization_exclude') + elif self.mode == 'validation': + return True + else: + assert_never(self.mode) + + def field_is_required( + self, + field: core_schema.ModelField | core_schema.DataclassField | core_schema.TypedDictField, + total: bool, + ) -> bool: + """Whether the field should be marked as required in the generated JSON schema. + (Note that this is irrelevant if the field is not present in the JSON schema.). + + Args: + field: The schema for the field itself. + total: Only applies to `TypedDictField`s. + Indicates if the `TypedDict` this field belongs to is total, in which case any fields that don't + explicitly specify `required=False` are required. + + Returns: + `True` if the field should be marked as required in the generated JSON schema, `False` otherwise. + """ + if self.mode == 'serialization' and self._config.json_schema_serialization_defaults_required: + return not field.get('serialization_exclude') + else: + if field['type'] == 'typed-dict-field': + return field.get('required', total) + else: + return field['schema']['type'] != 'default' + + def dataclass_args_schema(self, schema: core_schema.DataclassArgsSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a dataclass's constructor arguments. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + named_required_fields: list[tuple[str, bool, CoreSchemaField]] = [ + (field['name'], self.field_is_required(field, total=True), field) + for field in schema['fields'] + if self.field_is_present(field) + ] + if self.mode == 'serialization': + named_required_fields.extend(self._name_required_computed_fields(schema.get('computed_fields', []))) + return self._named_required_fields_schema(named_required_fields) + + def dataclass_schema(self, schema: core_schema.DataclassSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a dataclass. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + cls = schema['cls'] + config: ConfigDict = getattr(cls, '__pydantic_config__', cast('ConfigDict', {})) + title = config.get('title') or cls.__name__ + + with self._config_wrapper_stack.push(config): + json_schema = self.generate_inner(schema['schema']).copy() + + json_schema_extra = config.get('json_schema_extra') + json_schema = self._update_class_schema(json_schema, title, config.get('extra', None), cls, json_schema_extra) + + # Dataclass-specific handling of description + if is_dataclass(cls) and not hasattr(cls, '__pydantic_validator__'): + # vanilla dataclass; don't use cls.__doc__ as it will contain the class signature by default + description = None + else: + description = None if cls.__doc__ is None else inspect.cleandoc(cls.__doc__) + if description: + json_schema['description'] = description + + return json_schema + + def arguments_schema(self, schema: core_schema.ArgumentsSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a function's arguments. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + metadata = _core_metadata.CoreMetadataHandler(schema).metadata + prefer_positional = metadata.get('pydantic_js_prefer_positional_arguments') + + arguments = schema['arguments_schema'] + kw_only_arguments = [a for a in arguments if a.get('mode') == 'keyword_only'] + kw_or_p_arguments = [a for a in arguments if a.get('mode') in {'positional_or_keyword', None}] + p_only_arguments = [a for a in arguments if a.get('mode') == 'positional_only'] + var_args_schema = schema.get('var_args_schema') + var_kwargs_schema = schema.get('var_kwargs_schema') + + if prefer_positional: + positional_possible = not kw_only_arguments and not var_kwargs_schema + if positional_possible: + return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema) + + keyword_possible = not p_only_arguments and not var_args_schema + if keyword_possible: + return self.kw_arguments_schema(kw_or_p_arguments + kw_only_arguments, var_kwargs_schema) + + if not prefer_positional: + positional_possible = not kw_only_arguments and not var_kwargs_schema + if positional_possible: + return self.p_arguments_schema(p_only_arguments + kw_or_p_arguments, var_args_schema) + + raise PydanticInvalidForJsonSchema( + 'Unable to generate JSON schema for arguments validator with positional-only and keyword-only arguments' + ) + + def kw_arguments_schema( + self, arguments: list[core_schema.ArgumentsParameter], var_kwargs_schema: CoreSchema | None + ) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a function's keyword arguments. + + Args: + arguments: The core schema. + + Returns: + The generated JSON schema. + """ + properties: dict[str, JsonSchemaValue] = {} + required: list[str] = [] + for argument in arguments: + name = self.get_argument_name(argument) + argument_schema = self.generate_inner(argument['schema']).copy() + argument_schema['title'] = self.get_title_from_name(name) + properties[name] = argument_schema + + if argument['schema']['type'] != 'default': + # This assumes that if the argument has a default value, + # the inner schema must be of type WithDefaultSchema. + # I believe this is true, but I am not 100% sure + required.append(name) + + json_schema: JsonSchemaValue = {'type': 'object', 'properties': properties} + if required: + json_schema['required'] = required + + if var_kwargs_schema: + additional_properties_schema = self.generate_inner(var_kwargs_schema) + if additional_properties_schema: + json_schema['additionalProperties'] = additional_properties_schema + else: + json_schema['additionalProperties'] = False + return json_schema + + def p_arguments_schema( + self, arguments: list[core_schema.ArgumentsParameter], var_args_schema: CoreSchema | None + ) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a function's positional arguments. + + Args: + arguments: The core schema. + + Returns: + The generated JSON schema. + """ + prefix_items: list[JsonSchemaValue] = [] + min_items = 0 + + for argument in arguments: + name = self.get_argument_name(argument) + + argument_schema = self.generate_inner(argument['schema']).copy() + argument_schema['title'] = self.get_title_from_name(name) + prefix_items.append(argument_schema) + + if argument['schema']['type'] != 'default': + # This assumes that if the argument has a default value, + # the inner schema must be of type WithDefaultSchema. + # I believe this is true, but I am not 100% sure + min_items += 1 + + json_schema: JsonSchemaValue = {'type': 'array', 'prefixItems': prefix_items} + if min_items: + json_schema['minItems'] = min_items + + if var_args_schema: + items_schema = self.generate_inner(var_args_schema) + if items_schema: + json_schema['items'] = items_schema + else: + json_schema['maxItems'] = len(prefix_items) + + return json_schema + + def get_argument_name(self, argument: core_schema.ArgumentsParameter) -> str: + """Retrieves the name of an argument. + + Args: + argument: The core schema. + + Returns: + The name of the argument. + """ + name = argument['name'] + if self.by_alias: + alias = argument.get('alias') + if isinstance(alias, str): + name = alias + else: + pass # might want to do something else? + return name + + def call_schema(self, schema: core_schema.CallSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a function call. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.generate_inner(schema['arguments_schema']) + + def custom_error_schema(self, schema: core_schema.CustomErrorSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a custom error. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return self.generate_inner(schema['schema']) + + def json_schema(self, schema: core_schema.JsonSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a JSON object. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + content_core_schema = schema.get('schema') or core_schema.any_schema() + content_json_schema = self.generate_inner(content_core_schema) + if self.mode == 'validation': + return {'type': 'string', 'contentMediaType': 'application/json', 'contentSchema': content_json_schema} + else: + # self.mode == 'serialization' + return content_json_schema + + def url_schema(self, schema: core_schema.UrlSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a URL. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + json_schema = {'type': 'string', 'format': 'uri', 'minLength': 1} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.string) + return json_schema + + def multi_host_url_schema(self, schema: core_schema.MultiHostUrlSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a URL that can be used with multiple hosts. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + # Note: 'multi-host-uri' is a custom/pydantic-specific format, not part of the JSON Schema spec + json_schema = {'type': 'string', 'format': 'multi-host-uri', 'minLength': 1} + self.update_with_validations(json_schema, schema, self.ValidationsMapping.string) + return json_schema + + def uuid_schema(self, schema: core_schema.UuidSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a UUID. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + return {'type': 'string', 'format': 'uuid'} + + def definitions_schema(self, schema: core_schema.DefinitionsSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that defines a JSON object with definitions. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + for definition in schema['definitions']: + try: + self.generate_inner(definition) + except PydanticInvalidForJsonSchema as e: + core_ref: CoreRef = CoreRef(definition['ref']) # type: ignore + self._core_defs_invalid_for_json_schema[self.get_defs_ref((core_ref, self.mode))] = e + continue + return self.generate_inner(schema['schema']) + + def definition_ref_schema(self, schema: core_schema.DefinitionReferenceSchema) -> JsonSchemaValue: + """Generates a JSON schema that matches a schema that references a definition. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + core_ref = CoreRef(schema['schema_ref']) + _, ref_json_schema = self.get_cache_defs_ref_schema(core_ref) + return ref_json_schema + + def ser_schema( + self, schema: core_schema.SerSchema | core_schema.IncExSeqSerSchema | core_schema.IncExDictSerSchema + ) -> JsonSchemaValue | None: + """Generates a JSON schema that matches a schema that defines a serialized object. + + Args: + schema: The core schema. + + Returns: + The generated JSON schema. + """ + schema_type = schema['type'] + if schema_type == 'function-plain' or schema_type == 'function-wrap': + # PlainSerializerFunctionSerSchema or WrapSerializerFunctionSerSchema + return_schema = schema.get('return_schema') + if return_schema is not None: + return self.generate_inner(return_schema) + elif schema_type == 'format' or schema_type == 'to-string': + # FormatSerSchema or ToStringSerSchema + return self.str_schema(core_schema.str_schema()) + elif schema['type'] == 'model': + # ModelSerSchema + return self.generate_inner(schema['schema']) + return None + + # ### Utility methods + + def get_title_from_name(self, name: str) -> str: + """Retrieves a title from a name. + + Args: + name: The name to retrieve a title from. + + Returns: + The title. + """ + return name.title().replace('_', ' ') + + def field_title_should_be_set(self, schema: CoreSchemaOrField) -> bool: + """Returns true if a field with the given schema should have a title set based on the field name. + + Intuitively, we want this to return true for schemas that wouldn't otherwise provide their own title + (e.g., int, float, str), and false for those that would (e.g., BaseModel subclasses). + + Args: + schema: The schema to check. + + Returns: + `True` if the field should have a title set, `False` otherwise. + """ + if _core_utils.is_core_schema_field(schema): + if schema['type'] == 'computed-field': + field_schema = schema['return_schema'] + else: + field_schema = schema['schema'] + return self.field_title_should_be_set(field_schema) + + elif _core_utils.is_core_schema(schema): + if schema.get('ref'): # things with refs, such as models and enums, should not have titles set + return False + if schema['type'] in {'default', 'nullable', 'definitions'}: + return self.field_title_should_be_set(schema['schema']) # type: ignore[typeddict-item] + if _core_utils.is_function_with_inner_schema(schema): + return self.field_title_should_be_set(schema['schema']) + if schema['type'] == 'definition-ref': + # Referenced schemas should not have titles set for the same reason + # schemas with refs should not + return False + return True # anything else should have title set + + else: + raise PydanticInvalidForJsonSchema(f'Unexpected schema type: schema={schema}') # pragma: no cover + + def normalize_name(self, name: str) -> str: + """Normalizes a name to be used as a key in a dictionary. + + Args: + name: The name to normalize. + + Returns: + The normalized name. + """ + return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name).replace('.', '__') + + def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef: + """Override this method to change the way that definitions keys are generated from a core reference. + + Args: + core_mode_ref: The core reference. + + Returns: + The definitions key. + """ + # Split the core ref into "components"; generic origins and arguments are each separate components + core_ref, mode = core_mode_ref + components = re.split(r'([\][,])', core_ref) + # Remove IDs from each component + components = [x.rsplit(':', 1)[0] for x in components] + core_ref_no_id = ''.join(components) + # Remove everything before the last period from each "component" + components = [re.sub(r'(?:[^.[\]]+\.)+((?:[^.[\]]+))', r'\1', x) for x in components] + short_ref = ''.join(components) + + mode_title = _MODE_TITLE_MAPPING[mode] + + # It is important that the generated defs_ref values be such that at least one choice will not + # be generated for any other core_ref. Currently, this should be the case because we include + # the id of the source type in the core_ref + name = DefsRef(self.normalize_name(short_ref)) + name_mode = DefsRef(self.normalize_name(short_ref) + f'-{mode_title}') + module_qualname = DefsRef(self.normalize_name(core_ref_no_id)) + module_qualname_mode = DefsRef(f'{module_qualname}-{mode_title}') + module_qualname_id = DefsRef(self.normalize_name(core_ref)) + occurrence_index = self._collision_index.get(module_qualname_id) + if occurrence_index is None: + self._collision_counter[module_qualname] += 1 + occurrence_index = self._collision_index[module_qualname_id] = self._collision_counter[module_qualname] + + module_qualname_occurrence = DefsRef(f'{module_qualname}__{occurrence_index}') + module_qualname_occurrence_mode = DefsRef(f'{module_qualname_mode}__{occurrence_index}') + + self._prioritized_defsref_choices[module_qualname_occurrence_mode] = [ + name, + name_mode, + module_qualname, + module_qualname_mode, + module_qualname_occurrence, + module_qualname_occurrence_mode, + ] + + return module_qualname_occurrence_mode + + def get_cache_defs_ref_schema(self, core_ref: CoreRef) -> tuple[DefsRef, JsonSchemaValue]: + """This method wraps the get_defs_ref method with some cache-lookup/population logic, + and returns both the produced defs_ref and the JSON schema that will refer to the right definition. + + Args: + core_ref: The core reference to get the definitions reference for. + + Returns: + A tuple of the definitions reference and the JSON schema that will refer to it. + """ + core_mode_ref = (core_ref, self.mode) + maybe_defs_ref = self.core_to_defs_refs.get(core_mode_ref) + if maybe_defs_ref is not None: + json_ref = self.core_to_json_refs[core_mode_ref] + return maybe_defs_ref, {'$ref': json_ref} + + defs_ref = self.get_defs_ref(core_mode_ref) + + # populate the ref translation mappings + self.core_to_defs_refs[core_mode_ref] = defs_ref + self.defs_to_core_refs[defs_ref] = core_mode_ref + + json_ref = JsonRef(self.ref_template.format(model=defs_ref)) + self.core_to_json_refs[core_mode_ref] = json_ref + self.json_to_defs_refs[json_ref] = defs_ref + ref_json_schema = {'$ref': json_ref} + return defs_ref, ref_json_schema + + def handle_ref_overrides(self, json_schema: JsonSchemaValue) -> JsonSchemaValue: + """It is not valid for a schema with a top-level $ref to have sibling keys. + + During our own schema generation, we treat sibling keys as overrides to the referenced schema, + but this is not how the official JSON schema spec works. + + Because of this, we first remove any sibling keys that are redundant with the referenced schema, then if + any remain, we transform the schema from a top-level '$ref' to use allOf to move the $ref out of the top level. + (See bottom of https://swagger.io/docs/specification/using-ref/ for a reference about this behavior) + """ + if '$ref' in json_schema: + # prevent modifications to the input; this copy may be safe to drop if there is significant overhead + json_schema = json_schema.copy() + + referenced_json_schema = self.get_schema_from_definitions(JsonRef(json_schema['$ref'])) + if referenced_json_schema is None: + # This can happen when building schemas for models with not-yet-defined references. + # It may be a good idea to do a recursive pass at the end of the generation to remove + # any redundant override keys. + if len(json_schema) > 1: + # Make it an allOf to at least resolve the sibling keys issue + json_schema = json_schema.copy() + json_schema.setdefault('allOf', []) + json_schema['allOf'].append({'$ref': json_schema['$ref']}) + del json_schema['$ref'] + + return json_schema + for k, v in list(json_schema.items()): + if k == '$ref': + continue + if k in referenced_json_schema and referenced_json_schema[k] == v: + del json_schema[k] # redundant key + if len(json_schema) > 1: + # There is a remaining "override" key, so we need to move $ref out of the top level + json_ref = JsonRef(json_schema['$ref']) + del json_schema['$ref'] + assert 'allOf' not in json_schema # this should never happen, but just in case + json_schema['allOf'] = [{'$ref': json_ref}] + + return json_schema + + def get_schema_from_definitions(self, json_ref: JsonRef) -> JsonSchemaValue | None: + def_ref = self.json_to_defs_refs[json_ref] + if def_ref in self._core_defs_invalid_for_json_schema: + raise self._core_defs_invalid_for_json_schema[def_ref] + return self.definitions.get(def_ref, None) + + def encode_default(self, dft: Any) -> Any: + """Encode a default value to a JSON-serializable value. + + This is used to encode default values for fields in the generated JSON schema. + + Args: + dft: The default value to encode. + + Returns: + The encoded default value. + """ + from .type_adapter import TypeAdapter, _type_has_config + + config = self._config + try: + default = ( + dft + if _type_has_config(type(dft)) + else TypeAdapter(type(dft), config=config.config_dict).dump_python(dft, mode='json') + ) + except PydanticSchemaGenerationError: + raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}') + + return pydantic_core.to_jsonable_python( + default, + timedelta_mode=config.ser_json_timedelta, + bytes_mode=config.ser_json_bytes, + ) + + def update_with_validations( + self, json_schema: JsonSchemaValue, core_schema: CoreSchema, mapping: dict[str, str] + ) -> None: + """Update the json_schema with the corresponding validations specified in the core_schema, + using the provided mapping to translate keys in core_schema to the appropriate keys for a JSON schema. + + Args: + json_schema: The JSON schema to update. + core_schema: The core schema to get the validations from. + mapping: A mapping from core_schema attribute names to the corresponding JSON schema attribute names. + """ + for core_key, json_schema_key in mapping.items(): + if core_key in core_schema: + json_schema[json_schema_key] = core_schema[core_key] + + class ValidationsMapping: + """This class just contains mappings from core_schema attribute names to the corresponding + JSON schema attribute names. While I suspect it is unlikely to be necessary, you can in + principle override this class in a subclass of GenerateJsonSchema (by inheriting from + GenerateJsonSchema.ValidationsMapping) to change these mappings. + """ + + numeric = { + 'multiple_of': 'multipleOf', + 'le': 'maximum', + 'ge': 'minimum', + 'lt': 'exclusiveMaximum', + 'gt': 'exclusiveMinimum', + } + bytes = { + 'min_length': 'minLength', + 'max_length': 'maxLength', + } + string = { + 'min_length': 'minLength', + 'max_length': 'maxLength', + 'pattern': 'pattern', + } + array = { + 'min_length': 'minItems', + 'max_length': 'maxItems', + } + object = { + 'min_length': 'minProperties', + 'max_length': 'maxProperties', + } + date = { + 'le': 'maximum', + 'ge': 'minimum', + 'lt': 'exclusiveMaximum', + 'gt': 'exclusiveMinimum', + } + + def get_flattened_anyof(self, schemas: list[JsonSchemaValue]) -> JsonSchemaValue: + members = [] + for schema in schemas: + if len(schema) == 1 and 'anyOf' in schema: + members.extend(schema['anyOf']) + else: + members.append(schema) + members = _deduplicate_schemas(members) + if len(members) == 1: + return members[0] + return {'anyOf': members} + + def get_json_ref_counts(self, json_schema: JsonSchemaValue) -> dict[JsonRef, int]: + """Get all values corresponding to the key '$ref' anywhere in the json_schema.""" + json_refs: dict[JsonRef, int] = Counter() + + def _add_json_refs(schema: Any) -> None: + if isinstance(schema, dict): + if '$ref' in schema: + json_ref = JsonRef(schema['$ref']) + if not isinstance(json_ref, str): + return # in this case, '$ref' might have been the name of a property + already_visited = json_ref in json_refs + json_refs[json_ref] += 1 + if already_visited: + return # prevent recursion on a definition that was already visited + defs_ref = self.json_to_defs_refs[json_ref] + if defs_ref in self._core_defs_invalid_for_json_schema: + raise self._core_defs_invalid_for_json_schema[defs_ref] + _add_json_refs(self.definitions[defs_ref]) + + for v in schema.values(): + _add_json_refs(v) + elif isinstance(schema, list): + for v in schema: + _add_json_refs(v) + + _add_json_refs(json_schema) + return json_refs + + def handle_invalid_for_json_schema(self, schema: CoreSchemaOrField, error_info: str) -> JsonSchemaValue: + raise PydanticInvalidForJsonSchema(f'Cannot generate a JsonSchema for {error_info}') + + def emit_warning(self, kind: JsonSchemaWarningKind, detail: str) -> None: + """This method simply emits PydanticJsonSchemaWarnings based on handling in the `warning_message` method.""" + message = self.render_warning_message(kind, detail) + if message is not None: + warnings.warn(message, PydanticJsonSchemaWarning) + + def render_warning_message(self, kind: JsonSchemaWarningKind, detail: str) -> str | None: + """This method is responsible for ignoring warnings as desired, and for formatting the warning messages. + + You can override the value of `ignored_warning_kinds` in a subclass of GenerateJsonSchema + to modify what warnings are generated. If you want more control, you can override this method; + just return None in situations where you don't want warnings to be emitted. + + Args: + kind: The kind of warning to render. It can be one of the following: + + - 'skipped-choice': A choice field was skipped because it had no valid choices. + - 'non-serializable-default': A default value was skipped because it was not JSON-serializable. + detail: A string with additional details about the warning. + + Returns: + The formatted warning message, or `None` if no warning should be emitted. + """ + if kind in self.ignored_warning_kinds: + return None + return f'{detail} [{kind}]' + + def _build_definitions_remapping(self) -> _DefinitionsRemapping: + defs_to_json: dict[DefsRef, JsonRef] = {} + for defs_refs in self._prioritized_defsref_choices.values(): + for defs_ref in defs_refs: + json_ref = JsonRef(self.ref_template.format(model=defs_ref)) + defs_to_json[defs_ref] = json_ref + + return _DefinitionsRemapping.from_prioritized_choices( + self._prioritized_defsref_choices, defs_to_json, self.definitions + ) + + def _garbage_collect_definitions(self, schema: JsonSchemaValue) -> None: + visited_defs_refs: set[DefsRef] = set() + unvisited_json_refs = _get_all_json_refs(schema) + while unvisited_json_refs: + next_json_ref = unvisited_json_refs.pop() + next_defs_ref = self.json_to_defs_refs[next_json_ref] + if next_defs_ref in visited_defs_refs: + continue + visited_defs_refs.add(next_defs_ref) + unvisited_json_refs.update(_get_all_json_refs(self.definitions[next_defs_ref])) + + self.definitions = {k: v for k, v in self.definitions.items() if k in visited_defs_refs} + + +# ##### Start JSON Schema Generation Functions ##### + + +def model_json_schema( + cls: type[BaseModel] | type[PydanticDataclass], + by_alias: bool = True, + ref_template: str = DEFAULT_REF_TEMPLATE, + schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, + mode: JsonSchemaMode = 'validation', +) -> dict[str, Any]: + """Utility function to generate a JSON Schema for a model. + + Args: + cls: The model class to generate a JSON Schema for. + by_alias: If `True` (the default), fields will be serialized according to their alias. + If `False`, fields will be serialized according to their attribute name. + ref_template: The template to use for generating JSON Schema references. + schema_generator: The class to use for generating the JSON Schema. + mode: The mode to use for generating the JSON Schema. It can be one of the following: + + - 'validation': Generate a JSON Schema for validating data. + - 'serialization': Generate a JSON Schema for serializing data. + + Returns: + The generated JSON Schema. + """ + from .main import BaseModel + + schema_generator_instance = schema_generator(by_alias=by_alias, ref_template=ref_template) + + if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema): + cls.__pydantic_core_schema__.rebuild() + + if cls is BaseModel: + raise AttributeError('model_json_schema() must be called on a subclass of BaseModel, not BaseModel itself.') + + assert not isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it' + return schema_generator_instance.generate(cls.__pydantic_core_schema__, mode=mode) + + +def models_json_schema( + models: Sequence[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode]], + *, + by_alias: bool = True, + title: str | None = None, + description: str | None = None, + ref_template: str = DEFAULT_REF_TEMPLATE, + schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, +) -> tuple[dict[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]: + """Utility function to generate a JSON Schema for multiple models. + + Args: + models: A sequence of tuples of the form (model, mode). + by_alias: Whether field aliases should be used as keys in the generated JSON Schema. + title: The title of the generated JSON Schema. + description: The description of the generated JSON Schema. + ref_template: The reference template to use for generating JSON Schema references. + schema_generator: The schema generator to use for generating the JSON Schema. + + Returns: + A tuple where: + - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and + whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have + JsonRef references to definitions that are defined in the second returned element.) + - The second element is a JSON schema containing all definitions referenced in the first returned + element, along with the optional title and description keys. + """ + for cls, _ in models: + if isinstance(cls.__pydantic_core_schema__, _mock_val_ser.MockCoreSchema): + cls.__pydantic_core_schema__.rebuild() + + instance = schema_generator(by_alias=by_alias, ref_template=ref_template) + inputs: list[tuple[type[BaseModel] | type[PydanticDataclass], JsonSchemaMode, CoreSchema]] = [ + (m, mode, m.__pydantic_core_schema__) for m, mode in models + ] + json_schemas_map, definitions = instance.generate_definitions(inputs) + + json_schema: dict[str, Any] = {} + if definitions: + json_schema['$defs'] = definitions + if title: + json_schema['title'] = title + if description: + json_schema['description'] = description + + return json_schemas_map, json_schema + + +# ##### End JSON Schema Generation Functions ##### + + +_HashableJsonValue: TypeAlias = Union[ + int, float, str, bool, None, Tuple['_HashableJsonValue', ...], Tuple[Tuple[str, '_HashableJsonValue'], ...] +] + + +def _deduplicate_schemas(schemas: Iterable[JsonDict]) -> list[JsonDict]: + return list({_make_json_hashable(schema): schema for schema in schemas}.values()) + + +def _make_json_hashable(value: JsonValue) -> _HashableJsonValue: + if isinstance(value, dict): + return tuple(sorted((k, _make_json_hashable(v)) for k, v in value.items())) + elif isinstance(value, list): + return tuple(_make_json_hashable(v) for v in value) + else: + return value + + +def _sort_json_schema(value: JsonSchemaValue, parent_key: str | None = None) -> JsonSchemaValue: + if isinstance(value, dict): + sorted_dict: dict[str, JsonSchemaValue] = {} + keys = value.keys() + if (parent_key != 'properties') and (parent_key != 'default'): + keys = sorted(keys) + for key in keys: + sorted_dict[key] = _sort_json_schema(value[key], parent_key=key) + return sorted_dict + elif isinstance(value, list): + sorted_list: list[JsonSchemaValue] = [] + for item in value: # type: ignore + sorted_list.append(_sort_json_schema(item, parent_key)) + return sorted_list # type: ignore + else: + return value + + +@dataclasses.dataclass(**_internal_dataclass.slots_true) +class WithJsonSchema: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/json_schema/#withjsonschema-annotation + + Add this as an annotation on a field to override the (base) JSON schema that would be generated for that field. + This provides a way to set a JSON schema for types that would otherwise raise errors when producing a JSON schema, + such as Callable, or types that have an is-instance core schema, without needing to go so far as creating a + custom subclass of pydantic.json_schema.GenerateJsonSchema. + Note that any _modifications_ to the schema that would normally be made (such as setting the title for model fields) + will still be performed. + + If `mode` is set this will only apply to that schema generation mode, allowing you + to set different json schemas for validation and serialization. + """ + + json_schema: JsonSchemaValue | None + mode: Literal['validation', 'serialization'] | None = None + + def __get_pydantic_json_schema__( + self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + mode = self.mode or handler.mode + if mode != handler.mode: + return handler(core_schema) + if self.json_schema is None: + # This exception is handled in pydantic.json_schema.GenerateJsonSchema._named_required_fields_schema + raise PydanticOmit + else: + return self.json_schema + + def __hash__(self) -> int: + return hash(type(self.mode)) + + +@dataclasses.dataclass(**_internal_dataclass.slots_true) +class Examples: + """Add examples to a JSON schema. + + Examples should be a map of example names (strings) + to example values (any valid JSON). + + If `mode` is set this will only apply to that schema generation mode, + allowing you to add different examples for validation and serialization. + """ + + examples: dict[str, Any] + mode: Literal['validation', 'serialization'] | None = None + + def __get_pydantic_json_schema__( + self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + mode = self.mode or handler.mode + json_schema = handler(core_schema) + if mode != handler.mode: + return json_schema + examples = json_schema.get('examples', {}) + examples.update(to_jsonable_python(self.examples)) + json_schema['examples'] = examples + return json_schema + + def __hash__(self) -> int: + return hash(type(self.mode)) + + +def _get_all_json_refs(item: Any) -> set[JsonRef]: + """Get all the definitions references from a JSON schema.""" + refs: set[JsonRef] = set() + stack = [item] + + while stack: + current = stack.pop() + if isinstance(current, dict): + for key, value in current.items(): + if key == '$ref' and isinstance(value, str): + refs.add(JsonRef(value)) + elif isinstance(value, dict): + stack.append(value) + elif isinstance(value, list): + stack.extend(value) + elif isinstance(current, list): + stack.extend(current) + + return refs + + +AnyType = TypeVar('AnyType') + +if TYPE_CHECKING: + SkipJsonSchema = Annotated[AnyType, ...] +else: + + @dataclasses.dataclass(**_internal_dataclass.slots_true) + class SkipJsonSchema: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/json_schema/#skipjsonschema-annotation + + Add this as an annotation on a field to skip generating a JSON schema for that field. + + Example: + ```py + from typing import Union + + from pydantic import BaseModel + from pydantic.json_schema import SkipJsonSchema + + from pprint import pprint + + + class Model(BaseModel): + a: Union[int, None] = None # (1)! + b: Union[int, SkipJsonSchema[None]] = None # (2)! + c: SkipJsonSchema[Union[int, None]] = None # (3)! + + + pprint(Model.model_json_schema()) + ''' + { + 'properties': { + 'a': { + 'anyOf': [ + {'type': 'integer'}, + {'type': 'null'} + ], + 'default': None, + 'title': 'A' + }, + 'b': { + 'default': None, + 'title': 'B', + 'type': 'integer' + } + }, + 'title': 'Model', + 'type': 'object' + } + ''' + ``` + + 1. The integer and null types are both included in the schema for `a`. + 2. The integer type is the only type included in the schema for `b`. + 3. The entirety of the `c` field is omitted from the schema. + """ + + def __class_getitem__(cls, item: AnyType) -> AnyType: + return Annotated[item, cls()] + + def __get_pydantic_json_schema__( + self, core_schema: CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + raise PydanticOmit + + def __hash__(self) -> int: + return hash(type(self)) + + +def _get_typed_dict_cls(schema: core_schema.TypedDictSchema) -> type[Any] | None: + metadata = _core_metadata.CoreMetadataHandler(schema).metadata + cls = metadata.get('pydantic_typed_dict_cls') + return cls + + +def _get_typed_dict_config(cls: type[Any] | None) -> ConfigDict: + if cls is not None: + try: + return _decorators.get_attribute_from_bases(cls, '__pydantic_config__') + except AttributeError: + pass + return {} diff --git a/env/Lib/site-packages/pydantic/main.py b/env/Lib/site-packages/pydantic/main.py new file mode 100644 index 0000000..c40c818 --- /dev/null +++ b/env/Lib/site-packages/pydantic/main.py @@ -0,0 +1,1580 @@ +"""Logic for creating models.""" + +from __future__ import annotations as _annotations + +import operator +import sys +import types +import typing +import warnings +from copy import copy, deepcopy +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Dict, + Generator, + Literal, + Set, + Tuple, + TypeVar, + Union, + cast, + overload, +) + +import pydantic_core +import typing_extensions +from pydantic_core import PydanticUndefined +from typing_extensions import Self, TypeAlias, Unpack + +from ._internal import ( + _config, + _decorators, + _fields, + _forward_ref, + _generics, + _mock_val_ser, + _model_construction, + _repr, + _typing_extra, + _utils, +) +from ._migration import getattr_migration +from .aliases import AliasChoices, AliasPath +from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler +from .config import ConfigDict +from .errors import PydanticUndefinedAnnotation, PydanticUserError +from .json_schema import DEFAULT_REF_TEMPLATE, GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue, model_json_schema +from .plugin._schema_validator import PluggableSchemaValidator +from .warnings import PydanticDeprecatedSince20 + +# Always define certain types that are needed to resolve method type hints/annotations +# (even when not type checking) via typing.get_type_hints. +ModelT = TypeVar('ModelT', bound='BaseModel') +TupleGenerator = Generator[Tuple[str, Any], None, None] +# should be `set[int] | set[str] | dict[int, IncEx] | dict[str, IncEx] | None`, but mypy can't cope +IncEx: TypeAlias = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any], None] + + +if TYPE_CHECKING: + from inspect import Signature + from pathlib import Path + + from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator + + from ._internal._utils import AbstractSetIntStr, MappingIntStrAny + from .deprecated.parse import Protocol as DeprecatedParseProtocol + from .fields import ComputedFieldInfo, FieldInfo, ModelPrivateAttr + from .fields import PrivateAttr as _PrivateAttr +else: + # See PyCharm issues https://youtrack.jetbrains.com/issue/PY-21915 + # and https://youtrack.jetbrains.com/issue/PY-51428 + DeprecationWarning = PydanticDeprecatedSince20 + +__all__ = 'BaseModel', 'create_model' + +_object_setattr = _model_construction.object_setattr + + +class BaseModel(metaclass=_model_construction.ModelMetaclass): + """Usage docs: https://docs.pydantic.dev/2.8/concepts/models/ + + A base class for creating Pydantic models. + + Attributes: + __class_vars__: The names of classvars defined on the model. + __private_attributes__: Metadata about the private attributes of the model. + __signature__: The signature for instantiating the model. + + __pydantic_complete__: Whether model building is completed, or if there are still undefined fields. + __pydantic_core_schema__: The pydantic-core schema used to build the SchemaValidator and SchemaSerializer. + __pydantic_custom_init__: Whether the model has a custom `__init__` function. + __pydantic_decorators__: Metadata containing the decorators defined on the model. + This replaces `Model.__validators__` and `Model.__root_validators__` from Pydantic V1. + __pydantic_generic_metadata__: Metadata for generic models; contains data used for a similar purpose to + __args__, __origin__, __parameters__ in typing-module generics. May eventually be replaced by these. + __pydantic_parent_namespace__: Parent namespace of the model, used for automatic rebuilding of models. + __pydantic_post_init__: The name of the post-init method for the model, if defined. + __pydantic_root_model__: Whether the model is a `RootModel`. + __pydantic_serializer__: The pydantic-core SchemaSerializer used to dump instances of the model. + __pydantic_validator__: The pydantic-core SchemaValidator used to validate instances of the model. + + __pydantic_extra__: An instance attribute with the values of extra fields from validation when + `model_config['extra'] == 'allow'`. + __pydantic_fields_set__: An instance attribute with the names of fields explicitly set. + __pydantic_private__: Instance attribute with the values of private attributes set on the model instance. + """ + + if TYPE_CHECKING: + # Here we provide annotations for the attributes of BaseModel. + # Many of these are populated by the metaclass, which is why this section is in a `TYPE_CHECKING` block. + # However, for the sake of easy review, we have included type annotations of all class and instance attributes + # of `BaseModel` here: + + # Class attributes + model_config: ClassVar[ConfigDict] + """ + Configuration for the model, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. + """ + + model_fields: ClassVar[dict[str, FieldInfo]] + """ + Metadata about the fields defined on the model, + mapping of field names to [`FieldInfo`][pydantic.fields.FieldInfo]. + + This replaces `Model.__fields__` from Pydantic V1. + """ + + model_computed_fields: ClassVar[dict[str, ComputedFieldInfo]] + """A dictionary of computed field names and their corresponding `ComputedFieldInfo` objects.""" + + __class_vars__: ClassVar[set[str]] + __private_attributes__: ClassVar[dict[str, ModelPrivateAttr]] + __signature__: ClassVar[Signature] + + __pydantic_complete__: ClassVar[bool] + __pydantic_core_schema__: ClassVar[CoreSchema] + __pydantic_custom_init__: ClassVar[bool] + __pydantic_decorators__: ClassVar[_decorators.DecoratorInfos] + __pydantic_generic_metadata__: ClassVar[_generics.PydanticGenericMetadata] + __pydantic_parent_namespace__: ClassVar[dict[str, Any] | None] + __pydantic_post_init__: ClassVar[None | Literal['model_post_init']] + __pydantic_root_model__: ClassVar[bool] + __pydantic_serializer__: ClassVar[SchemaSerializer] + __pydantic_validator__: ClassVar[SchemaValidator | PluggableSchemaValidator] + + # Instance attributes + __pydantic_extra__: dict[str, Any] | None = _PrivateAttr() + __pydantic_fields_set__: set[str] = _PrivateAttr() + __pydantic_private__: dict[str, Any] | None = _PrivateAttr() + + else: + # `model_fields` and `__pydantic_decorators__` must be set for + # pydantic._internal._generate_schema.GenerateSchema.model_schema to work for a plain BaseModel annotation + model_fields = {} + model_computed_fields = {} + + __pydantic_decorators__ = _decorators.DecoratorInfos() + __pydantic_parent_namespace__ = None + # Prevent `BaseModel` from being instantiated directly: + __pydantic_core_schema__ = _mock_val_ser.MockCoreSchema( + 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', + code='base-model-instantiated', + ) + __pydantic_validator__ = _mock_val_ser.MockValSer( + 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', + val_or_ser='validator', + code='base-model-instantiated', + ) + __pydantic_serializer__ = _mock_val_ser.MockValSer( + 'Pydantic models should inherit from BaseModel, BaseModel cannot be instantiated directly', + val_or_ser='serializer', + code='base-model-instantiated', + ) + + __slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__' + + model_config = ConfigDict() + __pydantic_complete__ = False + __pydantic_root_model__ = False + + def __init__(self, /, **data: Any) -> None: # type: ignore + """Create a new model by parsing and validating input data from keyword arguments. + + Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be + validated to form a valid model. + + `self` is explicitly positional-only to allow `self` as a field name. + """ + # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks + __tracebackhide__ = True + self.__pydantic_validator__.validate_python(data, self_instance=self) + + # The following line sets a flag that we use to determine when `__init__` gets overridden by the user + __init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess] + + @property + def model_extra(self) -> dict[str, Any] | None: + """Get extra fields set during validation. + + Returns: + A dictionary of extra fields, or `None` if `config.extra` is not set to `"allow"`. + """ + return self.__pydantic_extra__ + + @property + def model_fields_set(self) -> set[str]: + """Returns the set of fields that have been explicitly set on this model instance. + + Returns: + A set of strings representing the fields that have been set, + i.e. that were not filled from defaults. + """ + return self.__pydantic_fields_set__ + + @classmethod + def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: C901 + """Creates a new instance of the `Model` class with validated data. + + Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data. + Default values are respected, but no other validation is performed. + + !!! note + `model_construct()` generally respects the `model_config.extra` setting on the provided model. + That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__` + and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored. + Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in + an error if extra values are passed, but they will be ignored. + + Args: + _fields_set: The set of field names accepted for the Model instance. + values: Trusted or pre-validated data dictionary. + + Returns: + A new instance of the `Model` class with validated data. + """ + m = cls.__new__(cls) + fields_values: dict[str, Any] = {} + fields_set = set() + + for name, field in cls.model_fields.items(): + if field.alias is not None and field.alias in values: + fields_values[name] = values.pop(field.alias) + fields_set.add(name) + + if (name not in fields_set) and (field.validation_alias is not None): + validation_aliases: list[str | AliasPath] = ( + field.validation_alias.choices + if isinstance(field.validation_alias, AliasChoices) + else [field.validation_alias] + ) + + for alias in validation_aliases: + if isinstance(alias, str) and alias in values: + fields_values[name] = values.pop(alias) + fields_set.add(name) + break + elif isinstance(alias, AliasPath): + value = alias.search_dict_for_path(values) + if value is not PydanticUndefined: + fields_values[name] = value + fields_set.add(name) + break + + if name not in fields_set: + if name in values: + fields_values[name] = values.pop(name) + fields_set.add(name) + elif not field.is_required(): + fields_values[name] = field.get_default(call_default_factory=True) + if _fields_set is None: + _fields_set = fields_set + + _extra: dict[str, Any] | None = ( + {k: v for k, v in values.items()} if cls.model_config.get('extra') == 'allow' else None + ) + _object_setattr(m, '__dict__', fields_values) + _object_setattr(m, '__pydantic_fields_set__', _fields_set) + if not cls.__pydantic_root_model__: + _object_setattr(m, '__pydantic_extra__', _extra) + + if cls.__pydantic_post_init__: + m.model_post_init(None) + # update private attributes with values set + if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None: + for k, v in values.items(): + if k in m.__private_attributes__: + m.__pydantic_private__[k] = v + + elif not cls.__pydantic_root_model__: + # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist + # Since it doesn't, that means that `__pydantic_private__` should be set to None + _object_setattr(m, '__pydantic_private__', None) + + return m + + def model_copy(self, *, update: dict[str, Any] | None = None, deep: bool = False) -> Self: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/serialization/#model_copy + + Returns a copy of the model. + + Args: + update: Values to change/add in the new model. Note: the data is not validated + before creating the new model. You should trust this data. + deep: Set to `True` to make a deep copy of the model. + + Returns: + New model instance. + """ + copied = self.__deepcopy__() if deep else self.__copy__() + if update: + if self.model_config.get('extra') == 'allow': + for k, v in update.items(): + if k in self.model_fields: + copied.__dict__[k] = v + else: + if copied.__pydantic_extra__ is None: + copied.__pydantic_extra__ = {} + copied.__pydantic_extra__[k] = v + else: + copied.__dict__.update(update) + copied.__pydantic_fields_set__.update(update.keys()) + return copied + + def model_dump( + self, + *, + mode: Literal['json', 'python'] | str = 'python', + include: IncEx = None, + exclude: IncEx = None, + context: Any | None = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool | Literal['none', 'warn', 'error'] = True, + serialize_as_any: bool = False, + ) -> dict[str, Any]: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/serialization/#modelmodel_dump + + Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + Args: + mode: The mode in which `to_python` should run. + If mode is 'json', the output will only contain JSON serializable types. + If mode is 'python', the output may contain non-JSON-serializable Python objects. + include: A set of fields to include in the output. + exclude: A set of fields to exclude from the output. + context: Additional context to pass to the serializer. + by_alias: Whether to use the field's alias in the dictionary key if defined. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. + warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + + Returns: + A dictionary representation of the model. + """ + return self.__pydantic_serializer__.to_python( + self, + mode=mode, + by_alias=by_alias, + include=include, + exclude=exclude, + context=context, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + round_trip=round_trip, + warnings=warnings, + serialize_as_any=serialize_as_any, + ) + + def model_dump_json( + self, + *, + indent: int | None = None, + include: IncEx = None, + exclude: IncEx = None, + context: Any | None = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool | Literal['none', 'warn', 'error'] = True, + serialize_as_any: bool = False, + ) -> str: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/serialization/#modelmodel_dump_json + + Generates a JSON representation of the model using Pydantic's `to_json` method. + + Args: + indent: Indentation to use in the JSON output. If None is passed, the output will be compact. + include: Field(s) to include in the JSON output. + exclude: Field(s) to exclude from the JSON output. + context: Additional context to pass to the serializer. + by_alias: Whether to serialize using field aliases. + exclude_unset: Whether to exclude fields that have not been explicitly set. + exclude_defaults: Whether to exclude fields that are set to their default value. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. + warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + + Returns: + A JSON string representation of the model. + """ + return self.__pydantic_serializer__.to_json( + self, + indent=indent, + include=include, + exclude=exclude, + context=context, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + round_trip=round_trip, + warnings=warnings, + serialize_as_any=serialize_as_any, + ).decode() + + @classmethod + def model_json_schema( + cls, + by_alias: bool = True, + ref_template: str = DEFAULT_REF_TEMPLATE, + schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, + mode: JsonSchemaMode = 'validation', + ) -> dict[str, Any]: + """Generates a JSON schema for a model class. + + Args: + by_alias: Whether to use attribute aliases or not. + ref_template: The reference template. + schema_generator: To override the logic used to generate the JSON schema, as a subclass of + `GenerateJsonSchema` with your desired modifications + mode: The mode in which to generate the schema. + + Returns: + The JSON schema for the given model class. + """ + return model_json_schema( + cls, by_alias=by_alias, ref_template=ref_template, schema_generator=schema_generator, mode=mode + ) + + @classmethod + def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str: + """Compute the class name for parametrizations of generic classes. + + This method can be overridden to achieve a custom naming scheme for generic BaseModels. + + Args: + params: Tuple of types of the class. Given a generic class + `Model` with 2 type variables and a concrete model `Model[str, int]`, + the value `(str, int)` would be passed to `params`. + + Returns: + String representing the new class where `params` are passed to `cls` as type variables. + + Raises: + TypeError: Raised when trying to generate concrete names for non-generic models. + """ + if not issubclass(cls, typing.Generic): + raise TypeError('Concrete names should only be generated for generic models.') + + # Any strings received should represent forward references, so we handle them specially below. + # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future, + # we may be able to remove this special case. + param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params] + params_component = ', '.join(param_names) + return f'{cls.__name__}[{params_component}]' + + def model_post_init(self, __context: Any) -> None: + """Override this method to perform additional initialization after `__init__` and `model_construct`. + This is useful if you want to do some validation that requires the entire model to be initialized. + """ + pass + + @classmethod + def model_rebuild( + cls, + *, + force: bool = False, + raise_errors: bool = True, + _parent_namespace_depth: int = 2, + _types_namespace: dict[str, Any] | None = None, + ) -> bool | None: + """Try to rebuild the pydantic-core schema for the model. + + This may be necessary when one of the annotations is a ForwardRef which could not be resolved during + the initial attempt to build the schema, and automatic rebuilding fails. + + Args: + force: Whether to force the rebuilding of the model schema, defaults to `False`. + raise_errors: Whether to raise errors, defaults to `True`. + _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. + _types_namespace: The types namespace, defaults to `None`. + + Returns: + Returns `None` if the schema is already "complete" and rebuilding was not required. + If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`. + """ + if not force and cls.__pydantic_complete__: + return None + else: + if '__pydantic_core_schema__' in cls.__dict__: + delattr(cls, '__pydantic_core_schema__') # delete cached value to ensure full rebuild happens + if _types_namespace is not None: + types_namespace: dict[str, Any] | None = _types_namespace.copy() + else: + if _parent_namespace_depth > 0: + frame_parent_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth) or {} + cls_parent_ns = ( + _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {} + ) + types_namespace = {**cls_parent_ns, **frame_parent_ns} + cls.__pydantic_parent_namespace__ = _model_construction.build_lenient_weakvaluedict(types_namespace) + else: + types_namespace = _model_construction.unpack_lenient_weakvaluedict( + cls.__pydantic_parent_namespace__ + ) + + types_namespace = _typing_extra.get_cls_types_namespace(cls, types_namespace) + + # manually override defer_build so complete_model_class doesn't skip building the model again + config = {**cls.model_config, 'defer_build': False} + return _model_construction.complete_model_class( + cls, + cls.__name__, + _config.ConfigWrapper(config, check=False), + raise_errors=raise_errors, + types_namespace=types_namespace, + ) + + @classmethod + def model_validate( + cls, + obj: Any, + *, + strict: bool | None = None, + from_attributes: bool | None = None, + context: Any | None = None, + ) -> Self: + """Validate a pydantic model instance. + + Args: + obj: The object to validate. + strict: Whether to enforce types strictly. + from_attributes: Whether to extract data from object attributes. + context: Additional context to pass to the validator. + + Raises: + ValidationError: If the object could not be validated. + + Returns: + The validated model instance. + """ + # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks + __tracebackhide__ = True + return cls.__pydantic_validator__.validate_python( + obj, strict=strict, from_attributes=from_attributes, context=context + ) + + @classmethod + def model_validate_json( + cls, + json_data: str | bytes | bytearray, + *, + strict: bool | None = None, + context: Any | None = None, + ) -> Self: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/json/#json-parsing + + Validate the given JSON data against the Pydantic model. + + Args: + json_data: The JSON data to validate. + strict: Whether to enforce types strictly. + context: Extra variables to pass to the validator. + + Returns: + The validated Pydantic model. + + Raises: + ValueError: If `json_data` is not a JSON string. + """ + # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks + __tracebackhide__ = True + return cls.__pydantic_validator__.validate_json(json_data, strict=strict, context=context) + + @classmethod + def model_validate_strings( + cls, + obj: Any, + *, + strict: bool | None = None, + context: Any | None = None, + ) -> Self: + """Validate the given object with string data against the Pydantic model. + + Args: + obj: The object containing string data to validate. + strict: Whether to enforce types strictly. + context: Extra variables to pass to the validator. + + Returns: + The validated Pydantic model. + """ + # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks + __tracebackhide__ = True + return cls.__pydantic_validator__.validate_strings(obj, strict=strict, context=context) + + @classmethod + def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler, /) -> CoreSchema: + """Hook into generating the model's CoreSchema. + + Args: + source: The class we are generating a schema for. + This will generally be the same as the `cls` argument if this is a classmethod. + handler: A callable that calls into Pydantic's internal CoreSchema generation logic. + + Returns: + A `pydantic-core` `CoreSchema`. + """ + # Only use the cached value from this _exact_ class; we don't want one from a parent class + # This is why we check `cls.__dict__` and don't use `cls.__pydantic_core_schema__` or similar. + schema = cls.__dict__.get('__pydantic_core_schema__') + if schema is not None and not isinstance(schema, _mock_val_ser.MockCoreSchema): + # Due to the way generic classes are built, it's possible that an invalid schema may be temporarily + # set on generic classes. I think we could resolve this to ensure that we get proper schema caching + # for generics, but for simplicity for now, we just always rebuild if the class has a generic origin. + if not cls.__pydantic_generic_metadata__['origin']: + return cls.__pydantic_core_schema__ + + return handler(source) + + @classmethod + def __get_pydantic_json_schema__( + cls, + core_schema: CoreSchema, + handler: GetJsonSchemaHandler, + /, + ) -> JsonSchemaValue: + """Hook into generating the model's JSON schema. + + Args: + core_schema: A `pydantic-core` CoreSchema. + You can ignore this argument and call the handler with a new CoreSchema, + wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`), + or just call the handler with the original schema. + handler: Call into Pydantic's internal JSON schema generation. + This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema + generation fails. + Since this gets called by `BaseModel.model_json_schema` you can override the + `schema_generator` argument to that function to change JSON schema generation globally + for a type. + + Returns: + A JSON schema, as a Python object. + """ + return handler(core_schema) + + @classmethod + def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: + """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass` + only after the class is actually fully initialized. In particular, attributes like `model_fields` will + be present when this is called. + + This is necessary because `__init_subclass__` will always be called by `type.__new__`, + and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that + `type.__new__` was called in such a manner that the class would already be sufficiently initialized. + + This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely, + any kwargs passed to the class definition that aren't used internally by pydantic. + + Args: + **kwargs: Any keyword arguments passed to the class definition that aren't used internally + by pydantic. + """ + pass + + def __class_getitem__( + cls, typevar_values: type[Any] | tuple[type[Any], ...] + ) -> type[BaseModel] | _forward_ref.PydanticRecursiveRef: + cached = _generics.get_cached_generic_type_early(cls, typevar_values) + if cached is not None: + return cached + + if cls is BaseModel: + raise TypeError('Type parameters should be placed on typing.Generic, not BaseModel') + if not hasattr(cls, '__parameters__'): + raise TypeError(f'{cls} cannot be parametrized because it does not inherit from typing.Generic') + if not cls.__pydantic_generic_metadata__['parameters'] and typing.Generic not in cls.__bases__: + raise TypeError(f'{cls} is not a generic class') + + if not isinstance(typevar_values, tuple): + typevar_values = (typevar_values,) + _generics.check_parameters_count(cls, typevar_values) + + # Build map from generic typevars to passed params + typevars_map: dict[_typing_extra.TypeVarType, type[Any]] = dict( + zip(cls.__pydantic_generic_metadata__['parameters'], typevar_values) + ) + + if _utils.all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: + submodel = cls # if arguments are equal to parameters it's the same object + _generics.set_cached_generic_type(cls, typevar_values, submodel) + else: + parent_args = cls.__pydantic_generic_metadata__['args'] + if not parent_args: + args = typevar_values + else: + args = tuple(_generics.replace_types(arg, typevars_map) for arg in parent_args) + + origin = cls.__pydantic_generic_metadata__['origin'] or cls + model_name = origin.model_parametrized_name(args) + params = tuple( + {param: None for param in _generics.iter_contained_typevars(typevars_map.values())} + ) # use dict as ordered set + + with _generics.generic_recursion_self_type(origin, args) as maybe_self_type: + if maybe_self_type is not None: + return maybe_self_type + + cached = _generics.get_cached_generic_type_late(cls, typevar_values, origin, args) + if cached is not None: + return cached + + # Attempt to rebuild the origin in case new types have been defined + try: + # depth 3 gets you above this __class_getitem__ call + origin.model_rebuild(_parent_namespace_depth=3) + except PydanticUndefinedAnnotation: + # It's okay if it fails, it just means there are still undefined types + # that could be evaluated later. + # TODO: Make sure validation fails if there are still undefined types, perhaps using MockValidator + pass + + submodel = _generics.create_generic_submodel(model_name, origin, args, params) + + # Update cache + _generics.set_cached_generic_type(cls, typevar_values, submodel, origin, args) + + return submodel + + def __copy__(self) -> Self: + """Returns a shallow copy of the model.""" + cls = type(self) + m = cls.__new__(cls) + _object_setattr(m, '__dict__', copy(self.__dict__)) + _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__)) + _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) + + if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: + _object_setattr(m, '__pydantic_private__', None) + else: + _object_setattr( + m, + '__pydantic_private__', + {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, + ) + + return m + + def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self: + """Returns a deep copy of the model.""" + cls = type(self) + m = cls.__new__(cls) + _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo)) + _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo)) + # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str], + # and attempting a deepcopy would be marginally slower. + _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) + + if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None: + _object_setattr(m, '__pydantic_private__', None) + else: + _object_setattr( + m, + '__pydantic_private__', + deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo), + ) + + return m + + if not TYPE_CHECKING: + # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access + # The same goes for __setattr__ and __delattr__, see: https://github.com/pydantic/pydantic/issues/8643 + + def __getattr__(self, item: str) -> Any: + private_attributes = object.__getattribute__(self, '__private_attributes__') + if item in private_attributes: + attribute = private_attributes[item] + if hasattr(attribute, '__get__'): + return attribute.__get__(self, type(self)) # type: ignore + + try: + # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items + return self.__pydantic_private__[item] # type: ignore + except KeyError as exc: + raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc + else: + # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized. + # See `BaseModel.__repr_args__` for more details + try: + pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') + except AttributeError: + pydantic_extra = None + + if pydantic_extra: + try: + return pydantic_extra[item] + except KeyError as exc: + raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc + else: + if hasattr(self.__class__, item): + return super().__getattribute__(item) # Raises AttributeError if appropriate + else: + # this is the current error + raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') + + def __setattr__(self, name: str, value: Any) -> None: + if name in self.__class_vars__: + raise AttributeError( + f'{name!r} is a ClassVar of `{self.__class__.__name__}` and cannot be set on an instance. ' + f'If you want to set a value on the class, use `{self.__class__.__name__}.{name} = value`.' + ) + elif not _fields.is_valid_field_name(name): + if self.__pydantic_private__ is None or name not in self.__private_attributes__: + _object_setattr(self, name, value) + else: + attribute = self.__private_attributes__[name] + if hasattr(attribute, '__set__'): + attribute.__set__(self, value) # type: ignore + else: + self.__pydantic_private__[name] = value + return + + self._check_frozen(name, value) + + attr = getattr(self.__class__, name, None) + if isinstance(attr, property): + attr.__set__(self, value) + elif self.model_config.get('validate_assignment', None): + self.__pydantic_validator__.validate_assignment(self, name, value) + elif self.model_config.get('extra') != 'allow' and name not in self.model_fields: + # TODO - matching error + raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"') + elif self.model_config.get('extra') == 'allow' and name not in self.model_fields: + if self.model_extra and name in self.model_extra: + self.__pydantic_extra__[name] = value # type: ignore + else: + try: + getattr(self, name) + except AttributeError: + # attribute does not already exist on instance, so put it in extra + self.__pydantic_extra__[name] = value # type: ignore + else: + # attribute _does_ already exist on instance, and was not in extra, so update it + _object_setattr(self, name, value) + else: + self.__dict__[name] = value + self.__pydantic_fields_set__.add(name) + + def __delattr__(self, item: str) -> Any: + if item in self.__private_attributes__: + attribute = self.__private_attributes__[item] + if hasattr(attribute, '__delete__'): + attribute.__delete__(self) # type: ignore + return + + try: + # Note: self.__pydantic_private__ cannot be None if self.__private_attributes__ has items + del self.__pydantic_private__[item] # type: ignore + return + except KeyError as exc: + raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') from exc + + self._check_frozen(item, None) + + if item in self.model_fields: + object.__delattr__(self, item) + elif self.__pydantic_extra__ is not None and item in self.__pydantic_extra__: + del self.__pydantic_extra__[item] + else: + try: + object.__delattr__(self, item) + except AttributeError: + raise AttributeError(f'{type(self).__name__!r} object has no attribute {item!r}') + + def _check_frozen(self, name: str, value: Any) -> None: + if self.model_config.get('frozen', None): + typ = 'frozen_instance' + elif getattr(self.model_fields.get(name), 'frozen', False): + typ = 'frozen_field' + else: + return + error: pydantic_core.InitErrorDetails = { + 'type': typ, + 'loc': (name,), + 'input': value, + } + raise pydantic_core.ValidationError.from_exception_data(self.__class__.__name__, [error]) + + def __getstate__(self) -> dict[Any, Any]: + private = self.__pydantic_private__ + if private: + private = {k: v for k, v in private.items() if v is not PydanticUndefined} + return { + '__dict__': self.__dict__, + '__pydantic_extra__': self.__pydantic_extra__, + '__pydantic_fields_set__': self.__pydantic_fields_set__, + '__pydantic_private__': private, + } + + def __setstate__(self, state: dict[Any, Any]) -> None: + _object_setattr(self, '__pydantic_fields_set__', state.get('__pydantic_fields_set__', {})) + _object_setattr(self, '__pydantic_extra__', state.get('__pydantic_extra__', {})) + _object_setattr(self, '__pydantic_private__', state.get('__pydantic_private__', {})) + _object_setattr(self, '__dict__', state.get('__dict__', {})) + + if not TYPE_CHECKING: + + def __eq__(self, other: Any) -> bool: + if isinstance(other, BaseModel): + # When comparing instances of generic types for equality, as long as all field values are equal, + # only require their generic origin types to be equal, rather than exact type equality. + # This prevents headaches like MyGeneric(x=1) != MyGeneric[Any](x=1). + self_type = self.__pydantic_generic_metadata__['origin'] or self.__class__ + other_type = other.__pydantic_generic_metadata__['origin'] or other.__class__ + + # Perform common checks first + if not ( + self_type == other_type + and getattr(self, '__pydantic_private__', None) == getattr(other, '__pydantic_private__', None) + and self.__pydantic_extra__ == other.__pydantic_extra__ + ): + return False + + # We only want to compare pydantic fields but ignoring fields is costly. + # We'll perform a fast check first, and fallback only when needed + # See GH-7444 and GH-7825 for rationale and a performance benchmark + + # First, do the fast (and sometimes faulty) __dict__ comparison + if self.__dict__ == other.__dict__: + # If the check above passes, then pydantic fields are equal, we can return early + return True + + # We don't want to trigger unnecessary costly filtering of __dict__ on all unequal objects, so we return + # early if there are no keys to ignore (we would just return False later on anyway) + model_fields = type(self).model_fields.keys() + if self.__dict__.keys() <= model_fields and other.__dict__.keys() <= model_fields: + return False + + # If we reach here, there are non-pydantic-fields keys, mapped to unequal values, that we need to ignore + # Resort to costly filtering of the __dict__ objects + # We use operator.itemgetter because it is much faster than dict comprehensions + # NOTE: Contrary to standard python class and instances, when the Model class has a default value for an + # attribute and the model instance doesn't have a corresponding attribute, accessing the missing attribute + # raises an error in BaseModel.__getattr__ instead of returning the class attribute + # So we can use operator.itemgetter() instead of operator.attrgetter() + getter = operator.itemgetter(*model_fields) if model_fields else lambda _: _utils._SENTINEL + try: + return getter(self.__dict__) == getter(other.__dict__) + except KeyError: + # In rare cases (such as when using the deprecated BaseModel.copy() method), + # the __dict__ may not contain all model fields, which is how we can get here. + # getter(self.__dict__) is much faster than any 'safe' method that accounts + # for missing keys, and wrapping it in a `try` doesn't slow things down much + # in the common case. + self_fields_proxy = _utils.SafeGetItemProxy(self.__dict__) + other_fields_proxy = _utils.SafeGetItemProxy(other.__dict__) + return getter(self_fields_proxy) == getter(other_fields_proxy) + + # other instance is not a BaseModel + else: + return NotImplemented # delegate to the other item in the comparison + + if TYPE_CHECKING: + # We put `__init_subclass__` in a TYPE_CHECKING block because, even though we want the type-checking benefits + # described in the signature of `__init_subclass__` below, we don't want to modify the default behavior of + # subclass initialization. + + def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]): + """This signature is included purely to help type-checkers check arguments to class declaration, which + provides a way to conveniently set model_config key/value pairs. + + ```py + from pydantic import BaseModel + + class MyModel(BaseModel, extra='allow'): + ... + ``` + + However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any + of the config arguments, and will only receive any keyword arguments passed during class initialization + that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.) + + Args: + **kwargs: Keyword arguments passed to the class definition, which set model_config + + Note: + You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called + *after* the class is fully initialized. + """ + + def __iter__(self) -> TupleGenerator: + """So `dict(model)` works.""" + yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')] + extra = self.__pydantic_extra__ + if extra: + yield from extra.items() + + def __repr__(self) -> str: + return f'{self.__repr_name__()}({self.__repr_str__(", ")})' + + def __repr_args__(self) -> _repr.ReprArgs: + for k, v in self.__dict__.items(): + field = self.model_fields.get(k) + if field and field.repr: + yield k, v + + # `__pydantic_extra__` can fail to be set if the model is not yet fully initialized. + # This can happen if a `ValidationError` is raised during initialization and the instance's + # repr is generated as part of the exception handling. Therefore, we use `getattr` here + # with a fallback, even though the type hints indicate the attribute will always be present. + try: + pydantic_extra = object.__getattribute__(self, '__pydantic_extra__') + except AttributeError: + pydantic_extra = None + + if pydantic_extra is not None: + yield from ((k, v) for k, v in pydantic_extra.items()) + yield from ((k, getattr(self, k)) for k, v in self.model_computed_fields.items() if v.repr) + + # take logic from `_repr.Representation` without the side effects of inheritance, see #5740 + __repr_name__ = _repr.Representation.__repr_name__ + __repr_str__ = _repr.Representation.__repr_str__ + __pretty__ = _repr.Representation.__pretty__ + __rich_repr__ = _repr.Representation.__rich_repr__ + + def __str__(self) -> str: + return self.__repr_str__(' ') + + # ##### Deprecated methods from v1 ##### + @property + @typing_extensions.deprecated( + 'The `__fields__` attribute is deprecated, use `model_fields` instead.', category=None + ) + def __fields__(self) -> dict[str, FieldInfo]: + warnings.warn( + 'The `__fields__` attribute is deprecated, use `model_fields` instead.', category=PydanticDeprecatedSince20 + ) + return self.model_fields + + @property + @typing_extensions.deprecated( + 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.', + category=None, + ) + def __fields_set__(self) -> set[str]: + warnings.warn( + 'The `__fields_set__` attribute is deprecated, use `model_fields_set` instead.', + category=PydanticDeprecatedSince20, + ) + return self.__pydantic_fields_set__ + + @typing_extensions.deprecated('The `dict` method is deprecated; use `model_dump` instead.', category=None) + def dict( # noqa: D102 + self, + *, + include: IncEx = None, + exclude: IncEx = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> Dict[str, Any]: # noqa UP006 + warnings.warn('The `dict` method is deprecated; use `model_dump` instead.', category=PydanticDeprecatedSince20) + return self.model_dump( + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + @typing_extensions.deprecated('The `json` method is deprecated; use `model_dump_json` instead.', category=None) + def json( # noqa: D102 + self, + *, + include: IncEx = None, + exclude: IncEx = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + encoder: Callable[[Any], Any] | None = PydanticUndefined, # type: ignore[assignment] + models_as_dict: bool = PydanticUndefined, # type: ignore[assignment] + **dumps_kwargs: Any, + ) -> str: + warnings.warn( + 'The `json` method is deprecated; use `model_dump_json` instead.', category=PydanticDeprecatedSince20 + ) + if encoder is not PydanticUndefined: + raise TypeError('The `encoder` argument is no longer supported; use field serializers instead.') + if models_as_dict is not PydanticUndefined: + raise TypeError('The `models_as_dict` argument is no longer supported; use a model serializer instead.') + if dumps_kwargs: + raise TypeError('`dumps_kwargs` keyword arguments are no longer supported.') + return self.model_dump_json( + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + + @classmethod + @typing_extensions.deprecated('The `parse_obj` method is deprecated; use `model_validate` instead.', category=None) + def parse_obj(cls, obj: Any) -> Self: # noqa: D102 + warnings.warn( + 'The `parse_obj` method is deprecated; use `model_validate` instead.', category=PydanticDeprecatedSince20 + ) + return cls.model_validate(obj) + + @classmethod + @typing_extensions.deprecated( + 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' + 'otherwise load the data then use `model_validate` instead.', + category=None, + ) + def parse_raw( # noqa: D102 + cls, + b: str | bytes, + *, + content_type: str | None = None, + encoding: str = 'utf8', + proto: DeprecatedParseProtocol | None = None, + allow_pickle: bool = False, + ) -> Self: # pragma: no cover + warnings.warn( + 'The `parse_raw` method is deprecated; if your data is JSON use `model_validate_json`, ' + 'otherwise load the data then use `model_validate` instead.', + category=PydanticDeprecatedSince20, + ) + from .deprecated import parse + + try: + obj = parse.load_str_bytes( + b, + proto=proto, + content_type=content_type, + encoding=encoding, + allow_pickle=allow_pickle, + ) + except (ValueError, TypeError) as exc: + import json + + # try to match V1 + if isinstance(exc, UnicodeDecodeError): + type_str = 'value_error.unicodedecode' + elif isinstance(exc, json.JSONDecodeError): + type_str = 'value_error.jsondecode' + elif isinstance(exc, ValueError): + type_str = 'value_error' + else: + type_str = 'type_error' + + # ctx is missing here, but since we've added `input` to the error, we're not pretending it's the same + error: pydantic_core.InitErrorDetails = { + # The type: ignore on the next line is to ignore the requirement of LiteralString + 'type': pydantic_core.PydanticCustomError(type_str, str(exc)), # type: ignore + 'loc': ('__root__',), + 'input': b, + } + raise pydantic_core.ValidationError.from_exception_data(cls.__name__, [error]) + return cls.model_validate(obj) + + @classmethod + @typing_extensions.deprecated( + 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON ' + 'use `model_validate_json`, otherwise `model_validate` instead.', + category=None, + ) + def parse_file( # noqa: D102 + cls, + path: str | Path, + *, + content_type: str | None = None, + encoding: str = 'utf8', + proto: DeprecatedParseProtocol | None = None, + allow_pickle: bool = False, + ) -> Self: + warnings.warn( + 'The `parse_file` method is deprecated; load the data from file, then if your data is JSON ' + 'use `model_validate_json`, otherwise `model_validate` instead.', + category=PydanticDeprecatedSince20, + ) + from .deprecated import parse + + obj = parse.load_file( + path, + proto=proto, + content_type=content_type, + encoding=encoding, + allow_pickle=allow_pickle, + ) + return cls.parse_obj(obj) + + @classmethod + @typing_extensions.deprecated( + 'The `from_orm` method is deprecated; set ' + "`model_config['from_attributes']=True` and use `model_validate` instead.", + category=None, + ) + def from_orm(cls, obj: Any) -> Self: # noqa: D102 + warnings.warn( + 'The `from_orm` method is deprecated; set ' + "`model_config['from_attributes']=True` and use `model_validate` instead.", + category=PydanticDeprecatedSince20, + ) + if not cls.model_config.get('from_attributes', None): + raise PydanticUserError( + 'You must set the config attribute `from_attributes=True` to use from_orm', code=None + ) + return cls.model_validate(obj) + + @classmethod + @typing_extensions.deprecated('The `construct` method is deprecated; use `model_construct` instead.', category=None) + def construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self: # noqa: D102 + warnings.warn( + 'The `construct` method is deprecated; use `model_construct` instead.', category=PydanticDeprecatedSince20 + ) + return cls.model_construct(_fields_set=_fields_set, **values) + + @typing_extensions.deprecated( + 'The `copy` method is deprecated; use `model_copy` instead. ' + 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.', + category=None, + ) + def copy( + self, + *, + include: AbstractSetIntStr | MappingIntStrAny | None = None, + exclude: AbstractSetIntStr | MappingIntStrAny | None = None, + update: Dict[str, Any] | None = None, # noqa UP006 + deep: bool = False, + ) -> Self: # pragma: no cover + """Returns a copy of the model. + + !!! warning "Deprecated" + This method is now deprecated; use `model_copy` instead. + + If you need `include` or `exclude`, use: + + ```py + data = self.model_dump(include=include, exclude=exclude, round_trip=True) + data = {**data, **(update or {})} + copied = self.model_validate(data) + ``` + + Args: + include: Optional set or mapping specifying which fields to include in the copied model. + exclude: Optional set or mapping specifying which fields to exclude in the copied model. + update: Optional dictionary of field-value pairs to override field values in the copied model. + deep: If True, the values of fields that are Pydantic models will be deep-copied. + + Returns: + A copy of the model with included, excluded and updated fields as specified. + """ + warnings.warn( + 'The `copy` method is deprecated; use `model_copy` instead. ' + 'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.', + category=PydanticDeprecatedSince20, + ) + from .deprecated import copy_internals + + values = dict( + copy_internals._iter( + self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False + ), + **(update or {}), + ) + if self.__pydantic_private__ is None: + private = None + else: + private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined} + + if self.__pydantic_extra__ is None: + extra: dict[str, Any] | None = None + else: + extra = self.__pydantic_extra__.copy() + for k in list(self.__pydantic_extra__): + if k not in values: # k was in the exclude + extra.pop(k) + for k in list(values): + if k in self.__pydantic_extra__: # k must have come from extra + extra[k] = values.pop(k) + + # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg + if update: + fields_set = self.__pydantic_fields_set__ | update.keys() + else: + fields_set = set(self.__pydantic_fields_set__) + + # removing excluded fields from `__pydantic_fields_set__` + if exclude: + fields_set -= set(exclude) + + return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep) + + @classmethod + @typing_extensions.deprecated('The `schema` method is deprecated; use `model_json_schema` instead.', category=None) + def schema( # noqa: D102 + cls, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE + ) -> Dict[str, Any]: # noqa UP006 + warnings.warn( + 'The `schema` method is deprecated; use `model_json_schema` instead.', category=PydanticDeprecatedSince20 + ) + return cls.model_json_schema(by_alias=by_alias, ref_template=ref_template) + + @classmethod + @typing_extensions.deprecated( + 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.', + category=None, + ) + def schema_json( # noqa: D102 + cls, *, by_alias: bool = True, ref_template: str = DEFAULT_REF_TEMPLATE, **dumps_kwargs: Any + ) -> str: # pragma: no cover + warnings.warn( + 'The `schema_json` method is deprecated; use `model_json_schema` and json.dumps instead.', + category=PydanticDeprecatedSince20, + ) + import json + + from .deprecated.json import pydantic_encoder + + return json.dumps( + cls.model_json_schema(by_alias=by_alias, ref_template=ref_template), + default=pydantic_encoder, + **dumps_kwargs, + ) + + @classmethod + @typing_extensions.deprecated('The `validate` method is deprecated; use `model_validate` instead.', category=None) + def validate(cls, value: Any) -> Self: # noqa: D102 + warnings.warn( + 'The `validate` method is deprecated; use `model_validate` instead.', category=PydanticDeprecatedSince20 + ) + return cls.model_validate(value) + + @classmethod + @typing_extensions.deprecated( + 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.', + category=None, + ) + def update_forward_refs(cls, **localns: Any) -> None: # noqa: D102 + warnings.warn( + 'The `update_forward_refs` method is deprecated; use `model_rebuild` instead.', + category=PydanticDeprecatedSince20, + ) + if localns: # pragma: no cover + raise TypeError('`localns` arguments are not longer accepted.') + cls.model_rebuild(force=True) + + @typing_extensions.deprecated( + 'The private method `_iter` will be removed and should no longer be used.', category=None + ) + def _iter(self, *args: Any, **kwargs: Any) -> Any: + warnings.warn( + 'The private method `_iter` will be removed and should no longer be used.', + category=PydanticDeprecatedSince20, + ) + from .deprecated import copy_internals + + return copy_internals._iter(self, *args, **kwargs) + + @typing_extensions.deprecated( + 'The private method `_copy_and_set_values` will be removed and should no longer be used.', + category=None, + ) + def _copy_and_set_values(self, *args: Any, **kwargs: Any) -> Any: + warnings.warn( + 'The private method `_copy_and_set_values` will be removed and should no longer be used.', + category=PydanticDeprecatedSince20, + ) + from .deprecated import copy_internals + + return copy_internals._copy_and_set_values(self, *args, **kwargs) + + @classmethod + @typing_extensions.deprecated( + 'The private method `_get_value` will be removed and should no longer be used.', + category=None, + ) + def _get_value(cls, *args: Any, **kwargs: Any) -> Any: + warnings.warn( + 'The private method `_get_value` will be removed and should no longer be used.', + category=PydanticDeprecatedSince20, + ) + from .deprecated import copy_internals + + return copy_internals._get_value(cls, *args, **kwargs) + + @typing_extensions.deprecated( + 'The private method `_calculate_keys` will be removed and should no longer be used.', + category=None, + ) + def _calculate_keys(self, *args: Any, **kwargs: Any) -> Any: + warnings.warn( + 'The private method `_calculate_keys` will be removed and should no longer be used.', + category=PydanticDeprecatedSince20, + ) + from .deprecated import copy_internals + + return copy_internals._calculate_keys(self, *args, **kwargs) + + +@overload +def create_model( + model_name: str, + /, + *, + __config__: ConfigDict | None = None, + __doc__: str | None = None, + __base__: None = None, + __module__: str = __name__, + __validators__: dict[str, Callable[..., Any]] | None = None, + __cls_kwargs__: dict[str, Any] | None = None, + **field_definitions: Any, +) -> type[BaseModel]: ... + + +@overload +def create_model( + model_name: str, + /, + *, + __config__: ConfigDict | None = None, + __doc__: str | None = None, + __base__: type[ModelT] | tuple[type[ModelT], ...], + __module__: str = __name__, + __validators__: dict[str, Callable[..., Any]] | None = None, + __cls_kwargs__: dict[str, Any] | None = None, + **field_definitions: Any, +) -> type[ModelT]: ... + + +def create_model( # noqa: C901 + model_name: str, + /, + *, + __config__: ConfigDict | None = None, + __doc__: str | None = None, + __base__: type[ModelT] | tuple[type[ModelT], ...] | None = None, + __module__: str | None = None, + __validators__: dict[str, Callable[..., Any]] | None = None, + __cls_kwargs__: dict[str, Any] | None = None, + __slots__: tuple[str, ...] | None = None, + **field_definitions: Any, +) -> type[ModelT]: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/models/#dynamic-model-creation + + Dynamically creates and returns a new Pydantic model, in other words, `create_model` dynamically creates a + subclass of [`BaseModel`][pydantic.BaseModel]. + + Args: + model_name: The name of the newly created model. + __config__: The configuration of the new model. + __doc__: The docstring of the new model. + __base__: The base class or classes for the new model. + __module__: The name of the module that the model belongs to; + if `None`, the value is taken from `sys._getframe(1)` + __validators__: A dictionary of methods that validate fields. The keys are the names of the validation methods to + be added to the model, and the values are the validation methods themselves. You can read more about functional + validators [here](https://docs.pydantic.dev/2.8/concepts/validators/#field-validators). + __cls_kwargs__: A dictionary of keyword arguments for class creation, such as `metaclass`. + __slots__: Deprecated. Should not be passed to `create_model`. + **field_definitions: Attributes of the new model. They should be passed in the format: + `=(, )`, `=(, )`, or `typing.Annotated[, ]`. + Any additional metadata in `typing.Annotated[, , ...]` will be ignored. + + Returns: + The new [model][pydantic.BaseModel]. + + Raises: + PydanticUserError: If `__base__` and `__config__` are both passed. + """ + if __slots__ is not None: + # __slots__ will be ignored from here on + warnings.warn('__slots__ should not be passed to create_model', RuntimeWarning) + + if __base__ is not None: + if __config__ is not None: + raise PydanticUserError( + 'to avoid confusion `__config__` and `__base__` cannot be used together', + code='create-model-config-base', + ) + if not isinstance(__base__, tuple): + __base__ = (__base__,) + else: + __base__ = (cast('type[ModelT]', BaseModel),) + + __cls_kwargs__ = __cls_kwargs__ or {} + + fields = {} + annotations = {} + + for f_name, f_def in field_definitions.items(): + if not _fields.is_valid_field_name(f_name): + warnings.warn(f'fields may not start with an underscore, ignoring "{f_name}"', RuntimeWarning) + if isinstance(f_def, tuple): + f_def = cast('tuple[str, Any]', f_def) + try: + f_annotation, f_value = f_def + except ValueError as e: + raise PydanticUserError( + 'Field definitions should be a `(, )`.', + code='create-model-field-definitions', + ) from e + + elif _typing_extra.is_annotated(f_def): + (f_annotation, f_value, *_) = typing_extensions.get_args( + f_def + ) # first two input are expected from Annotated, refer to https://docs.python.org/3/library/typing.html#typing.Annotated + from .fields import FieldInfo + + if not isinstance(f_value, FieldInfo): + raise PydanticUserError( + 'Field definitions should be a Annotated[, ]', + code='create-model-field-definitions', + ) + + else: + f_annotation, f_value = None, f_def + + if f_annotation: + annotations[f_name] = f_annotation + fields[f_name] = f_value + + if __module__ is None: + f = sys._getframe(1) + __module__ = f.f_globals['__name__'] + + namespace: dict[str, Any] = {'__annotations__': annotations, '__module__': __module__} + if __doc__: + namespace.update({'__doc__': __doc__}) + if __validators__: + namespace.update(__validators__) + namespace.update(fields) + if __config__: + namespace['model_config'] = _config.ConfigWrapper(__config__).config_dict + resolved_bases = types.resolve_bases(__base__) + meta, ns, kwds = types.prepare_class(model_name, resolved_bases, kwds=__cls_kwargs__) + if resolved_bases is not __base__: + ns['__orig_bases__'] = __base__ + namespace.update(ns) + + return meta( + model_name, + resolved_bases, + namespace, + __pydantic_reset_parent_namespace__=False, + _create_model_module=__module__, + **kwds, + ) + + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/mypy.py b/env/Lib/site-packages/pydantic/mypy.py new file mode 100644 index 0000000..93e29d5 --- /dev/null +++ b/env/Lib/site-packages/pydantic/mypy.py @@ -0,0 +1,1313 @@ +"""This module includes classes and functions designed specifically for use with the mypy plugin.""" + +from __future__ import annotations + +import sys +from configparser import ConfigParser +from typing import Any, Callable, Iterator + +from mypy.errorcodes import ErrorCode +from mypy.expandtype import expand_type, expand_type_by_instance +from mypy.nodes import ( + ARG_NAMED, + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + ARG_STAR2, + INVARIANT, + MDEF, + Argument, + AssignmentStmt, + Block, + CallExpr, + ClassDef, + Context, + Decorator, + DictExpr, + EllipsisExpr, + Expression, + FuncDef, + IfStmt, + JsonDict, + MemberExpr, + NameExpr, + PassStmt, + PlaceholderNode, + RefExpr, + Statement, + StrExpr, + SymbolTableNode, + TempNode, + TypeAlias, + TypeInfo, + Var, +) +from mypy.options import Options +from mypy.plugin import ( + CheckerPluginInterface, + ClassDefContext, + FunctionContext, + MethodContext, + Plugin, + ReportConfigContext, + SemanticAnalyzerPluginInterface, +) +from mypy.plugins import dataclasses +from mypy.plugins.common import ( + deserialize_and_fixup_type, +) +from mypy.semanal import set_callable_name +from mypy.server.trigger import make_wildcard_trigger +from mypy.state import state +from mypy.typeops import map_type_from_supertype +from mypy.types import ( + AnyType, + CallableType, + Instance, + NoneType, + Overloaded, + Type, + TypeOfAny, + TypeType, + TypeVarType, + UnionType, + get_proper_type, +) +from mypy.typevars import fill_typevars +from mypy.util import get_unique_redefinition_name +from mypy.version import __version__ as mypy_version + +from pydantic._internal import _fields +from pydantic.version import parse_mypy_version + +try: + from mypy.types import TypeVarDef # type: ignore[attr-defined] +except ImportError: # pragma: no cover + # Backward-compatible with TypeVarDef from Mypy 0.930. + from mypy.types import TypeVarType as TypeVarDef + +CONFIGFILE_KEY = 'pydantic-mypy' +METADATA_KEY = 'pydantic-mypy-metadata' +BASEMODEL_FULLNAME = 'pydantic.main.BaseModel' +BASESETTINGS_FULLNAME = 'pydantic_settings.main.BaseSettings' +ROOT_MODEL_FULLNAME = 'pydantic.root_model.RootModel' +MODEL_METACLASS_FULLNAME = 'pydantic._internal._model_construction.ModelMetaclass' +FIELD_FULLNAME = 'pydantic.fields.Field' +DATACLASS_FULLNAME = 'pydantic.dataclasses.dataclass' +MODEL_VALIDATOR_FULLNAME = 'pydantic.functional_validators.model_validator' +DECORATOR_FULLNAMES = { + 'pydantic.functional_validators.field_validator', + 'pydantic.functional_validators.model_validator', + 'pydantic.functional_serializers.serializer', + 'pydantic.functional_serializers.model_serializer', + 'pydantic.deprecated.class_validators.validator', + 'pydantic.deprecated.class_validators.root_validator', +} + + +MYPY_VERSION_TUPLE = parse_mypy_version(mypy_version) +BUILTINS_NAME = 'builtins' if MYPY_VERSION_TUPLE >= (0, 930) else '__builtins__' + +# Increment version if plugin changes and mypy caches should be invalidated +__version__ = 2 + + +def plugin(version: str) -> type[Plugin]: + """`version` is the mypy version string. + + We might want to use this to print a warning if the mypy version being used is + newer, or especially older, than we expect (or need). + + Args: + version: The mypy version string. + + Return: + The Pydantic mypy plugin type. + """ + return PydanticPlugin + + +class PydanticPlugin(Plugin): + """The Pydantic mypy plugin.""" + + def __init__(self, options: Options) -> None: + self.plugin_config = PydanticPluginConfig(options) + self._plugin_data = self.plugin_config.to_data() + super().__init__(options) + + def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], bool] | None: + """Update Pydantic model class.""" + sym = self.lookup_fully_qualified(fullname) + if sym and isinstance(sym.node, TypeInfo): # pragma: no branch + # No branching may occur if the mypy cache has not been cleared + if any(base.fullname == BASEMODEL_FULLNAME for base in sym.node.mro): + return self._pydantic_model_class_maker_callback + return None + + def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + """Update Pydantic `ModelMetaclass` definition.""" + if fullname == MODEL_METACLASS_FULLNAME: + return self._pydantic_model_metaclass_marker_callback + return None + + def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None: + """Adjust the return type of the `Field` function.""" + sym = self.lookup_fully_qualified(fullname) + if sym and sym.fullname == FIELD_FULLNAME: + return self._pydantic_field_callback + return None + + def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None: + """Adjust return type of `from_orm` method call.""" + if fullname.endswith('.from_orm'): + return from_attributes_callback + return None + + def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None: + """Mark pydantic.dataclasses as dataclass. + + Mypy version 1.1.1 added support for `@dataclass_transform` decorator. + """ + if fullname == DATACLASS_FULLNAME and MYPY_VERSION_TUPLE < (1, 1): + return dataclasses.dataclass_class_maker_callback # type: ignore[return-value] + return None + + def report_config_data(self, ctx: ReportConfigContext) -> dict[str, Any]: + """Return all plugin config data. + + Used by mypy to determine if cache needs to be discarded. + """ + return self._plugin_data + + def _pydantic_model_class_maker_callback(self, ctx: ClassDefContext) -> bool: + transformer = PydanticModelTransformer(ctx.cls, ctx.reason, ctx.api, self.plugin_config) + return transformer.transform() + + def _pydantic_model_metaclass_marker_callback(self, ctx: ClassDefContext) -> None: + """Reset dataclass_transform_spec attribute of ModelMetaclass. + + Let the plugin handle it. This behavior can be disabled + if 'debug_dataclass_transform' is set to True', for testing purposes. + """ + if self.plugin_config.debug_dataclass_transform: + return + info_metaclass = ctx.cls.info.declared_metaclass + assert info_metaclass, "callback not passed from 'get_metaclass_hook'" + if getattr(info_metaclass.type, 'dataclass_transform_spec', None): + info_metaclass.type.dataclass_transform_spec = None + + def _pydantic_field_callback(self, ctx: FunctionContext) -> Type: + """Extract the type of the `default` argument from the Field function, and use it as the return type. + + In particular: + * Check whether the default and default_factory argument is specified. + * Output an error if both are specified. + * Retrieve the type of the argument which is specified, and use it as return type for the function. + """ + default_any_type = ctx.default_return_type + + assert ctx.callee_arg_names[0] == 'default', '"default" is no longer first argument in Field()' + assert ctx.callee_arg_names[1] == 'default_factory', '"default_factory" is no longer second argument in Field()' + default_args = ctx.args[0] + default_factory_args = ctx.args[1] + + if default_args and default_factory_args: + error_default_and_default_factory_specified(ctx.api, ctx.context) + return default_any_type + + if default_args: + default_type = ctx.arg_types[0][0] + default_arg = default_args[0] + + # Fallback to default Any type if the field is required + if not isinstance(default_arg, EllipsisExpr): + return default_type + + elif default_factory_args: + default_factory_type = ctx.arg_types[1][0] + + # Functions which use `ParamSpec` can be overloaded, exposing the callable's types as a parameter + # Pydantic calls the default factory without any argument, so we retrieve the first item + if isinstance(default_factory_type, Overloaded): + default_factory_type = default_factory_type.items[0] + + if isinstance(default_factory_type, CallableType): + ret_type = default_factory_type.ret_type + # mypy doesn't think `ret_type` has `args`, you'd think mypy should know, + # add this check in case it varies by version + args = getattr(ret_type, 'args', None) + if args: + if all(isinstance(arg, TypeVarType) for arg in args): + # Looks like the default factory is a type like `list` or `dict`, replace all args with `Any` + ret_type.args = tuple(default_any_type for _ in args) # type: ignore[attr-defined] + return ret_type + + return default_any_type + + +class PydanticPluginConfig: + """A Pydantic mypy plugin config holder. + + Attributes: + init_forbid_extra: Whether to add a `**kwargs` at the end of the generated `__init__` signature. + init_typed: Whether to annotate fields in the generated `__init__`. + warn_required_dynamic_aliases: Whether to raise required dynamic aliases error. + debug_dataclass_transform: Whether to not reset `dataclass_transform_spec` attribute + of `ModelMetaclass` for testing purposes. + """ + + __slots__ = ( + 'init_forbid_extra', + 'init_typed', + 'warn_required_dynamic_aliases', + 'debug_dataclass_transform', + ) + init_forbid_extra: bool + init_typed: bool + warn_required_dynamic_aliases: bool + debug_dataclass_transform: bool # undocumented + + def __init__(self, options: Options) -> None: + if options.config_file is None: # pragma: no cover + return + + toml_config = parse_toml(options.config_file) + if toml_config is not None: + config = toml_config.get('tool', {}).get('pydantic-mypy', {}) + for key in self.__slots__: + setting = config.get(key, False) + if not isinstance(setting, bool): + raise ValueError(f'Configuration value must be a boolean for key: {key}') + setattr(self, key, setting) + else: + plugin_config = ConfigParser() + plugin_config.read(options.config_file) + for key in self.__slots__: + setting = plugin_config.getboolean(CONFIGFILE_KEY, key, fallback=False) + setattr(self, key, setting) + + def to_data(self) -> dict[str, Any]: + """Returns a dict of config names to their values.""" + return {key: getattr(self, key) for key in self.__slots__} + + +def from_attributes_callback(ctx: MethodContext) -> Type: + """Raise an error if from_attributes is not enabled.""" + model_type: Instance + ctx_type = ctx.type + if isinstance(ctx_type, TypeType): + ctx_type = ctx_type.item + if isinstance(ctx_type, CallableType) and isinstance(ctx_type.ret_type, Instance): + model_type = ctx_type.ret_type # called on the class + elif isinstance(ctx_type, Instance): + model_type = ctx_type # called on an instance (unusual, but still valid) + else: # pragma: no cover + detail = f'ctx.type: {ctx_type} (of type {ctx_type.__class__.__name__})' + error_unexpected_behavior(detail, ctx.api, ctx.context) + return ctx.default_return_type + pydantic_metadata = model_type.type.metadata.get(METADATA_KEY) + if pydantic_metadata is None: + return ctx.default_return_type + from_attributes = pydantic_metadata.get('config', {}).get('from_attributes') + if from_attributes is not True: + error_from_attributes(model_type.type.name, ctx.api, ctx.context) + return ctx.default_return_type + + +class PydanticModelField: + """Based on mypy.plugins.dataclasses.DataclassAttribute.""" + + def __init__( + self, + name: str, + alias: str | None, + has_dynamic_alias: bool, + has_default: bool, + line: int, + column: int, + type: Type | None, + info: TypeInfo, + ): + self.name = name + self.alias = alias + self.has_dynamic_alias = has_dynamic_alias + self.has_default = has_default + self.line = line + self.column = column + self.type = type + self.info = info + + def to_argument( + self, + current_info: TypeInfo, + typed: bool, + force_optional: bool, + use_alias: bool, + api: SemanticAnalyzerPluginInterface, + force_typevars_invariant: bool, + ) -> Argument: + """Based on mypy.plugins.dataclasses.DataclassAttribute.to_argument.""" + variable = self.to_var(current_info, api, use_alias, force_typevars_invariant) + type_annotation = self.expand_type(current_info, api) if typed else AnyType(TypeOfAny.explicit) + return Argument( + variable=variable, + type_annotation=type_annotation, + initializer=None, + kind=ARG_NAMED_OPT if force_optional or self.has_default else ARG_NAMED, + ) + + def expand_type( + self, current_info: TypeInfo, api: SemanticAnalyzerPluginInterface, force_typevars_invariant: bool = False + ) -> Type | None: + """Based on mypy.plugins.dataclasses.DataclassAttribute.expand_type.""" + # The getattr in the next line is used to prevent errors in legacy versions of mypy without this attribute + if force_typevars_invariant: + # In some cases, mypy will emit an error "Cannot use a covariant type variable as a parameter" + # To prevent that, we add an option to replace typevars with invariant ones while building certain + # method signatures (in particular, `__init__`). There may be a better way to do this, if this causes + # us problems in the future, we should look into why the dataclasses plugin doesn't have this issue. + if isinstance(self.type, TypeVarType): + modified_type = self.type.copy_modified() + modified_type.variance = INVARIANT + self.type = modified_type + + if self.type is not None and getattr(self.info, 'self_type', None) is not None: + # In general, it is not safe to call `expand_type()` during semantic analyzis, + # however this plugin is called very late, so all types should be fully ready. + # Also, it is tricky to avoid eager expansion of Self types here (e.g. because + # we serialize attributes). + with state.strict_optional_set(api.options.strict_optional): + filled_with_typevars = fill_typevars(current_info) + if force_typevars_invariant: + for arg in filled_with_typevars.args: + if isinstance(arg, TypeVarType): + arg.variance = INVARIANT + return expand_type(self.type, {self.info.self_type.id: filled_with_typevars}) + return self.type + + def to_var( + self, + current_info: TypeInfo, + api: SemanticAnalyzerPluginInterface, + use_alias: bool, + force_typevars_invariant: bool = False, + ) -> Var: + """Based on mypy.plugins.dataclasses.DataclassAttribute.to_var.""" + if use_alias and self.alias is not None: + name = self.alias + else: + name = self.name + + return Var(name, self.expand_type(current_info, api, force_typevars_invariant)) + + def serialize(self) -> JsonDict: + """Based on mypy.plugins.dataclasses.DataclassAttribute.serialize.""" + assert self.type + return { + 'name': self.name, + 'alias': self.alias, + 'has_dynamic_alias': self.has_dynamic_alias, + 'has_default': self.has_default, + 'line': self.line, + 'column': self.column, + 'type': self.type.serialize(), + } + + @classmethod + def deserialize(cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface) -> PydanticModelField: + """Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize.""" + data = data.copy() + typ = deserialize_and_fixup_type(data.pop('type'), api) + return cls(type=typ, info=info, **data) + + def expand_typevar_from_subtype(self, sub_type: TypeInfo, api: SemanticAnalyzerPluginInterface) -> None: + """Expands type vars in the context of a subtype when an attribute is inherited + from a generic super type. + """ + if self.type is not None: + with state.strict_optional_set(api.options.strict_optional): + self.type = map_type_from_supertype(self.type, sub_type, self.info) + + +class PydanticModelClassVar: + """Based on mypy.plugins.dataclasses.DataclassAttribute. + + ClassVars are ignored by subclasses. + + Attributes: + name: the ClassVar name + """ + + def __init__(self, name): + self.name = name + + @classmethod + def deserialize(cls, data: JsonDict) -> PydanticModelClassVar: + """Based on mypy.plugins.dataclasses.DataclassAttribute.deserialize.""" + data = data.copy() + return cls(**data) + + def serialize(self) -> JsonDict: + """Based on mypy.plugins.dataclasses.DataclassAttribute.serialize.""" + return { + 'name': self.name, + } + + +class PydanticModelTransformer: + """Transform the BaseModel subclass according to the plugin settings. + + Attributes: + tracked_config_fields: A set of field configs that the plugin has to track their value. + """ + + tracked_config_fields: set[str] = { + 'extra', + 'frozen', + 'from_attributes', + 'populate_by_name', + 'alias_generator', + } + + def __init__( + self, + cls: ClassDef, + reason: Expression | Statement, + api: SemanticAnalyzerPluginInterface, + plugin_config: PydanticPluginConfig, + ) -> None: + self._cls = cls + self._reason = reason + self._api = api + + self.plugin_config = plugin_config + + def transform(self) -> bool: + """Configures the BaseModel subclass according to the plugin settings. + + In particular: + + * determines the model config and fields, + * adds a fields-aware signature for the initializer and construct methods + * freezes the class if frozen = True + * stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses + """ + info = self._cls.info + is_root_model = any(ROOT_MODEL_FULLNAME in base.fullname for base in info.mro[:-1]) + config = self.collect_config() + fields, class_vars = self.collect_fields_and_class_vars(config, is_root_model) + if fields is None or class_vars is None: + # Some definitions are not ready. We need another pass. + return False + for field in fields: + if field.type is None: + return False + + is_settings = any(base.fullname == BASESETTINGS_FULLNAME for base in info.mro[:-1]) + self.add_initializer(fields, config, is_settings, is_root_model) + if not is_root_model: + self.add_model_construct_method(fields, config, is_settings) + self.set_frozen(fields, self._api, frozen=config.frozen is True) + + self.adjust_decorator_signatures() + + info.metadata[METADATA_KEY] = { + 'fields': {field.name: field.serialize() for field in fields}, + 'class_vars': {class_var.name: class_var.serialize() for class_var in class_vars}, + 'config': config.get_values_dict(), + } + + return True + + def adjust_decorator_signatures(self) -> None: + """When we decorate a function `f` with `pydantic.validator(...)`, `pydantic.field_validator` + or `pydantic.serializer(...)`, mypy sees `f` as a regular method taking a `self` instance, + even though pydantic internally wraps `f` with `classmethod` if necessary. + + Teach mypy this by marking any function whose outermost decorator is a `validator()`, + `field_validator()` or `serializer()` call as a `classmethod`. + """ + for name, sym in self._cls.info.names.items(): + if isinstance(sym.node, Decorator): + first_dec = sym.node.original_decorators[0] + if ( + isinstance(first_dec, CallExpr) + and isinstance(first_dec.callee, NameExpr) + and first_dec.callee.fullname in DECORATOR_FULLNAMES + # @model_validator(mode="after") is an exception, it expects a regular method + and not ( + first_dec.callee.fullname == MODEL_VALIDATOR_FULLNAME + and any( + first_dec.arg_names[i] == 'mode' and isinstance(arg, StrExpr) and arg.value == 'after' + for i, arg in enumerate(first_dec.args) + ) + ) + ): + # TODO: Only do this if the first argument of the decorated function is `cls` + sym.node.func.is_class = True + + def collect_config(self) -> ModelConfigData: # noqa: C901 (ignore complexity) + """Collects the values of the config attributes that are used by the plugin, accounting for parent classes.""" + cls = self._cls + config = ModelConfigData() + + has_config_kwargs = False + has_config_from_namespace = False + + # Handle `class MyModel(BaseModel, =, ...):` + for name, expr in cls.keywords.items(): + config_data = self.get_config_update(name, expr) + if config_data: + has_config_kwargs = True + config.update(config_data) + + # Handle `model_config` + stmt: Statement | None = None + for stmt in cls.defs.body: + if not isinstance(stmt, (AssignmentStmt, ClassDef)): + continue + + if isinstance(stmt, AssignmentStmt): + lhs = stmt.lvalues[0] + if not isinstance(lhs, NameExpr) or lhs.name != 'model_config': + continue + + if isinstance(stmt.rvalue, CallExpr): # calls to `dict` or `ConfigDict` + for arg_name, arg in zip(stmt.rvalue.arg_names, stmt.rvalue.args): + if arg_name is None: + continue + config.update(self.get_config_update(arg_name, arg, lax_extra=True)) + elif isinstance(stmt.rvalue, DictExpr): # dict literals + for key_expr, value_expr in stmt.rvalue.items: + if not isinstance(key_expr, StrExpr): + continue + config.update(self.get_config_update(key_expr.value, value_expr)) + + elif isinstance(stmt, ClassDef): + if stmt.name != 'Config': # 'deprecated' Config-class + continue + for substmt in stmt.defs.body: + if not isinstance(substmt, AssignmentStmt): + continue + lhs = substmt.lvalues[0] + if not isinstance(lhs, NameExpr): + continue + config.update(self.get_config_update(lhs.name, substmt.rvalue)) + + if has_config_kwargs: + self._api.fail( + 'Specifying config in two places is ambiguous, use either Config attribute or class kwargs', + cls, + ) + break + + has_config_from_namespace = True + + if has_config_kwargs or has_config_from_namespace: + if ( + stmt + and config.has_alias_generator + and not config.populate_by_name + and self.plugin_config.warn_required_dynamic_aliases + ): + error_required_dynamic_aliases(self._api, stmt) + + for info in cls.info.mro[1:]: # 0 is the current class + if METADATA_KEY not in info.metadata: + continue + + # Each class depends on the set of fields in its ancestors + self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname)) + for name, value in info.metadata[METADATA_KEY]['config'].items(): + config.setdefault(name, value) + return config + + def collect_fields_and_class_vars( + self, model_config: ModelConfigData, is_root_model: bool + ) -> tuple[list[PydanticModelField] | None, list[PydanticModelClassVar] | None]: + """Collects the fields for the model, accounting for parent classes.""" + cls = self._cls + + # First, collect fields and ClassVars belonging to any class in the MRO, ignoring duplicates. + # + # We iterate through the MRO in reverse because attrs defined in the parent must appear + # earlier in the attributes list than attrs defined in the child. See: + # https://docs.python.org/3/library/dataclasses.html#inheritance + # + # However, we also want fields defined in the subtype to override ones defined + # in the parent. We can implement this via a dict without disrupting the attr order + # because dicts preserve insertion order in Python 3.7+. + found_fields: dict[str, PydanticModelField] = {} + found_class_vars: dict[str, PydanticModelClassVar] = {} + for info in reversed(cls.info.mro[1:-1]): # 0 is the current class, -2 is BaseModel, -1 is object + # if BASEMODEL_METADATA_TAG_KEY in info.metadata and BASEMODEL_METADATA_KEY not in info.metadata: + # # We haven't processed the base class yet. Need another pass. + # return None, None + if METADATA_KEY not in info.metadata: + continue + + # Each class depends on the set of attributes in its dataclass ancestors. + self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname)) + + for name, data in info.metadata[METADATA_KEY]['fields'].items(): + field = PydanticModelField.deserialize(info, data, self._api) + # (The following comment comes directly from the dataclasses plugin) + # TODO: We shouldn't be performing type operations during the main + # semantic analysis pass, since some TypeInfo attributes might + # still be in flux. This should be performed in a later phase. + field.expand_typevar_from_subtype(cls.info, self._api) + found_fields[name] = field + + sym_node = cls.info.names.get(name) + if sym_node and sym_node.node and not isinstance(sym_node.node, Var): + self._api.fail( + 'BaseModel field may only be overridden by another field', + sym_node.node, + ) + # Collect ClassVars + for name, data in info.metadata[METADATA_KEY]['class_vars'].items(): + found_class_vars[name] = PydanticModelClassVar.deserialize(data) + + # Second, collect fields and ClassVars belonging to the current class. + current_field_names: set[str] = set() + current_class_vars_names: set[str] = set() + for stmt in self._get_assignment_statements_from_block(cls.defs): + maybe_field = self.collect_field_or_class_var_from_stmt(stmt, model_config, found_class_vars) + if isinstance(maybe_field, PydanticModelField): + lhs = stmt.lvalues[0] + if is_root_model and lhs.name != 'root': + error_extra_fields_on_root_model(self._api, stmt) + else: + current_field_names.add(lhs.name) + found_fields[lhs.name] = maybe_field + elif isinstance(maybe_field, PydanticModelClassVar): + lhs = stmt.lvalues[0] + current_class_vars_names.add(lhs.name) + found_class_vars[lhs.name] = maybe_field + + return list(found_fields.values()), list(found_class_vars.values()) + + def _get_assignment_statements_from_if_statement(self, stmt: IfStmt) -> Iterator[AssignmentStmt]: + for body in stmt.body: + if not body.is_unreachable: + yield from self._get_assignment_statements_from_block(body) + if stmt.else_body is not None and not stmt.else_body.is_unreachable: + yield from self._get_assignment_statements_from_block(stmt.else_body) + + def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]: + for stmt in block.body: + if isinstance(stmt, AssignmentStmt): + yield stmt + elif isinstance(stmt, IfStmt): + yield from self._get_assignment_statements_from_if_statement(stmt) + + def collect_field_or_class_var_from_stmt( # noqa C901 + self, stmt: AssignmentStmt, model_config: ModelConfigData, class_vars: dict[str, PydanticModelClassVar] + ) -> PydanticModelField | PydanticModelClassVar | None: + """Get pydantic model field from statement. + + Args: + stmt: The statement. + model_config: Configuration settings for the model. + class_vars: ClassVars already known to be defined on the model. + + Returns: + A pydantic model field if it could find the field in statement. Otherwise, `None`. + """ + cls = self._cls + + lhs = stmt.lvalues[0] + if not isinstance(lhs, NameExpr) or not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config': + return None + + if not stmt.new_syntax: + if ( + isinstance(stmt.rvalue, CallExpr) + and isinstance(stmt.rvalue.callee, CallExpr) + and isinstance(stmt.rvalue.callee.callee, NameExpr) + and stmt.rvalue.callee.callee.fullname in DECORATOR_FULLNAMES + ): + # This is a (possibly-reused) validator or serializer, not a field + # In particular, it looks something like: my_validator = validator('my_field')(f) + # Eventually, we may want to attempt to respect model_config['ignored_types'] + return None + + if lhs.name in class_vars: + # Class vars are not fields and are not required to be annotated + return None + + # The assignment does not have an annotation, and it's not anything else we recognize + error_untyped_fields(self._api, stmt) + return None + + lhs = stmt.lvalues[0] + if not isinstance(lhs, NameExpr): + return None + + if not _fields.is_valid_field_name(lhs.name) or lhs.name == 'model_config': + return None + + sym = cls.info.names.get(lhs.name) + if sym is None: # pragma: no cover + # This is likely due to a star import (see the dataclasses plugin for a more detailed explanation) + # This is the same logic used in the dataclasses plugin + return None + + node = sym.node + if isinstance(node, PlaceholderNode): # pragma: no cover + # See the PlaceholderNode docstring for more detail about how this can occur + # Basically, it is an edge case when dealing with complex import logic + + # The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does.. + return None + + if isinstance(node, TypeAlias): + self._api.fail( + 'Type aliases inside BaseModel definitions are not supported at runtime', + node, + ) + # Skip processing this node. This doesn't match the runtime behaviour, + # but the only alternative would be to modify the SymbolTable, + # and it's a little hairy to do that in a plugin. + return None + + if not isinstance(node, Var): # pragma: no cover + # Don't know if this edge case still happens with the `is_valid_field` check above + # but better safe than sorry + + # The dataclasses plugin now asserts this cannot happen, but I'd rather not error if it does.. + return None + + # x: ClassVar[int] is not a field + if node.is_classvar: + return PydanticModelClassVar(lhs.name) + + # x: InitVar[int] is not supported in BaseModel + node_type = get_proper_type(node.type) + if isinstance(node_type, Instance) and node_type.type.fullname == 'dataclasses.InitVar': + self._api.fail( + 'InitVar is not supported in BaseModel', + node, + ) + + has_default = self.get_has_default(stmt) + + if sym.type is None and node.is_final and node.is_inferred: + # This follows the logic from the dataclasses plugin. The following comment is taken verbatim: + # + # This is a special case, assignment like x: Final = 42 is classified + # annotated above, but mypy strips the `Final` turning it into x = 42. + # We do not support inferred types in dataclasses, so we can try inferring + # type for simple literals, and otherwise require an explicit type + # argument for Final[...]. + typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True) + if typ: + node.type = typ + else: + self._api.fail( + 'Need type argument for Final[...] with non-literal default in BaseModel', + stmt, + ) + node.type = AnyType(TypeOfAny.from_error) + + alias, has_dynamic_alias = self.get_alias_info(stmt) + if has_dynamic_alias and not model_config.populate_by_name and self.plugin_config.warn_required_dynamic_aliases: + error_required_dynamic_aliases(self._api, stmt) + + init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt) + return PydanticModelField( + name=lhs.name, + has_dynamic_alias=has_dynamic_alias, + has_default=has_default, + alias=alias, + line=stmt.line, + column=stmt.column, + type=init_type, + info=cls.info, + ) + + def _infer_dataclass_attr_init_type(self, sym: SymbolTableNode, name: str, context: Context) -> Type | None: + """Infer __init__ argument type for an attribute. + + In particular, possibly use the signature of __set__. + """ + default = sym.type + if sym.implicit: + return default + t = get_proper_type(sym.type) + + # Perform a simple-minded inference from the signature of __set__, if present. + # We can't use mypy.checkmember here, since this plugin runs before type checking. + # We only support some basic scanerios here, which is hopefully sufficient for + # the vast majority of use cases. + if not isinstance(t, Instance): + return default + setter = t.type.get('__set__') + if setter: + if isinstance(setter.node, FuncDef): + super_info = t.type.get_containing_type_info('__set__') + assert super_info + if setter.type: + setter_type = get_proper_type(map_type_from_supertype(setter.type, t.type, super_info)) + else: + return AnyType(TypeOfAny.unannotated) + if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [ + ARG_POS, + ARG_POS, + ARG_POS, + ]: + return expand_type_by_instance(setter_type.arg_types[2], t) + else: + self._api.fail(f'Unsupported signature for "__set__" in "{t.type.name}"', context) + else: + self._api.fail(f'Unsupported "__set__" in "{t.type.name}"', context) + + return default + + def add_initializer( + self, fields: list[PydanticModelField], config: ModelConfigData, is_settings: bool, is_root_model: bool + ) -> None: + """Adds a fields-aware `__init__` method to the class. + + The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings. + """ + if '__init__' in self._cls.info.names and not self._cls.info.names['__init__'].plugin_generated: + return # Don't generate an __init__ if one already exists + + typed = self.plugin_config.init_typed + use_alias = config.populate_by_name is not True + requires_dynamic_aliases = bool(config.has_alias_generator and not config.populate_by_name) + args = self.get_field_arguments( + fields, + typed=typed, + requires_dynamic_aliases=requires_dynamic_aliases, + use_alias=use_alias, + is_settings=is_settings, + force_typevars_invariant=True, + ) + + if is_root_model and MYPY_VERSION_TUPLE <= (1, 0, 1): + # convert root argument to positional argument + # This is needed because mypy support for `dataclass_transform` isn't complete on 1.0.1 + args[0].kind = ARG_POS if args[0].kind == ARG_NAMED else ARG_OPT + + if is_settings: + base_settings_node = self._api.lookup_fully_qualified(BASESETTINGS_FULLNAME).node + if '__init__' in base_settings_node.names: + base_settings_init_node = base_settings_node.names['__init__'].node + if base_settings_init_node is not None and base_settings_init_node.type is not None: + func_type = base_settings_init_node.type + for arg_idx, arg_name in enumerate(func_type.arg_names): + if arg_name.startswith('__') or not arg_name.startswith('_'): + continue + analyzed_variable_type = self._api.anal_type(func_type.arg_types[arg_idx]) + variable = Var(arg_name, analyzed_variable_type) + args.append(Argument(variable, analyzed_variable_type, None, ARG_OPT)) + + if not self.should_init_forbid_extra(fields, config): + var = Var('kwargs') + args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2)) + + add_method(self._api, self._cls, '__init__', args=args, return_type=NoneType()) + + def add_model_construct_method( + self, fields: list[PydanticModelField], config: ModelConfigData, is_settings: bool + ) -> None: + """Adds a fully typed `model_construct` classmethod to the class. + + Similar to the fields-aware __init__ method, but always uses the field names (not aliases), + and does not treat settings fields as optional. + """ + set_str = self._api.named_type(f'{BUILTINS_NAME}.set', [self._api.named_type(f'{BUILTINS_NAME}.str')]) + optional_set_str = UnionType([set_str, NoneType()]) + fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT) + with state.strict_optional_set(self._api.options.strict_optional): + args = self.get_field_arguments( + fields, typed=True, requires_dynamic_aliases=False, use_alias=False, is_settings=is_settings + ) + if not self.should_init_forbid_extra(fields, config): + var = Var('kwargs') + args.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2)) + + args = [fields_set_argument] + args + + add_method( + self._api, + self._cls, + 'model_construct', + args=args, + return_type=fill_typevars(self._cls.info), + is_classmethod=True, + ) + + def set_frozen(self, fields: list[PydanticModelField], api: SemanticAnalyzerPluginInterface, frozen: bool) -> None: + """Marks all fields as properties so that attempts to set them trigger mypy errors. + + This is the same approach used by the attrs and dataclasses plugins. + """ + info = self._cls.info + for field in fields: + sym_node = info.names.get(field.name) + if sym_node is not None: + var = sym_node.node + if isinstance(var, Var): + var.is_property = frozen + elif isinstance(var, PlaceholderNode) and not self._api.final_iteration: + # See https://github.com/pydantic/pydantic/issues/5191 to hit this branch for test coverage + self._api.defer() + else: # pragma: no cover + # I don't know whether it's possible to hit this branch, but I've added it for safety + try: + var_str = str(var) + except TypeError: + # This happens for PlaceholderNode; perhaps it will happen for other types in the future.. + var_str = repr(var) + detail = f'sym_node.node: {var_str} (of type {var.__class__})' + error_unexpected_behavior(detail, self._api, self._cls) + else: + var = field.to_var(info, api, use_alias=False) + var.info = info + var.is_property = frozen + var._fullname = info.fullname + '.' + var.name + info.names[var.name] = SymbolTableNode(MDEF, var) + + def get_config_update(self, name: str, arg: Expression, lax_extra: bool = False) -> ModelConfigData | None: + """Determines the config update due to a single kwarg in the ConfigDict definition. + + Warns if a tracked config attribute is set to a value the plugin doesn't know how to interpret (e.g., an int) + """ + if name not in self.tracked_config_fields: + return None + if name == 'extra': + if isinstance(arg, StrExpr): + forbid_extra = arg.value == 'forbid' + elif isinstance(arg, MemberExpr): + forbid_extra = arg.name == 'forbid' + else: + if not lax_extra: + # Only emit an error for other types of `arg` (e.g., `NameExpr`, `ConditionalExpr`, etc.) when + # reading from a config class, etc. If a ConfigDict is used, then we don't want to emit an error + # because you'll get type checking from the ConfigDict itself. + # + # It would be nice if we could introspect the types better otherwise, but I don't know what the API + # is to evaluate an expr into its type and then check if that type is compatible with the expected + # type. Note that you can still get proper type checking via: `model_config = ConfigDict(...)`, just + # if you don't use an explicit string, the plugin won't be able to infer whether extra is forbidden. + error_invalid_config_value(name, self._api, arg) + return None + return ModelConfigData(forbid_extra=forbid_extra) + if name == 'alias_generator': + has_alias_generator = True + if isinstance(arg, NameExpr) and arg.fullname == 'builtins.None': + has_alias_generator = False + return ModelConfigData(has_alias_generator=has_alias_generator) + if isinstance(arg, NameExpr) and arg.fullname in ('builtins.True', 'builtins.False'): + return ModelConfigData(**{name: arg.fullname == 'builtins.True'}) + error_invalid_config_value(name, self._api, arg) + return None + + @staticmethod + def get_has_default(stmt: AssignmentStmt) -> bool: + """Returns a boolean indicating whether the field defined in `stmt` is a required field.""" + expr = stmt.rvalue + if isinstance(expr, TempNode): + # TempNode means annotation-only, so has no default + return False + if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME: + # The "default value" is a call to `Field`; at this point, the field has a default if and only if: + # * there is a positional argument that is not `...` + # * there is a keyword argument named "default" that is not `...` + # * there is a "default_factory" that is not `None` + for arg, name in zip(expr.args, expr.arg_names): + # If name is None, then this arg is the default because it is the only positional argument. + if name is None or name == 'default': + return arg.__class__ is not EllipsisExpr + if name == 'default_factory': + return not (isinstance(arg, NameExpr) and arg.fullname == 'builtins.None') + return False + # Has no default if the "default value" is Ellipsis (i.e., `field_name: Annotation = ...`) + return not isinstance(expr, EllipsisExpr) + + @staticmethod + def get_alias_info(stmt: AssignmentStmt) -> tuple[str | None, bool]: + """Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in `stmt`. + + `has_dynamic_alias` is True if and only if an alias is provided, but not as a string literal. + If `has_dynamic_alias` is True, `alias` will be None. + """ + expr = stmt.rvalue + if isinstance(expr, TempNode): + # TempNode means annotation-only + return None, False + + if not ( + isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME + ): + # Assigned value is not a call to pydantic.fields.Field + return None, False + + for i, arg_name in enumerate(expr.arg_names): + if arg_name != 'alias': + continue + arg = expr.args[i] + if isinstance(arg, StrExpr): + return arg.value, False + else: + return None, True + return None, False + + def get_field_arguments( + self, + fields: list[PydanticModelField], + typed: bool, + use_alias: bool, + requires_dynamic_aliases: bool, + is_settings: bool, + force_typevars_invariant: bool = False, + ) -> list[Argument]: + """Helper function used during the construction of the `__init__` and `model_construct` method signatures. + + Returns a list of mypy Argument instances for use in the generated signatures. + """ + info = self._cls.info + arguments = [ + field.to_argument( + info, + typed=typed, + force_optional=requires_dynamic_aliases or is_settings, + use_alias=use_alias, + api=self._api, + force_typevars_invariant=force_typevars_invariant, + ) + for field in fields + if not (use_alias and field.has_dynamic_alias) + ] + return arguments + + def should_init_forbid_extra(self, fields: list[PydanticModelField], config: ModelConfigData) -> bool: + """Indicates whether the generated `__init__` should get a `**kwargs` at the end of its signature. + + We disallow arbitrary kwargs if the extra config setting is "forbid", or if the plugin config says to, + *unless* a required dynamic alias is present (since then we can't determine a valid signature). + """ + if not config.populate_by_name: + if self.is_dynamic_alias_present(fields, bool(config.has_alias_generator)): + return False + if config.forbid_extra: + return True + return self.plugin_config.init_forbid_extra + + @staticmethod + def is_dynamic_alias_present(fields: list[PydanticModelField], has_alias_generator: bool) -> bool: + """Returns whether any fields on the model have a "dynamic alias", i.e., an alias that cannot be + determined during static analysis. + """ + for field in fields: + if field.has_dynamic_alias: + return True + if has_alias_generator: + for field in fields: + if field.alias is None: + return True + return False + + +class ModelConfigData: + """Pydantic mypy plugin model config class.""" + + def __init__( + self, + forbid_extra: bool | None = None, + frozen: bool | None = None, + from_attributes: bool | None = None, + populate_by_name: bool | None = None, + has_alias_generator: bool | None = None, + ): + self.forbid_extra = forbid_extra + self.frozen = frozen + self.from_attributes = from_attributes + self.populate_by_name = populate_by_name + self.has_alias_generator = has_alias_generator + + def get_values_dict(self) -> dict[str, Any]: + """Returns a dict of Pydantic model config names to their values. + + It includes the config if config value is not `None`. + """ + return {k: v for k, v in self.__dict__.items() if v is not None} + + def update(self, config: ModelConfigData | None) -> None: + """Update Pydantic model config values.""" + if config is None: + return + for k, v in config.get_values_dict().items(): + setattr(self, k, v) + + def setdefault(self, key: str, value: Any) -> None: + """Set default value for Pydantic model config if config value is `None`.""" + if getattr(self, key) is None: + setattr(self, key, value) + + +ERROR_ORM = ErrorCode('pydantic-orm', 'Invalid from_attributes call', 'Pydantic') +ERROR_CONFIG = ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic') +ERROR_ALIAS = ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic') +ERROR_UNEXPECTED = ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic') +ERROR_UNTYPED = ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic') +ERROR_FIELD_DEFAULTS = ErrorCode('pydantic-field', 'Invalid Field defaults', 'Pydantic') +ERROR_EXTRA_FIELD_ROOT_MODEL = ErrorCode('pydantic-field', 'Extra field on RootModel subclass', 'Pydantic') + + +def error_from_attributes(model_name: str, api: CheckerPluginInterface, context: Context) -> None: + """Emits an error when the model does not have `from_attributes=True`.""" + api.fail(f'"{model_name}" does not have from_attributes=True', context, code=ERROR_ORM) + + +def error_invalid_config_value(name: str, api: SemanticAnalyzerPluginInterface, context: Context) -> None: + """Emits an error when the config value is invalid.""" + api.fail(f'Invalid value for "Config.{name}"', context, code=ERROR_CONFIG) + + +def error_required_dynamic_aliases(api: SemanticAnalyzerPluginInterface, context: Context) -> None: + """Emits required dynamic aliases error. + + This will be called when `warn_required_dynamic_aliases=True`. + """ + api.fail('Required dynamic aliases disallowed', context, code=ERROR_ALIAS) + + +def error_unexpected_behavior( + detail: str, api: CheckerPluginInterface | SemanticAnalyzerPluginInterface, context: Context +) -> None: # pragma: no cover + """Emits unexpected behavior error.""" + # Can't think of a good way to test this, but I confirmed it renders as desired by adding to a non-error path + link = 'https://github.com/pydantic/pydantic/issues/new/choose' + full_message = f'The pydantic mypy plugin ran into unexpected behavior: {detail}\n' + full_message += f'Please consider reporting this bug at {link} so we can try to fix it!' + api.fail(full_message, context, code=ERROR_UNEXPECTED) + + +def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None: + """Emits an error when there is an untyped field in the model.""" + api.fail('Untyped fields disallowed', context, code=ERROR_UNTYPED) + + +def error_extra_fields_on_root_model(api: CheckerPluginInterface, context: Context) -> None: + """Emits an error when there is more than just a root field defined for a subclass of RootModel.""" + api.fail('Only `root` is allowed as a field of a `RootModel`', context, code=ERROR_EXTRA_FIELD_ROOT_MODEL) + + +def error_default_and_default_factory_specified(api: CheckerPluginInterface, context: Context) -> None: + """Emits an error when `Field` has both `default` and `default_factory` together.""" + api.fail('Field default and default_factory cannot be specified together', context, code=ERROR_FIELD_DEFAULTS) + + +def add_method( + api: SemanticAnalyzerPluginInterface | CheckerPluginInterface, + cls: ClassDef, + name: str, + args: list[Argument], + return_type: Type, + self_type: Type | None = None, + tvar_def: TypeVarDef | None = None, + is_classmethod: bool = False, +) -> None: + """Very closely related to `mypy.plugins.common.add_method_to_class`, with a few pydantic-specific changes.""" + info = cls.info + + # First remove any previously generated methods with the same name + # to avoid clashes and problems in the semantic analyzer. + if name in info.names: + sym = info.names[name] + if sym.plugin_generated and isinstance(sym.node, FuncDef): + cls.defs.body.remove(sym.node) # pragma: no cover + + if isinstance(api, SemanticAnalyzerPluginInterface): + function_type = api.named_type('builtins.function') + else: + function_type = api.named_generic_type('builtins.function', []) + + if is_classmethod: + self_type = self_type or TypeType(fill_typevars(info)) + first = [Argument(Var('_cls'), self_type, None, ARG_POS, True)] + else: + self_type = self_type or fill_typevars(info) + # `self` is positional *ONLY* here, but this can't be expressed + # fully in the mypy internal API. ARG_POS is the closest we can get. + # Using ARG_POS will, however, give mypy errors if a `self` field + # is present on a model: + # + # Name "self" already defined (possibly by an import) [no-redef] + # + # As a workaround, we give this argument a name that will + # never conflict. By its positional nature, this name will not + # be used or exposed to users. + first = [Argument(Var('__pydantic_self__'), self_type, None, ARG_POS)] + args = first + args + + arg_types, arg_names, arg_kinds = [], [], [] + for arg in args: + assert arg.type_annotation, 'All arguments must be fully typed.' + arg_types.append(arg.type_annotation) + arg_names.append(arg.variable.name) + arg_kinds.append(arg.kind) + + signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) + if tvar_def: + signature.variables = [tvar_def] + + func = FuncDef(name, args, Block([PassStmt()])) + func.info = info + func.type = set_callable_name(signature, func) + func.is_class = is_classmethod + func._fullname = info.fullname + '.' + name + func.line = info.line + + # NOTE: we would like the plugin generated node to dominate, but we still + # need to keep any existing definitions so they get semantically analyzed. + if name in info.names: + # Get a nice unique name instead. + r_name = get_unique_redefinition_name(name, info.names) + info.names[r_name] = info.names[name] + + # Add decorator for is_classmethod + # The dataclasses plugin claims this is unnecessary for classmethods, but not including it results in a + # signature incompatible with the superclass, which causes mypy errors to occur for every subclass of BaseModel. + if is_classmethod: + func.is_decorated = True + v = Var(name, func.type) + v.info = info + v._fullname = func._fullname + v.is_classmethod = True + dec = Decorator(func, [NameExpr('classmethod')], v) + dec.line = info.line + sym = SymbolTableNode(MDEF, dec) + else: + sym = SymbolTableNode(MDEF, func) + sym.plugin_generated = True + info.names[name] = sym + + info.defn.defs.body.append(func) + + +def parse_toml(config_file: str) -> dict[str, Any] | None: + """Returns a dict of config keys to values. + + It reads configs from toml file and returns `None` if the file is not a toml file. + """ + if not config_file.endswith('.toml'): + return None + + if sys.version_info >= (3, 11): + import tomllib as toml_ + else: + try: + import tomli as toml_ + except ImportError: # pragma: no cover + import warnings + + warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.') + return None + + with open(config_file, 'rb') as rf: + return toml_.load(rf) diff --git a/env/Lib/site-packages/pydantic/networks.py b/env/Lib/site-packages/pydantic/networks.py new file mode 100644 index 0000000..830ab39 --- /dev/null +++ b/env/Lib/site-packages/pydantic/networks.py @@ -0,0 +1,761 @@ +"""The networks module contains types for common network-related fields.""" + +from __future__ import annotations as _annotations + +import dataclasses as _dataclasses +import re +from importlib.metadata import version +from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network +from typing import TYPE_CHECKING, Any + +from pydantic_core import MultiHostUrl, PydanticCustomError, Url, core_schema +from typing_extensions import Annotated, Self, TypeAlias + +from ._internal import _fields, _repr, _schema_generation_shared +from ._migration import getattr_migration +from .annotated_handlers import GetCoreSchemaHandler +from .json_schema import JsonSchemaValue + +if TYPE_CHECKING: + import email_validator + + NetworkType: TypeAlias = 'str | bytes | int | tuple[str | bytes | int, str | int]' + +else: + email_validator = None + + +__all__ = [ + 'AnyUrl', + 'AnyHttpUrl', + 'FileUrl', + 'FtpUrl', + 'HttpUrl', + 'WebsocketUrl', + 'AnyWebsocketUrl', + 'UrlConstraints', + 'EmailStr', + 'NameEmail', + 'IPvAnyAddress', + 'IPvAnyInterface', + 'IPvAnyNetwork', + 'PostgresDsn', + 'CockroachDsn', + 'AmqpDsn', + 'RedisDsn', + 'MongoDsn', + 'KafkaDsn', + 'NatsDsn', + 'validate_email', + 'MySQLDsn', + 'MariaDBDsn', + 'ClickHouseDsn', +] + + +@_dataclasses.dataclass +class UrlConstraints(_fields.PydanticMetadata): + """Url constraints. + + Attributes: + max_length: The maximum length of the url. Defaults to `None`. + allowed_schemes: The allowed schemes. Defaults to `None`. + host_required: Whether the host is required. Defaults to `None`. + default_host: The default host. Defaults to `None`. + default_port: The default port. Defaults to `None`. + default_path: The default path. Defaults to `None`. + """ + + max_length: int | None = None + allowed_schemes: list[str] | None = None + host_required: bool | None = None + default_host: str | None = None + default_port: int | None = None + default_path: str | None = None + + def __hash__(self) -> int: + return hash( + ( + self.max_length, + tuple(self.allowed_schemes) if self.allowed_schemes is not None else None, + self.host_required, + self.default_host, + self.default_port, + self.default_path, + ) + ) + + +AnyUrl = Url +"""Base type for all URLs. + +* Any scheme allowed +* Top-level domain (TLD) not required +* Host required + +Assuming an input URL of `http://samuel:pass@example.com:8000/the/path/?query=here#fragment=is;this=bit`, +the types export the following properties: + +- `scheme`: the URL scheme (`http`), always set. +- `host`: the URL host (`example.com`), always set. +- `username`: optional username if included (`samuel`). +- `password`: optional password if included (`pass`). +- `port`: optional port (`8000`). +- `path`: optional path (`/the/path/`). +- `query`: optional URL query (for example, `GET` arguments or "search string", such as `query=here`). +- `fragment`: optional fragment (`fragment=is;this=bit`). +""" +AnyHttpUrl = Annotated[Url, UrlConstraints(allowed_schemes=['http', 'https'])] +"""A type that will accept any http or https URL. + +* TLD not required +* Host required +""" +HttpUrl = Annotated[Url, UrlConstraints(max_length=2083, allowed_schemes=['http', 'https'])] +"""A type that will accept any http or https URL. + +* TLD not required +* Host required +* Max length 2083 + +```py +from pydantic import BaseModel, HttpUrl, ValidationError + +class MyModel(BaseModel): + url: HttpUrl + +m = MyModel(url='http://www.example.com') # (1)! +print(m.url) +#> http://www.example.com/ + +try: + MyModel(url='ftp://invalid.url') +except ValidationError as e: + print(e) + ''' + 1 validation error for MyModel + url + URL scheme should be 'http' or 'https' [type=url_scheme, input_value='ftp://invalid.url', input_type=str] + ''' + +try: + MyModel(url='not a url') +except ValidationError as e: + print(e) + ''' + 1 validation error for MyModel + url + Input should be a valid URL, relative URL without a base [type=url_parsing, input_value='not a url', input_type=str] + ''' +``` + +1. Note: mypy would prefer `m = MyModel(url=HttpUrl('http://www.example.com'))`, but Pydantic will convert the string to an HttpUrl instance anyway. + +"International domains" (e.g. a URL where the host or TLD includes non-ascii characters) will be encoded via +[punycode](https://en.wikipedia.org/wiki/Punycode) (see +[this article](https://www.xudongz.com/blog/2017/idn-phishing/) for a good description of why this is important): + +```py +from pydantic import BaseModel, HttpUrl + +class MyModel(BaseModel): + url: HttpUrl + +m1 = MyModel(url='http://puny£code.com') +print(m1.url) +#> http://xn--punycode-eja.com/ +m2 = MyModel(url='https://www.аррӏе.com/') +print(m2.url) +#> https://www.xn--80ak6aa92e.com/ +m3 = MyModel(url='https://www.example.珠宝/') +print(m3.url) +#> https://www.example.xn--pbt977c/ +``` + + +!!! warning "Underscores in Hostnames" + In Pydantic, underscores are allowed in all parts of a domain except the TLD. + Technically this might be wrong - in theory the hostname cannot have underscores, but subdomains can. + + To explain this; consider the following two cases: + + - `exam_ple.co.uk`: the hostname is `exam_ple`, which should not be allowed since it contains an underscore. + - `foo_bar.example.com` the hostname is `example`, which should be allowed since the underscore is in the subdomain. + + Without having an exhaustive list of TLDs, it would be impossible to differentiate between these two. Therefore + underscores are allowed, but you can always do further validation in a validator if desired. + + Also, Chrome, Firefox, and Safari all currently accept `http://exam_ple.com` as a URL, so we're in good + (or at least big) company. +""" +AnyWebsocketUrl = Annotated[Url, UrlConstraints(allowed_schemes=['ws', 'wss'])] +"""A type that will accept any ws or wss URL. + +* TLD not required +* Host required +""" +WebsocketUrl = Annotated[Url, UrlConstraints(max_length=2083, allowed_schemes=['ws', 'wss'])] +"""A type that will accept any ws or wss URL. + +* TLD not required +* Host required +* Max length 2083 +""" +FileUrl = Annotated[Url, UrlConstraints(allowed_schemes=['file'])] +"""A type that will accept any file URL. + +* Host not required +""" +FtpUrl = Annotated[Url, UrlConstraints(allowed_schemes=['ftp'])] +"""A type that will accept ftp URL. + +* TLD not required +* Host required +""" +PostgresDsn = Annotated[ + MultiHostUrl, + UrlConstraints( + host_required=True, + allowed_schemes=[ + 'postgres', + 'postgresql', + 'postgresql+asyncpg', + 'postgresql+pg8000', + 'postgresql+psycopg', + 'postgresql+psycopg2', + 'postgresql+psycopg2cffi', + 'postgresql+py-postgresql', + 'postgresql+pygresql', + ], + ), +] +"""A type that will accept any Postgres DSN. + +* User info required +* TLD not required +* Host required +* Supports multiple hosts + +If further validation is required, these properties can be used by validators to enforce specific behaviour: + +```py +from pydantic import ( + BaseModel, + HttpUrl, + PostgresDsn, + ValidationError, + field_validator, +) + +class MyModel(BaseModel): + url: HttpUrl + +m = MyModel(url='http://www.example.com') + +# the repr() method for a url will display all properties of the url +print(repr(m.url)) +#> Url('http://www.example.com/') +print(m.url.scheme) +#> http +print(m.url.host) +#> www.example.com +print(m.url.port) +#> 80 + +class MyDatabaseModel(BaseModel): + db: PostgresDsn + + @field_validator('db') + def check_db_name(cls, v): + assert v.path and len(v.path) > 1, 'database must be provided' + return v + +m = MyDatabaseModel(db='postgres://user:pass@localhost:5432/foobar') +print(m.db) +#> postgres://user:pass@localhost:5432/foobar + +try: + MyDatabaseModel(db='postgres://user:pass@localhost:5432') +except ValidationError as e: + print(e) + ''' + 1 validation error for MyDatabaseModel + db + Assertion failed, database must be provided + assert (None) + + where None = MultiHostUrl('postgres://user:pass@localhost:5432').path [type=assertion_error, input_value='postgres://user:pass@localhost:5432', input_type=str] + ''' +``` +""" + +CockroachDsn = Annotated[ + Url, + UrlConstraints( + host_required=True, + allowed_schemes=[ + 'cockroachdb', + 'cockroachdb+psycopg2', + 'cockroachdb+asyncpg', + ], + ), +] +"""A type that will accept any Cockroach DSN. + +* User info required +* TLD not required +* Host required +""" +AmqpDsn = Annotated[Url, UrlConstraints(allowed_schemes=['amqp', 'amqps'])] +"""A type that will accept any AMQP DSN. + +* User info required +* TLD not required +* Host required +""" +RedisDsn = Annotated[ + Url, + UrlConstraints(allowed_schemes=['redis', 'rediss'], default_host='localhost', default_port=6379, default_path='/0'), +] +"""A type that will accept any Redis DSN. + +* User info required +* TLD not required +* Host required (e.g., `rediss://:pass@localhost`) +""" +MongoDsn = Annotated[MultiHostUrl, UrlConstraints(allowed_schemes=['mongodb', 'mongodb+srv'], default_port=27017)] +"""A type that will accept any MongoDB DSN. + +* User info not required +* Database name not required +* Port not required +* User info may be passed without user part (e.g., `mongodb://mongodb0.example.com:27017`). +""" +KafkaDsn = Annotated[Url, UrlConstraints(allowed_schemes=['kafka'], default_host='localhost', default_port=9092)] +"""A type that will accept any Kafka DSN. + +* User info required +* TLD not required +* Host required +""" +NatsDsn = Annotated[ + MultiHostUrl, UrlConstraints(allowed_schemes=['nats', 'tls', 'ws'], default_host='localhost', default_port=4222) +] +"""A type that will accept any NATS DSN. + +NATS is a connective technology built for the ever increasingly hyper-connected world. +It is a single technology that enables applications to securely communicate across +any combination of cloud vendors, on-premise, edge, web and mobile, and devices. +More: https://nats.io +""" +MySQLDsn = Annotated[ + Url, + UrlConstraints( + allowed_schemes=[ + 'mysql', + 'mysql+mysqlconnector', + 'mysql+aiomysql', + 'mysql+asyncmy', + 'mysql+mysqldb', + 'mysql+pymysql', + 'mysql+cymysql', + 'mysql+pyodbc', + ], + default_port=3306, + ), +] +"""A type that will accept any MySQL DSN. + +* User info required +* TLD not required +* Host required +""" +MariaDBDsn = Annotated[ + Url, + UrlConstraints( + allowed_schemes=['mariadb', 'mariadb+mariadbconnector', 'mariadb+pymysql'], + default_port=3306, + ), +] +"""A type that will accept any MariaDB DSN. + +* User info required +* TLD not required +* Host required +""" +ClickHouseDsn = Annotated[ + Url, + UrlConstraints( + allowed_schemes=['clickhouse+native', 'clickhouse+asynch'], + default_host='localhost', + default_port=9000, + ), +] +"""A type that will accept any ClickHouse DSN. + +* User info required +* TLD not required +* Host required +""" + + +def import_email_validator() -> None: + global email_validator + try: + import email_validator + except ImportError as e: + raise ImportError('email-validator is not installed, run `pip install pydantic[email]`') from e + if not version('email-validator').partition('.')[0] == '2': + raise ImportError('email-validator version >= 2.0 required, run pip install -U email-validator') + + +if TYPE_CHECKING: + EmailStr = Annotated[str, ...] +else: + + class EmailStr: + """ + Info: + To use this type, you need to install the optional + [`email-validator`](https://github.com/JoshData/python-email-validator) package: + + ```bash + pip install email-validator + ``` + + Validate email addresses. + + ```py + from pydantic import BaseModel, EmailStr + + class Model(BaseModel): + email: EmailStr + + print(Model(email='contact@mail.com')) + #> email='contact@mail.com' + ``` + """ # noqa: D212 + + @classmethod + def __get_pydantic_core_schema__( + cls, + _source: type[Any], + _handler: GetCoreSchemaHandler, + ) -> core_schema.CoreSchema: + import_email_validator() + return core_schema.no_info_after_validator_function(cls._validate, core_schema.str_schema()) + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = handler(core_schema) + field_schema.update(type='string', format='email') + return field_schema + + @classmethod + def _validate(cls, input_value: str, /) -> str: + return validate_email(input_value)[1] + + +class NameEmail(_repr.Representation): + """ + Info: + To use this type, you need to install the optional + [`email-validator`](https://github.com/JoshData/python-email-validator) package: + + ```bash + pip install email-validator + ``` + + Validate a name and email address combination, as specified by + [RFC 5322](https://datatracker.ietf.org/doc/html/rfc5322#section-3.4). + + The `NameEmail` has two properties: `name` and `email`. + In case the `name` is not provided, it's inferred from the email address. + + ```py + from pydantic import BaseModel, NameEmail + + class User(BaseModel): + email: NameEmail + + user = User(email='Fred Bloggs ') + print(user.email) + #> Fred Bloggs + print(user.email.name) + #> Fred Bloggs + + user = User(email='fred.bloggs@example.com') + print(user.email) + #> fred.bloggs + print(user.email.name) + #> fred.bloggs + ``` + """ # noqa: D212 + + __slots__ = 'name', 'email' + + def __init__(self, name: str, email: str): + self.name = name + self.email = email + + def __eq__(self, other: Any) -> bool: + return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email) + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = handler(core_schema) + field_schema.update(type='string', format='name-email') + return field_schema + + @classmethod + def __get_pydantic_core_schema__( + cls, + _source: type[Any], + _handler: GetCoreSchemaHandler, + ) -> core_schema.CoreSchema: + import_email_validator() + + return core_schema.no_info_after_validator_function( + cls._validate, + core_schema.json_or_python_schema( + json_schema=core_schema.str_schema(), + python_schema=core_schema.union_schema( + [core_schema.is_instance_schema(cls), core_schema.str_schema()], + custom_error_type='name_email_type', + custom_error_message='Input is not a valid NameEmail', + ), + serialization=core_schema.to_string_ser_schema(), + ), + ) + + @classmethod + def _validate(cls, input_value: Self | str, /) -> Self: + if isinstance(input_value, str): + name, email = validate_email(input_value) + return cls(name, email) + else: + return input_value + + def __str__(self) -> str: + if '@' in self.name: + return f'"{self.name}" <{self.email}>' + + return f'{self.name} <{self.email}>' + + +class IPvAnyAddress: + """Validate an IPv4 or IPv6 address. + + ```py + from pydantic import BaseModel + from pydantic.networks import IPvAnyAddress + + class IpModel(BaseModel): + ip: IPvAnyAddress + + print(IpModel(ip='127.0.0.1')) + #> ip=IPv4Address('127.0.0.1') + + try: + IpModel(ip='http://www.example.com') + except ValueError as e: + print(e.errors()) + ''' + [ + { + 'type': 'ip_any_address', + 'loc': ('ip',), + 'msg': 'value is not a valid IPv4 or IPv6 address', + 'input': 'http://www.example.com', + } + ] + ''' + ``` + """ + + __slots__ = () + + def __new__(cls, value: Any) -> IPv4Address | IPv6Address: + """Validate an IPv4 or IPv6 address.""" + try: + return IPv4Address(value) + except ValueError: + pass + + try: + return IPv6Address(value) + except ValueError: + raise PydanticCustomError('ip_any_address', 'value is not a valid IPv4 or IPv6 address') + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = {} + field_schema.update(type='string', format='ipvanyaddress') + return field_schema + + @classmethod + def __get_pydantic_core_schema__( + cls, + _source: type[Any], + _handler: GetCoreSchemaHandler, + ) -> core_schema.CoreSchema: + return core_schema.no_info_plain_validator_function( + cls._validate, serialization=core_schema.to_string_ser_schema() + ) + + @classmethod + def _validate(cls, input_value: Any, /) -> IPv4Address | IPv6Address: + return cls(input_value) # type: ignore[return-value] + + +class IPvAnyInterface: + """Validate an IPv4 or IPv6 interface.""" + + __slots__ = () + + def __new__(cls, value: NetworkType) -> IPv4Interface | IPv6Interface: + """Validate an IPv4 or IPv6 interface.""" + try: + return IPv4Interface(value) + except ValueError: + pass + + try: + return IPv6Interface(value) + except ValueError: + raise PydanticCustomError('ip_any_interface', 'value is not a valid IPv4 or IPv6 interface') + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = {} + field_schema.update(type='string', format='ipvanyinterface') + return field_schema + + @classmethod + def __get_pydantic_core_schema__( + cls, + _source: type[Any], + _handler: GetCoreSchemaHandler, + ) -> core_schema.CoreSchema: + return core_schema.no_info_plain_validator_function( + cls._validate, serialization=core_schema.to_string_ser_schema() + ) + + @classmethod + def _validate(cls, input_value: NetworkType, /) -> IPv4Interface | IPv6Interface: + return cls(input_value) # type: ignore[return-value] + + +IPvAnyNetworkType: TypeAlias = 'IPv4Network | IPv6Network' + +if TYPE_CHECKING: + IPvAnyNetwork = IPvAnyNetworkType +else: + + class IPvAnyNetwork: + """Validate an IPv4 or IPv6 network.""" + + __slots__ = () + + def __new__(cls, value: NetworkType) -> IPvAnyNetworkType: + """Validate an IPv4 or IPv6 network.""" + # Assume IP Network is defined with a default value for `strict` argument. + # Define your own class if you want to specify network address check strictness. + try: + return IPv4Network(value) + except ValueError: + pass + + try: + return IPv6Network(value) + except ValueError: + raise PydanticCustomError('ip_any_network', 'value is not a valid IPv4 or IPv6 network') + + @classmethod + def __get_pydantic_json_schema__( + cls, core_schema: core_schema.CoreSchema, handler: _schema_generation_shared.GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = {} + field_schema.update(type='string', format='ipvanynetwork') + return field_schema + + @classmethod + def __get_pydantic_core_schema__( + cls, + _source: type[Any], + _handler: GetCoreSchemaHandler, + ) -> core_schema.CoreSchema: + return core_schema.no_info_plain_validator_function( + cls._validate, serialization=core_schema.to_string_ser_schema() + ) + + @classmethod + def _validate(cls, input_value: NetworkType, /) -> IPvAnyNetworkType: + return cls(input_value) # type: ignore[return-value] + + +def _build_pretty_email_regex() -> re.Pattern[str]: + name_chars = r'[\w!#$%&\'*+\-/=?^_`{|}~]' + unquoted_name_group = rf'((?:{name_chars}+\s+)*{name_chars}+)' + quoted_name_group = r'"((?:[^"]|\")+)"' + email_group = r'<\s*(.+)\s*>' + return re.compile(rf'\s*(?:{unquoted_name_group}|{quoted_name_group})?\s*{email_group}\s*') + + +pretty_email_regex = _build_pretty_email_regex() + +MAX_EMAIL_LENGTH = 2048 +"""Maximum length for an email. +A somewhat arbitrary but very generous number compared to what is allowed by most implementations. +""" + + +def validate_email(value: str) -> tuple[str, str]: + """Email address validation using [email-validator](https://pypi.org/project/email-validator/). + + Note: + Note that: + + * Raw IP address (literal) domain parts are not allowed. + * `"John Doe "` style "pretty" email addresses are processed. + * Spaces are striped from the beginning and end of addresses, but no error is raised. + """ + if email_validator is None: + import_email_validator() + + if len(value) > MAX_EMAIL_LENGTH: + raise PydanticCustomError( + 'value_error', + 'value is not a valid email address: {reason}', + {'reason': f'Length must not exceed {MAX_EMAIL_LENGTH} characters'}, + ) + + m = pretty_email_regex.fullmatch(value) + name: str | None = None + if m: + unquoted_name, quoted_name, value = m.groups() + name = unquoted_name or quoted_name + + email = value.strip() + + try: + parts = email_validator.validate_email(email, check_deliverability=False) + except email_validator.EmailNotValidError as e: + raise PydanticCustomError( + 'value_error', 'value is not a valid email address: {reason}', {'reason': str(e.args[0])} + ) from e + + email = parts.normalized + assert email is not None + name = name or parts.local_part + return name, email + + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/parse.py b/env/Lib/site-packages/pydantic/parse.py new file mode 100644 index 0000000..68b7f04 --- /dev/null +++ b/env/Lib/site-packages/pydantic/parse.py @@ -0,0 +1,5 @@ +"""The `parse` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/plugin/__init__.py b/env/Lib/site-packages/pydantic/plugin/__init__.py new file mode 100644 index 0000000..549c095 --- /dev/null +++ b/env/Lib/site-packages/pydantic/plugin/__init__.py @@ -0,0 +1,171 @@ +"""Usage docs: https://docs.pydantic.dev/2.8/concepts/plugins#build-a-plugin + +Plugin interface for Pydantic plugins, and related types. +""" + +from __future__ import annotations + +from typing import Any, Callable, NamedTuple + +from pydantic_core import CoreConfig, CoreSchema, ValidationError +from typing_extensions import Literal, Protocol, TypeAlias + +__all__ = ( + 'PydanticPluginProtocol', + 'BaseValidateHandlerProtocol', + 'ValidatePythonHandlerProtocol', + 'ValidateJsonHandlerProtocol', + 'ValidateStringsHandlerProtocol', + 'NewSchemaReturns', + 'SchemaTypePath', + 'SchemaKind', +) + +NewSchemaReturns: TypeAlias = 'tuple[ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None]' + + +class SchemaTypePath(NamedTuple): + """Path defining where `schema_type` was defined, or where `TypeAdapter` was called.""" + + module: str + name: str + + +SchemaKind: TypeAlias = Literal['BaseModel', 'TypeAdapter', 'dataclass', 'create_model', 'validate_call'] + + +class PydanticPluginProtocol(Protocol): + """Protocol defining the interface for Pydantic plugins.""" + + def new_schema_validator( + self, + schema: CoreSchema, + schema_type: Any, + schema_type_path: SchemaTypePath, + schema_kind: SchemaKind, + config: CoreConfig | None, + plugin_settings: dict[str, object], + ) -> tuple[ + ValidatePythonHandlerProtocol | None, ValidateJsonHandlerProtocol | None, ValidateStringsHandlerProtocol | None + ]: + """This method is called for each plugin every time a new [`SchemaValidator`][pydantic_core.SchemaValidator] + is created. + + It should return an event handler for each of the three validation methods, or `None` if the plugin does not + implement that method. + + Args: + schema: The schema to validate against. + schema_type: The original type which the schema was created from, e.g. the model class. + schema_type_path: Path defining where `schema_type` was defined, or where `TypeAdapter` was called. + schema_kind: The kind of schema to validate against. + config: The config to use for validation. + plugin_settings: Any plugin settings. + + Returns: + A tuple of optional event handlers for each of the three validation methods - + `validate_python`, `validate_json`, `validate_strings`. + """ + raise NotImplementedError('Pydantic plugins should implement `new_schema_validator`.') + + +class BaseValidateHandlerProtocol(Protocol): + """Base class for plugin callbacks protocols. + + You shouldn't implement this protocol directly, instead use one of the subclasses with adds the correctly + typed `on_error` method. + """ + + on_enter: Callable[..., None] + """`on_enter` is changed to be more specific on all subclasses""" + + def on_success(self, result: Any) -> None: + """Callback to be notified of successful validation. + + Args: + result: The result of the validation. + """ + return + + def on_error(self, error: ValidationError) -> None: + """Callback to be notified of validation errors. + + Args: + error: The validation error. + """ + return + + def on_exception(self, exception: Exception) -> None: + """Callback to be notified of validation exceptions. + + Args: + exception: The exception raised during validation. + """ + return + + +class ValidatePythonHandlerProtocol(BaseValidateHandlerProtocol, Protocol): + """Event handler for `SchemaValidator.validate_python`.""" + + def on_enter( + self, + input: Any, + *, + strict: bool | None = None, + from_attributes: bool | None = None, + context: dict[str, Any] | None = None, + self_instance: Any | None = None, + ) -> None: + """Callback to be notified of validation start, and create an instance of the event handler. + + Args: + input: The input to be validated. + strict: Whether to validate the object in strict mode. + from_attributes: Whether to validate objects as inputs by extracting attributes. + context: The context to use for validation, this is passed to functional validators. + self_instance: An instance of a model to set attributes on from validation, this is used when running + validation from the `__init__` method of a model. + """ + pass + + +class ValidateJsonHandlerProtocol(BaseValidateHandlerProtocol, Protocol): + """Event handler for `SchemaValidator.validate_json`.""" + + def on_enter( + self, + input: str | bytes | bytearray, + *, + strict: bool | None = None, + context: dict[str, Any] | None = None, + self_instance: Any | None = None, + ) -> None: + """Callback to be notified of validation start, and create an instance of the event handler. + + Args: + input: The JSON data to be validated. + strict: Whether to validate the object in strict mode. + context: The context to use for validation, this is passed to functional validators. + self_instance: An instance of a model to set attributes on from validation, this is used when running + validation from the `__init__` method of a model. + """ + pass + + +StringInput: TypeAlias = 'dict[str, StringInput]' + + +class ValidateStringsHandlerProtocol(BaseValidateHandlerProtocol, Protocol): + """Event handler for `SchemaValidator.validate_strings`.""" + + def on_enter( + self, input: StringInput, *, strict: bool | None = None, context: dict[str, Any] | None = None + ) -> None: + """Callback to be notified of validation start, and create an instance of the event handler. + + Args: + input: The string data to be validated. + strict: Whether to validate the object in strict mode. + context: The context to use for validation, this is passed to functional validators. + """ + pass diff --git a/env/Lib/site-packages/pydantic/plugin/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/pydantic/plugin/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..feeb343 Binary files /dev/null and b/env/Lib/site-packages/pydantic/plugin/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/plugin/__pycache__/_loader.cpython-311.pyc b/env/Lib/site-packages/pydantic/plugin/__pycache__/_loader.cpython-311.pyc new file mode 100644 index 0000000..7b32d6b Binary files /dev/null and b/env/Lib/site-packages/pydantic/plugin/__pycache__/_loader.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-311.pyc b/env/Lib/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-311.pyc new file mode 100644 index 0000000..2660e35 Binary files /dev/null and b/env/Lib/site-packages/pydantic/plugin/__pycache__/_schema_validator.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/plugin/_loader.py b/env/Lib/site-packages/pydantic/plugin/_loader.py new file mode 100644 index 0000000..2f90dc5 --- /dev/null +++ b/env/Lib/site-packages/pydantic/plugin/_loader.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import importlib.metadata as importlib_metadata +import os +import warnings +from typing import TYPE_CHECKING, Final, Iterable + +if TYPE_CHECKING: + from . import PydanticPluginProtocol + + +PYDANTIC_ENTRY_POINT_GROUP: Final[str] = 'pydantic' + +# cache of plugins +_plugins: dict[str, PydanticPluginProtocol] | None = None +# return no plugins while loading plugins to avoid recursion and errors while import plugins +# this means that if plugins use pydantic +_loading_plugins: bool = False + + +def get_plugins() -> Iterable[PydanticPluginProtocol]: + """Load plugins for Pydantic. + + Inspired by: https://github.com/pytest-dev/pluggy/blob/1.3.0/src/pluggy/_manager.py#L376-L402 + """ + disabled_plugins = os.getenv('PYDANTIC_DISABLE_PLUGINS') + global _plugins, _loading_plugins + if _loading_plugins: + # this happens when plugins themselves use pydantic, we return no plugins + return () + elif disabled_plugins in ('__all__', '1', 'true'): + return () + elif _plugins is None: + _plugins = {} + # set _loading_plugins so any plugins that use pydantic don't themselves use plugins + _loading_plugins = True + try: + for dist in importlib_metadata.distributions(): + for entry_point in dist.entry_points: + if entry_point.group != PYDANTIC_ENTRY_POINT_GROUP: + continue + if entry_point.value in _plugins: + continue + if disabled_plugins is not None and entry_point.name in disabled_plugins.split(','): + continue + try: + _plugins[entry_point.value] = entry_point.load() + except (ImportError, AttributeError) as e: + warnings.warn( + f'{e.__class__.__name__} while loading the `{entry_point.name}` Pydantic plugin, ' + f'this plugin will not be installed.\n\n{e!r}' + ) + finally: + _loading_plugins = False + + return _plugins.values() diff --git a/env/Lib/site-packages/pydantic/plugin/_schema_validator.py b/env/Lib/site-packages/pydantic/plugin/_schema_validator.py new file mode 100644 index 0000000..21287f4 --- /dev/null +++ b/env/Lib/site-packages/pydantic/plugin/_schema_validator.py @@ -0,0 +1,139 @@ +"""Pluggable schema validator for pydantic.""" + +from __future__ import annotations + +import functools +from typing import TYPE_CHECKING, Any, Callable, Iterable, TypeVar + +from pydantic_core import CoreConfig, CoreSchema, SchemaValidator, ValidationError +from typing_extensions import Literal, ParamSpec + +if TYPE_CHECKING: + from . import BaseValidateHandlerProtocol, PydanticPluginProtocol, SchemaKind, SchemaTypePath + + +P = ParamSpec('P') +R = TypeVar('R') +Event = Literal['on_validate_python', 'on_validate_json', 'on_validate_strings'] +events: list[Event] = list(Event.__args__) # type: ignore + + +def create_schema_validator( + schema: CoreSchema, + schema_type: Any, + schema_type_module: str, + schema_type_name: str, + schema_kind: SchemaKind, + config: CoreConfig | None = None, + plugin_settings: dict[str, Any] | None = None, +) -> SchemaValidator | PluggableSchemaValidator: + """Create a `SchemaValidator` or `PluggableSchemaValidator` if plugins are installed. + + Returns: + If plugins are installed then return `PluggableSchemaValidator`, otherwise return `SchemaValidator`. + """ + from . import SchemaTypePath + from ._loader import get_plugins + + plugins = get_plugins() + if plugins: + return PluggableSchemaValidator( + schema, + schema_type, + SchemaTypePath(schema_type_module, schema_type_name), + schema_kind, + config, + plugins, + plugin_settings or {}, + ) + else: + return SchemaValidator(schema, config) + + +class PluggableSchemaValidator: + """Pluggable schema validator.""" + + __slots__ = '_schema_validator', 'validate_json', 'validate_python', 'validate_strings' + + def __init__( + self, + schema: CoreSchema, + schema_type: Any, + schema_type_path: SchemaTypePath, + schema_kind: SchemaKind, + config: CoreConfig | None, + plugins: Iterable[PydanticPluginProtocol], + plugin_settings: dict[str, Any], + ) -> None: + self._schema_validator = SchemaValidator(schema, config) + + python_event_handlers: list[BaseValidateHandlerProtocol] = [] + json_event_handlers: list[BaseValidateHandlerProtocol] = [] + strings_event_handlers: list[BaseValidateHandlerProtocol] = [] + for plugin in plugins: + try: + p, j, s = plugin.new_schema_validator( + schema, schema_type, schema_type_path, schema_kind, config, plugin_settings + ) + except TypeError as e: # pragma: no cover + raise TypeError(f'Error using plugin `{plugin.__module__}:{plugin.__class__.__name__}`: {e}') from e + if p is not None: + python_event_handlers.append(p) + if j is not None: + json_event_handlers.append(j) + if s is not None: + strings_event_handlers.append(s) + + self.validate_python = build_wrapper(self._schema_validator.validate_python, python_event_handlers) + self.validate_json = build_wrapper(self._schema_validator.validate_json, json_event_handlers) + self.validate_strings = build_wrapper(self._schema_validator.validate_strings, strings_event_handlers) + + def __getattr__(self, name: str) -> Any: + return getattr(self._schema_validator, name) + + +def build_wrapper(func: Callable[P, R], event_handlers: list[BaseValidateHandlerProtocol]) -> Callable[P, R]: + if not event_handlers: + return func + else: + on_enters = tuple(h.on_enter for h in event_handlers if filter_handlers(h, 'on_enter')) + on_successes = tuple(h.on_success for h in event_handlers if filter_handlers(h, 'on_success')) + on_errors = tuple(h.on_error for h in event_handlers if filter_handlers(h, 'on_error')) + on_exceptions = tuple(h.on_exception for h in event_handlers if filter_handlers(h, 'on_exception')) + + @functools.wraps(func) + def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: + for on_enter_handler in on_enters: + on_enter_handler(*args, **kwargs) + + try: + result = func(*args, **kwargs) + except ValidationError as error: + for on_error_handler in on_errors: + on_error_handler(error) + raise + except Exception as exception: + for on_exception_handler in on_exceptions: + on_exception_handler(exception) + raise + else: + for on_success_handler in on_successes: + on_success_handler(result) + return result + + return wrapper + + +def filter_handlers(handler_cls: BaseValidateHandlerProtocol, method_name: str) -> bool: + """Filter out handler methods which are not implemented by the plugin directly - e.g. are missing + or are inherited from the protocol. + """ + handler = getattr(handler_cls, method_name, None) + if handler is None: + return False + elif handler.__module__ == 'pydantic.plugin': + # this is the original handler, from the protocol due to runtime inheritance + # we don't want to call it + return False + else: + return True diff --git a/env/Lib/site-packages/pydantic/py.typed b/env/Lib/site-packages/pydantic/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/pydantic/root_model.py b/env/Lib/site-packages/pydantic/root_model.py new file mode 100644 index 0000000..b073631 --- /dev/null +++ b/env/Lib/site-packages/pydantic/root_model.py @@ -0,0 +1,154 @@ +"""RootModel class and type definitions.""" + +from __future__ import annotations as _annotations + +import typing +from copy import copy, deepcopy + +from pydantic_core import PydanticUndefined + +from . import PydanticUserError +from ._internal import _model_construction, _repr +from .main import BaseModel, _object_setattr + +if typing.TYPE_CHECKING: + from typing import Any + + from typing_extensions import Literal, Self, dataclass_transform + + from .fields import Field as PydanticModelField + from .fields import PrivateAttr as PydanticModelPrivateAttr + + # dataclass_transform could be applied to RootModel directly, but `ModelMetaclass`'s dataclass_transform + # takes priority (at least with pyright). We trick type checkers into thinking we apply dataclass_transform + # on a new metaclass. + @dataclass_transform(kw_only_default=False, field_specifiers=(PydanticModelField, PydanticModelPrivateAttr)) + class _RootModelMetaclass(_model_construction.ModelMetaclass): ... +else: + _RootModelMetaclass = _model_construction.ModelMetaclass + +__all__ = ('RootModel',) + +RootModelRootType = typing.TypeVar('RootModelRootType') + + +class RootModel(BaseModel, typing.Generic[RootModelRootType], metaclass=_RootModelMetaclass): + """Usage docs: https://docs.pydantic.dev/2.8/concepts/models/#rootmodel-and-custom-root-types + + A Pydantic `BaseModel` for the root object of the model. + + Attributes: + root: The root object of the model. + __pydantic_root_model__: Whether the model is a RootModel. + __pydantic_private__: Private fields in the model. + __pydantic_extra__: Extra fields in the model. + + """ + + __pydantic_root_model__ = True + __pydantic_private__ = None + __pydantic_extra__ = None + + root: RootModelRootType + + def __init_subclass__(cls, **kwargs): + extra = cls.model_config.get('extra') + if extra is not None: + raise PydanticUserError( + "`RootModel` does not support setting `model_config['extra']`", code='root-model-extra' + ) + super().__init_subclass__(**kwargs) + + def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None: # type: ignore + __tracebackhide__ = True + if data: + if root is not PydanticUndefined: + raise ValueError( + '"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments' + ) + root = data # type: ignore + self.__pydantic_validator__.validate_python(root, self_instance=self) + + __init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess] + + @classmethod + def model_construct(cls, root: RootModelRootType, _fields_set: set[str] | None = None) -> Self: # type: ignore + """Create a new model using the provided root object and update fields set. + + Args: + root: The root object of the model. + _fields_set: The set of fields to be updated. + + Returns: + The new model. + + Raises: + NotImplemented: If the model is not a subclass of `RootModel`. + """ + return super().model_construct(root=root, _fields_set=_fields_set) + + def __getstate__(self) -> dict[Any, Any]: + return { + '__dict__': self.__dict__, + '__pydantic_fields_set__': self.__pydantic_fields_set__, + } + + def __setstate__(self, state: dict[Any, Any]) -> None: + _object_setattr(self, '__pydantic_fields_set__', state['__pydantic_fields_set__']) + _object_setattr(self, '__dict__', state['__dict__']) + + def __copy__(self) -> Self: + """Returns a shallow copy of the model.""" + cls = type(self) + m = cls.__new__(cls) + _object_setattr(m, '__dict__', copy(self.__dict__)) + _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) + return m + + def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self: + """Returns a deep copy of the model.""" + cls = type(self) + m = cls.__new__(cls) + _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo)) + # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str], + # and attempting a deepcopy would be marginally slower. + _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__)) + return m + + if typing.TYPE_CHECKING: + + def model_dump( # type: ignore + self, + *, + mode: Literal['json', 'python'] | str = 'python', + include: Any = None, + exclude: Any = None, + context: dict[str, Any] | None = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool | Literal['none', 'warn', 'error'] = True, + serialize_as_any: bool = False, + ) -> Any: + """This method is included just to get a more accurate return type for type checkers. + It is included in this `if TYPE_CHECKING:` block since no override is actually necessary. + + See the documentation of `BaseModel.model_dump` for more details about the arguments. + + Generally, this method will have a return type of `RootModelRootType`, assuming that `RootModelRootType` is + not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` subclass, then the return + type will likely be `dict[str, Any]`, as `model_dump` calls are recursive. The return type could + even be something different, in the case of a custom serializer. + Thus, `Any` is used here to catch all of these cases. + """ + ... + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, RootModel): + return NotImplemented + return self.model_fields['root'].annotation == other.model_fields['root'].annotation and super().__eq__(other) + + def __repr_args__(self) -> _repr.ReprArgs: + yield 'root', self.root diff --git a/env/Lib/site-packages/pydantic/schema.py b/env/Lib/site-packages/pydantic/schema.py new file mode 100644 index 0000000..a3245a6 --- /dev/null +++ b/env/Lib/site-packages/pydantic/schema.py @@ -0,0 +1,5 @@ +"""The `schema` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/tools.py b/env/Lib/site-packages/pydantic/tools.py new file mode 100644 index 0000000..fdc68c4 --- /dev/null +++ b/env/Lib/site-packages/pydantic/tools.py @@ -0,0 +1,5 @@ +"""The `tools` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/type_adapter.py b/env/Lib/site-packages/pydantic/type_adapter.py new file mode 100644 index 0000000..d6001df --- /dev/null +++ b/env/Lib/site-packages/pydantic/type_adapter.py @@ -0,0 +1,601 @@ +"""Type adapter specification.""" + +from __future__ import annotations as _annotations + +import sys +from contextlib import contextmanager +from dataclasses import is_dataclass +from functools import cached_property, wraps +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Generic, + Iterable, + Iterator, + Literal, + Set, + TypeVar, + Union, + cast, + final, + overload, +) + +from pydantic_core import CoreSchema, SchemaSerializer, SchemaValidator, Some +from typing_extensions import Concatenate, ParamSpec, is_typeddict + +from pydantic.errors import PydanticUserError +from pydantic.main import BaseModel + +from ._internal import _config, _generate_schema, _mock_val_ser, _typing_extra, _utils +from .config import ConfigDict +from .json_schema import ( + DEFAULT_REF_TEMPLATE, + GenerateJsonSchema, + JsonSchemaKeyT, + JsonSchemaMode, + JsonSchemaValue, +) +from .plugin._schema_validator import PluggableSchemaValidator, create_schema_validator + +T = TypeVar('T') +R = TypeVar('R') +P = ParamSpec('P') +TypeAdapterT = TypeVar('TypeAdapterT', bound='TypeAdapter') + + +if TYPE_CHECKING: + # should be `set[int] | set[str] | dict[int, IncEx] | dict[str, IncEx] | None`, but mypy can't cope + IncEx = Union[Set[int], Set[str], Dict[int, Any], Dict[str, Any]] + + +def _get_schema(type_: Any, config_wrapper: _config.ConfigWrapper, parent_depth: int) -> CoreSchema: + """`BaseModel` uses its own `__module__` to find out where it was defined + and then looks for symbols to resolve forward references in those globals. + On the other hand this function can be called with arbitrary objects, + including type aliases, where `__module__` (always `typing.py`) is not useful. + So instead we look at the globals in our parent stack frame. + + This works for the case where this function is called in a module that + has the target of forward references in its scope, but + does not always work for more complex cases. + + For example, take the following: + + a.py + ```python + from typing import Dict, List + + IntList = List[int] + OuterDict = Dict[str, 'IntList'] + ``` + + b.py + ```python test="skip" + from a import OuterDict + + from pydantic import TypeAdapter + + IntList = int # replaces the symbol the forward reference is looking for + v = TypeAdapter(OuterDict) + v({'x': 1}) # should fail but doesn't + ``` + + If `OuterDict` were a `BaseModel`, this would work because it would resolve + the forward reference within the `a.py` namespace. + But `TypeAdapter(OuterDict)` can't determine what module `OuterDict` came from. + + In other words, the assumption that _all_ forward references exist in the + module we are being called from is not technically always true. + Although most of the time it is and it works fine for recursive models and such, + `BaseModel`'s behavior isn't perfect either and _can_ break in similar ways, + so there is no right or wrong between the two. + + But at the very least this behavior is _subtly_ different from `BaseModel`'s. + """ + local_ns = _typing_extra.parent_frame_namespace(parent_depth=parent_depth) + global_ns = sys._getframe(max(parent_depth - 1, 1)).f_globals.copy() + global_ns.update(local_ns or {}) + gen = _generate_schema.GenerateSchema(config_wrapper, types_namespace=global_ns, typevars_map={}) + schema = gen.generate_schema(type_) + schema = gen.clean_schema(schema) + return schema + + +def _getattr_no_parents(obj: Any, attribute: str) -> Any: + """Returns the attribute value without attempting to look up attributes from parent types.""" + if hasattr(obj, '__dict__'): + try: + return obj.__dict__[attribute] + except KeyError: + pass + + slots = getattr(obj, '__slots__', None) + if slots is not None and attribute in slots: + return getattr(obj, attribute) + else: + raise AttributeError(attribute) + + +def _type_has_config(type_: Any) -> bool: + """Returns whether the type has config.""" + type_ = _typing_extra.annotated_type(type_) or type_ + try: + return issubclass(type_, BaseModel) or is_dataclass(type_) or is_typeddict(type_) + except TypeError: + # type is not a class + return False + + +# This is keeping track of the frame depth for the TypeAdapter functions. This is required for _parent_depth used for +# ForwardRef resolution. We may enter the TypeAdapter schema building via different TypeAdapter functions. Hence, we +# need to keep track of the frame depth relative to the originally provided _parent_depth. +def _frame_depth( + depth: int, +) -> Callable[[Callable[Concatenate[TypeAdapterT, P], R]], Callable[Concatenate[TypeAdapterT, P], R]]: + def wrapper(func: Callable[Concatenate[TypeAdapterT, P], R]) -> Callable[Concatenate[TypeAdapterT, P], R]: + @wraps(func) + def wrapped(self: TypeAdapterT, *args: P.args, **kwargs: P.kwargs) -> R: + with self._with_frame_depth(depth + 1): # depth + 1 for the wrapper function + return func(self, *args, **kwargs) + + return wrapped + + return wrapper + + +@final +class TypeAdapter(Generic[T]): + """Usage docs: https://docs.pydantic.dev/2.8/concepts/type_adapter/ + + Type adapters provide a flexible way to perform validation and serialization based on a Python type. + + A `TypeAdapter` instance exposes some of the functionality from `BaseModel` instance methods + for types that do not have such methods (such as dataclasses, primitive types, and more). + + **Note:** `TypeAdapter` instances are not types, and cannot be used as type annotations for fields. + + **Note:** By default, `TypeAdapter` does not respect the + [`defer_build=True`][pydantic.config.ConfigDict.defer_build] setting in the + [`model_config`][pydantic.BaseModel.model_config] or in the `TypeAdapter` constructor `config`. You need to also + explicitly set [`experimental_defer_build_mode=('model', 'type_adapter')`][pydantic.config.ConfigDict.experimental_defer_build_mode] of the + config to defer the model validator and serializer construction. Thus, this feature is opt-in to ensure backwards + compatibility. + + Attributes: + core_schema: The core schema for the type. + validator (SchemaValidator): The schema validator for the type. + serializer: The schema serializer for the type. + """ + + @overload + def __init__( + self, + type: type[T], + *, + config: ConfigDict | None = ..., + _parent_depth: int = ..., + module: str | None = ..., + ) -> None: ... + + # This second overload is for unsupported special forms (such as Annotated, Union, etc.) + # Currently there is no way to type this correctly + # See https://github.com/python/typing/pull/1618 + @overload + def __init__( + self, + type: Any, + *, + config: ConfigDict | None = ..., + _parent_depth: int = ..., + module: str | None = ..., + ) -> None: ... + + def __init__( + self, + type: Any, + *, + config: ConfigDict | None = None, + _parent_depth: int = 2, + module: str | None = None, + ) -> None: + """Initializes the TypeAdapter object. + + Args: + type: The type associated with the `TypeAdapter`. + config: Configuration for the `TypeAdapter`, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict]. + _parent_depth: depth at which to search the parent namespace to construct the local namespace. + module: The module that passes to plugin if provided. + + !!! note + You cannot use the `config` argument when instantiating a `TypeAdapter` if the type you're using has its own + config that cannot be overridden (ex: `BaseModel`, `TypedDict`, and `dataclass`). A + [`type-adapter-config-unused`](../errors/usage_errors.md#type-adapter-config-unused) error will be raised in this case. + + !!! note + The `_parent_depth` argument is named with an underscore to suggest its private nature and discourage use. + It may be deprecated in a minor version, so we only recommend using it if you're + comfortable with potential change in behavior / support. + + ??? tip "Compatibility with `mypy`" + Depending on the type used, `mypy` might raise an error when instantiating a `TypeAdapter`. As a workaround, you can explicitly + annotate your variable: + + ```py + from typing import Union + + from pydantic import TypeAdapter + + ta: TypeAdapter[Union[str, int]] = TypeAdapter(Union[str, int]) # type: ignore[arg-type] + ``` + + Returns: + A type adapter configured for the specified `type`. + """ + if _type_has_config(type) and config is not None: + raise PydanticUserError( + 'Cannot use `config` when the type is a BaseModel, dataclass or TypedDict.' + ' These types can have their own config and setting the config via the `config`' + ' parameter to TypeAdapter will not override it, thus the `config` you passed to' + ' TypeAdapter becomes meaningless, which is probably not what you want.', + code='type-adapter-config-unused', + ) + + self._type = type + self._config = config + self._parent_depth = _parent_depth + if module is None: + f = sys._getframe(1) + self._module_name = cast(str, f.f_globals.get('__name__', '')) + else: + self._module_name = module + + self._core_schema: CoreSchema | None = None + self._validator: SchemaValidator | PluggableSchemaValidator | None = None + self._serializer: SchemaSerializer | None = None + + if not self._defer_build(): + # Immediately initialize the core schema, validator and serializer + with self._with_frame_depth(1): # +1 frame depth for this __init__ + # Model itself may be using deferred building. For backward compatibility we don't rebuild model mocks + # here as part of __init__ even though TypeAdapter itself is not using deferred building. + self._init_core_attrs(rebuild_mocks=False) + + @contextmanager + def _with_frame_depth(self, depth: int) -> Iterator[None]: + self._parent_depth += depth + try: + yield + finally: + self._parent_depth -= depth + + @_frame_depth(1) + def _init_core_attrs(self, rebuild_mocks: bool) -> None: + try: + self._core_schema = _getattr_no_parents(self._type, '__pydantic_core_schema__') + self._validator = _getattr_no_parents(self._type, '__pydantic_validator__') + self._serializer = _getattr_no_parents(self._type, '__pydantic_serializer__') + except AttributeError: + config_wrapper = _config.ConfigWrapper(self._config) + core_config = config_wrapper.core_config(None) + + self._core_schema = _get_schema(self._type, config_wrapper, parent_depth=self._parent_depth) + self._validator = create_schema_validator( + schema=self._core_schema, + schema_type=self._type, + schema_type_module=self._module_name, + schema_type_name=str(self._type), + schema_kind='TypeAdapter', + config=core_config, + plugin_settings=config_wrapper.plugin_settings, + ) + self._serializer = SchemaSerializer(self._core_schema, core_config) + + if rebuild_mocks and isinstance(self._core_schema, _mock_val_ser.MockCoreSchema): + self._core_schema.rebuild() + self._init_core_attrs(rebuild_mocks=False) + assert not isinstance(self._core_schema, _mock_val_ser.MockCoreSchema) + assert not isinstance(self._validator, _mock_val_ser.MockValSer) + assert not isinstance(self._serializer, _mock_val_ser.MockValSer) + + @cached_property + @_frame_depth(2) # +2 for @cached_property and core_schema(self) + def core_schema(self) -> CoreSchema: + """The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.""" + if self._core_schema is None or isinstance(self._core_schema, _mock_val_ser.MockCoreSchema): + self._init_core_attrs(rebuild_mocks=True) # Do not expose MockCoreSchema from public function + assert self._core_schema is not None and not isinstance(self._core_schema, _mock_val_ser.MockCoreSchema) + return self._core_schema + + @cached_property + @_frame_depth(2) # +2 for @cached_property + validator(self) + def validator(self) -> SchemaValidator | PluggableSchemaValidator: + """The pydantic-core SchemaValidator used to validate instances of the model.""" + if not isinstance(self._validator, (SchemaValidator, PluggableSchemaValidator)): + self._init_core_attrs(rebuild_mocks=True) # Do not expose MockValSer from public function + assert isinstance(self._validator, (SchemaValidator, PluggableSchemaValidator)) + return self._validator + + @cached_property + @_frame_depth(2) # +2 for @cached_property + serializer(self) + def serializer(self) -> SchemaSerializer: + """The pydantic-core SchemaSerializer used to dump instances of the model.""" + if not isinstance(self._serializer, SchemaSerializer): + self._init_core_attrs(rebuild_mocks=True) # Do not expose MockValSer from public function + assert isinstance(self._serializer, SchemaSerializer) + return self._serializer + + def _defer_build(self) -> bool: + config = self._config if self._config is not None else self._model_config() + return self._is_defer_build_config(config) if config is not None else False + + def _model_config(self) -> ConfigDict | None: + type_: Any = _typing_extra.annotated_type(self._type) or self._type # Eg FastAPI heavily uses Annotated + if _utils.lenient_issubclass(type_, BaseModel): + return type_.model_config + return getattr(type_, '__pydantic_config__', None) + + @staticmethod + def _is_defer_build_config(config: ConfigDict) -> bool: + # TODO reevaluate this logic when we have a better understanding of how defer_build should work with TypeAdapter + # Should we drop the special experimental_defer_build_mode check? + return config.get('defer_build', False) is True and 'type_adapter' in config.get( + 'experimental_defer_build_mode', tuple() + ) + + @_frame_depth(1) + def validate_python( + self, + object: Any, + /, + *, + strict: bool | None = None, + from_attributes: bool | None = None, + context: dict[str, Any] | None = None, + ) -> T: + """Validate a Python object against the model. + + Args: + object: The Python object to validate against the model. + strict: Whether to strictly check types. + from_attributes: Whether to extract data from object attributes. + context: Additional context to pass to the validator. + + !!! note + When using `TypeAdapter` with a Pydantic `dataclass`, the use of the `from_attributes` + argument is not supported. + + Returns: + The validated object. + """ + return self.validator.validate_python(object, strict=strict, from_attributes=from_attributes, context=context) + + @_frame_depth(1) + def validate_json( + self, data: str | bytes, /, *, strict: bool | None = None, context: dict[str, Any] | None = None + ) -> T: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/json/#json-parsing + + Validate a JSON string or bytes against the model. + + Args: + data: The JSON data to validate against the model. + strict: Whether to strictly check types. + context: Additional context to use during validation. + + Returns: + The validated object. + """ + return self.validator.validate_json(data, strict=strict, context=context) + + @_frame_depth(1) + def validate_strings(self, obj: Any, /, *, strict: bool | None = None, context: dict[str, Any] | None = None) -> T: + """Validate object contains string data against the model. + + Args: + obj: The object contains string data to validate. + strict: Whether to strictly check types. + context: Additional context to use during validation. + + Returns: + The validated object. + """ + return self.validator.validate_strings(obj, strict=strict, context=context) + + @_frame_depth(1) + def get_default_value(self, *, strict: bool | None = None, context: dict[str, Any] | None = None) -> Some[T] | None: + """Get the default value for the wrapped type. + + Args: + strict: Whether to strictly check types. + context: Additional context to pass to the validator. + + Returns: + The default value wrapped in a `Some` if there is one or None if not. + """ + return self.validator.get_default_value(strict=strict, context=context) + + @_frame_depth(1) + def dump_python( + self, + instance: T, + /, + *, + mode: Literal['json', 'python'] = 'python', + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool | Literal['none', 'warn', 'error'] = True, + serialize_as_any: bool = False, + context: dict[str, Any] | None = None, + ) -> Any: + """Dump an instance of the adapted type to a Python object. + + Args: + instance: The Python object to serialize. + mode: The output format. + include: Fields to include in the output. + exclude: Fields to exclude from the output. + by_alias: Whether to use alias names for field names. + exclude_unset: Whether to exclude unset fields. + exclude_defaults: Whether to exclude fields with default values. + exclude_none: Whether to exclude fields with None values. + round_trip: Whether to output the serialized data in a way that is compatible with deserialization. + warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + context: Additional context to pass to the serializer. + + Returns: + The serialized object. + """ + return self.serializer.to_python( + instance, + mode=mode, + by_alias=by_alias, + include=include, + exclude=exclude, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + round_trip=round_trip, + warnings=warnings, + serialize_as_any=serialize_as_any, + context=context, + ) + + @_frame_depth(1) + def dump_json( + self, + instance: T, + /, + *, + indent: int | None = None, + include: IncEx | None = None, + exclude: IncEx | None = None, + by_alias: bool = False, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool | Literal['none', 'warn', 'error'] = True, + serialize_as_any: bool = False, + context: dict[str, Any] | None = None, + ) -> bytes: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/json/#json-serialization + + Serialize an instance of the adapted type to JSON. + + Args: + instance: The instance to be serialized. + indent: Number of spaces for JSON indentation. + include: Fields to include. + exclude: Fields to exclude. + by_alias: Whether to use alias names for field names. + exclude_unset: Whether to exclude unset fields. + exclude_defaults: Whether to exclude fields with default values. + exclude_none: Whether to exclude fields with a value of `None`. + round_trip: Whether to serialize and deserialize the instance to ensure round-tripping. + warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + context: Additional context to pass to the serializer. + + Returns: + The JSON representation of the given instance as bytes. + """ + return self.serializer.to_json( + instance, + indent=indent, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + round_trip=round_trip, + warnings=warnings, + serialize_as_any=serialize_as_any, + context=context, + ) + + @_frame_depth(1) + def json_schema( + self, + *, + by_alias: bool = True, + ref_template: str = DEFAULT_REF_TEMPLATE, + schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, + mode: JsonSchemaMode = 'validation', + ) -> dict[str, Any]: + """Generate a JSON schema for the adapted type. + + Args: + by_alias: Whether to use alias names for field names. + ref_template: The format string used for generating $ref strings. + schema_generator: The generator class used for creating the schema. + mode: The mode to use for schema generation. + + Returns: + The JSON schema for the model as a dictionary. + """ + schema_generator_instance = schema_generator(by_alias=by_alias, ref_template=ref_template) + return schema_generator_instance.generate(self.core_schema, mode=mode) + + @staticmethod + def json_schemas( + inputs: Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]], + /, + *, + by_alias: bool = True, + title: str | None = None, + description: str | None = None, + ref_template: str = DEFAULT_REF_TEMPLATE, + schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema, + ) -> tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]: + """Generate a JSON schema including definitions from multiple type adapters. + + Args: + inputs: Inputs to schema generation. The first two items will form the keys of the (first) + output mapping; the type adapters will provide the core schemas that get converted into + definitions in the output JSON schema. + by_alias: Whether to use alias names. + title: The title for the schema. + description: The description for the schema. + ref_template: The format string used for generating $ref strings. + schema_generator: The generator class used for creating the schema. + + Returns: + A tuple where: + + - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and + whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have + JsonRef references to definitions that are defined in the second returned element.) + - The second element is a JSON schema containing all definitions referenced in the first returned + element, along with the optional title and description keys. + + """ + schema_generator_instance = schema_generator(by_alias=by_alias, ref_template=ref_template) + + inputs_ = [] + for key, mode, adapter in inputs: + with adapter._with_frame_depth(1): # +1 for json_schemas staticmethod + inputs_.append((key, mode, adapter.core_schema)) + + json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_) + + json_schema: dict[str, Any] = {} + if definitions: + json_schema['$defs'] = definitions + if title: + json_schema['title'] = title + if description: + json_schema['description'] = description + + return json_schemas_map, json_schema diff --git a/env/Lib/site-packages/pydantic/types.py b/env/Lib/site-packages/pydantic/types.py new file mode 100644 index 0000000..50f397e --- /dev/null +++ b/env/Lib/site-packages/pydantic/types.py @@ -0,0 +1,3043 @@ +"""The types module contains custom types used by pydantic.""" + +from __future__ import annotations as _annotations + +import base64 +import dataclasses as _dataclasses +import re +from datetime import date, datetime +from decimal import Decimal +from enum import Enum +from pathlib import Path +from types import ModuleType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Dict, + FrozenSet, + Generic, + Hashable, + Iterator, + List, + Pattern, + Set, + TypeVar, + Union, + cast, + get_args, + get_origin, +) +from uuid import UUID + +import annotated_types +from annotated_types import BaseMetadata, MaxLen, MinLen +from pydantic_core import CoreSchema, PydanticCustomError, core_schema +from typing_extensions import Annotated, Literal, Protocol, TypeAlias, TypeAliasType, deprecated + +from ._internal import ( + _core_utils, + _fields, + _internal_dataclass, + _typing_extra, + _utils, + _validators, +) +from ._migration import getattr_migration +from .annotated_handlers import GetCoreSchemaHandler, GetJsonSchemaHandler +from .errors import PydanticUserError +from .json_schema import JsonSchemaValue +from .warnings import PydanticDeprecatedSince20 + +__all__ = ( + 'Strict', + 'StrictStr', + 'conbytes', + 'conlist', + 'conset', + 'confrozenset', + 'constr', + 'ImportString', + 'conint', + 'PositiveInt', + 'NegativeInt', + 'NonNegativeInt', + 'NonPositiveInt', + 'confloat', + 'PositiveFloat', + 'NegativeFloat', + 'NonNegativeFloat', + 'NonPositiveFloat', + 'FiniteFloat', + 'condecimal', + 'UUID1', + 'UUID3', + 'UUID4', + 'UUID5', + 'FilePath', + 'DirectoryPath', + 'NewPath', + 'Json', + 'Secret', + 'SecretStr', + 'SecretBytes', + 'StrictBool', + 'StrictBytes', + 'StrictInt', + 'StrictFloat', + 'PaymentCardNumber', + 'ByteSize', + 'PastDate', + 'FutureDate', + 'PastDatetime', + 'FutureDatetime', + 'condate', + 'AwareDatetime', + 'NaiveDatetime', + 'AllowInfNan', + 'EncoderProtocol', + 'EncodedBytes', + 'EncodedStr', + 'Base64Encoder', + 'Base64Bytes', + 'Base64Str', + 'Base64UrlBytes', + 'Base64UrlStr', + 'GetPydanticSchema', + 'StringConstraints', + 'Tag', + 'Discriminator', + 'JsonValue', + 'OnErrorOmit', + 'FailFast', +) + + +T = TypeVar('T') + + +@_dataclasses.dataclass +class Strict(_fields.PydanticMetadata, BaseMetadata): + """Usage docs: https://docs.pydantic.dev/2.8/concepts/strict_mode/#strict-mode-with-annotated-strict + + A field metadata class to indicate that a field should be validated in strict mode. + + Attributes: + strict: Whether to validate the field in strict mode. + + Example: + ```python + from typing_extensions import Annotated + + from pydantic.types import Strict + + StrictBool = Annotated[bool, Strict()] + ``` + """ + + strict: bool = True + + def __hash__(self) -> int: + return hash(self.strict) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BOOLEAN TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +StrictBool = Annotated[bool, Strict()] +"""A boolean that must be either ``True`` or ``False``.""" + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INTEGER TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +def conint( + *, + strict: bool | None = None, + gt: int | None = None, + ge: int | None = None, + lt: int | None = None, + le: int | None = None, + multiple_of: int | None = None, +) -> type[int]: + """ + !!! warning "Discouraged" + This function is **discouraged** in favor of using + [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with + [`Field`][pydantic.fields.Field] instead. + + This function will be **deprecated** in Pydantic 3.0. + + The reason is that `conint` returns a type, which doesn't play well with static analysis tools. + + === ":x: Don't do this" + ```py + from pydantic import BaseModel, conint + + class Foo(BaseModel): + bar: conint(strict=True, gt=0) + ``` + + === ":white_check_mark: Do this" + ```py + from typing_extensions import Annotated + + from pydantic import BaseModel, Field + + class Foo(BaseModel): + bar: Annotated[int, Field(strict=True, gt=0)] + ``` + + A wrapper around `int` that allows for additional constraints. + + Args: + strict: Whether to validate the integer in strict mode. Defaults to `None`. + gt: The value must be greater than this. + ge: The value must be greater than or equal to this. + lt: The value must be less than this. + le: The value must be less than or equal to this. + multiple_of: The value must be a multiple of this. + + Returns: + The wrapped integer type. + + ```py + from pydantic import BaseModel, ValidationError, conint + + class ConstrainedExample(BaseModel): + constrained_int: conint(gt=1) + + m = ConstrainedExample(constrained_int=2) + print(repr(m)) + #> ConstrainedExample(constrained_int=2) + + try: + ConstrainedExample(constrained_int=0) + except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'greater_than', + 'loc': ('constrained_int',), + 'msg': 'Input should be greater than 1', + 'input': 0, + 'ctx': {'gt': 1}, + 'url': 'https://errors.pydantic.dev/2/v/greater_than', + } + ] + ''' + ``` + + """ # noqa: D212 + return Annotated[ # pyright: ignore[reportReturnType] + int, + Strict(strict) if strict is not None else None, + annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le), + annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None, + ] + + +PositiveInt = Annotated[int, annotated_types.Gt(0)] +"""An integer that must be greater than zero. + +```py +from pydantic import BaseModel, PositiveInt, ValidationError + +class Model(BaseModel): + positive_int: PositiveInt + +m = Model(positive_int=1) +print(repr(m)) +#> Model(positive_int=1) + +try: + Model(positive_int=-1) +except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'greater_than', + 'loc': ('positive_int',), + 'msg': 'Input should be greater than 0', + 'input': -1, + 'ctx': {'gt': 0}, + 'url': 'https://errors.pydantic.dev/2/v/greater_than', + } + ] + ''' +``` +""" +NegativeInt = Annotated[int, annotated_types.Lt(0)] +"""An integer that must be less than zero. + +```py +from pydantic import BaseModel, NegativeInt, ValidationError + +class Model(BaseModel): + negative_int: NegativeInt + +m = Model(negative_int=-1) +print(repr(m)) +#> Model(negative_int=-1) + +try: + Model(negative_int=1) +except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'less_than', + 'loc': ('negative_int',), + 'msg': 'Input should be less than 0', + 'input': 1, + 'ctx': {'lt': 0}, + 'url': 'https://errors.pydantic.dev/2/v/less_than', + } + ] + ''' +``` +""" +NonPositiveInt = Annotated[int, annotated_types.Le(0)] +"""An integer that must be less than or equal to zero. + +```py +from pydantic import BaseModel, NonPositiveInt, ValidationError + +class Model(BaseModel): + non_positive_int: NonPositiveInt + +m = Model(non_positive_int=0) +print(repr(m)) +#> Model(non_positive_int=0) + +try: + Model(non_positive_int=1) +except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'less_than_equal', + 'loc': ('non_positive_int',), + 'msg': 'Input should be less than or equal to 0', + 'input': 1, + 'ctx': {'le': 0}, + 'url': 'https://errors.pydantic.dev/2/v/less_than_equal', + } + ] + ''' +``` +""" +NonNegativeInt = Annotated[int, annotated_types.Ge(0)] +"""An integer that must be greater than or equal to zero. + +```py +from pydantic import BaseModel, NonNegativeInt, ValidationError + +class Model(BaseModel): + non_negative_int: NonNegativeInt + +m = Model(non_negative_int=0) +print(repr(m)) +#> Model(non_negative_int=0) + +try: + Model(non_negative_int=-1) +except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'greater_than_equal', + 'loc': ('non_negative_int',), + 'msg': 'Input should be greater than or equal to 0', + 'input': -1, + 'ctx': {'ge': 0}, + 'url': 'https://errors.pydantic.dev/2/v/greater_than_equal', + } + ] + ''' +``` +""" +StrictInt = Annotated[int, Strict()] +"""An integer that must be validated in strict mode. + +```py +from pydantic import BaseModel, StrictInt, ValidationError + +class StrictIntModel(BaseModel): + strict_int: StrictInt + +try: + StrictIntModel(strict_int=3.14159) +except ValidationError as e: + print(e) + ''' + 1 validation error for StrictIntModel + strict_int + Input should be a valid integer [type=int_type, input_value=3.14159, input_type=float] + ''' +``` +""" + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FLOAT TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +@_dataclasses.dataclass +class AllowInfNan(_fields.PydanticMetadata): + """A field metadata class to indicate that a field should allow ``-inf``, ``inf``, and ``nan``.""" + + allow_inf_nan: bool = True + + def __hash__(self) -> int: + return hash(self.allow_inf_nan) + + +def confloat( + *, + strict: bool | None = None, + gt: float | None = None, + ge: float | None = None, + lt: float | None = None, + le: float | None = None, + multiple_of: float | None = None, + allow_inf_nan: bool | None = None, +) -> type[float]: + """ + !!! warning "Discouraged" + This function is **discouraged** in favor of using + [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with + [`Field`][pydantic.fields.Field] instead. + + This function will be **deprecated** in Pydantic 3.0. + + The reason is that `confloat` returns a type, which doesn't play well with static analysis tools. + + === ":x: Don't do this" + ```py + from pydantic import BaseModel, confloat + + class Foo(BaseModel): + bar: confloat(strict=True, gt=0) + ``` + + === ":white_check_mark: Do this" + ```py + from typing_extensions import Annotated + + from pydantic import BaseModel, Field + + class Foo(BaseModel): + bar: Annotated[float, Field(strict=True, gt=0)] + ``` + + A wrapper around `float` that allows for additional constraints. + + Args: + strict: Whether to validate the float in strict mode. + gt: The value must be greater than this. + ge: The value must be greater than or equal to this. + lt: The value must be less than this. + le: The value must be less than or equal to this. + multiple_of: The value must be a multiple of this. + allow_inf_nan: Whether to allow `-inf`, `inf`, and `nan`. + + Returns: + The wrapped float type. + + ```py + from pydantic import BaseModel, ValidationError, confloat + + class ConstrainedExample(BaseModel): + constrained_float: confloat(gt=1.0) + + m = ConstrainedExample(constrained_float=1.1) + print(repr(m)) + #> ConstrainedExample(constrained_float=1.1) + + try: + ConstrainedExample(constrained_float=0.9) + except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'greater_than', + 'loc': ('constrained_float',), + 'msg': 'Input should be greater than 1', + 'input': 0.9, + 'ctx': {'gt': 1.0}, + 'url': 'https://errors.pydantic.dev/2/v/greater_than', + } + ] + ''' + ``` + """ # noqa: D212 + return Annotated[ # pyright: ignore[reportReturnType] + float, + Strict(strict) if strict is not None else None, + annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le), + annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None, + AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None, + ] + + +PositiveFloat = Annotated[float, annotated_types.Gt(0)] +"""A float that must be greater than zero. + +```py +from pydantic import BaseModel, PositiveFloat, ValidationError + +class Model(BaseModel): + positive_float: PositiveFloat + +m = Model(positive_float=1.0) +print(repr(m)) +#> Model(positive_float=1.0) + +try: + Model(positive_float=-1.0) +except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'greater_than', + 'loc': ('positive_float',), + 'msg': 'Input should be greater than 0', + 'input': -1.0, + 'ctx': {'gt': 0.0}, + 'url': 'https://errors.pydantic.dev/2/v/greater_than', + } + ] + ''' +``` +""" +NegativeFloat = Annotated[float, annotated_types.Lt(0)] +"""A float that must be less than zero. + +```py +from pydantic import BaseModel, NegativeFloat, ValidationError + +class Model(BaseModel): + negative_float: NegativeFloat + +m = Model(negative_float=-1.0) +print(repr(m)) +#> Model(negative_float=-1.0) + +try: + Model(negative_float=1.0) +except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'less_than', + 'loc': ('negative_float',), + 'msg': 'Input should be less than 0', + 'input': 1.0, + 'ctx': {'lt': 0.0}, + 'url': 'https://errors.pydantic.dev/2/v/less_than', + } + ] + ''' +``` +""" +NonPositiveFloat = Annotated[float, annotated_types.Le(0)] +"""A float that must be less than or equal to zero. + +```py +from pydantic import BaseModel, NonPositiveFloat, ValidationError + +class Model(BaseModel): + non_positive_float: NonPositiveFloat + +m = Model(non_positive_float=0.0) +print(repr(m)) +#> Model(non_positive_float=0.0) + +try: + Model(non_positive_float=1.0) +except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'less_than_equal', + 'loc': ('non_positive_float',), + 'msg': 'Input should be less than or equal to 0', + 'input': 1.0, + 'ctx': {'le': 0.0}, + 'url': 'https://errors.pydantic.dev/2/v/less_than_equal', + } + ] + ''' +``` +""" +NonNegativeFloat = Annotated[float, annotated_types.Ge(0)] +"""A float that must be greater than or equal to zero. + +```py +from pydantic import BaseModel, NonNegativeFloat, ValidationError + +class Model(BaseModel): + non_negative_float: NonNegativeFloat + +m = Model(non_negative_float=0.0) +print(repr(m)) +#> Model(non_negative_float=0.0) + +try: + Model(non_negative_float=-1.0) +except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'greater_than_equal', + 'loc': ('non_negative_float',), + 'msg': 'Input should be greater than or equal to 0', + 'input': -1.0, + 'ctx': {'ge': 0.0}, + 'url': 'https://errors.pydantic.dev/2/v/greater_than_equal', + } + ] + ''' +``` +""" +StrictFloat = Annotated[float, Strict(True)] +"""A float that must be validated in strict mode. + +```py +from pydantic import BaseModel, StrictFloat, ValidationError + +class StrictFloatModel(BaseModel): + strict_float: StrictFloat + +try: + StrictFloatModel(strict_float='1.0') +except ValidationError as e: + print(e) + ''' + 1 validation error for StrictFloatModel + strict_float + Input should be a valid number [type=float_type, input_value='1.0', input_type=str] + ''' +``` +""" +FiniteFloat = Annotated[float, AllowInfNan(False)] +"""A float that must be finite (not ``-inf``, ``inf``, or ``nan``). + +```py +from pydantic import BaseModel, FiniteFloat + +class Model(BaseModel): + finite: FiniteFloat + +m = Model(finite=1.0) +print(m) +#> finite=1.0 +``` +""" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTES TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +def conbytes( + *, + min_length: int | None = None, + max_length: int | None = None, + strict: bool | None = None, +) -> type[bytes]: + """A wrapper around `bytes` that allows for additional constraints. + + Args: + min_length: The minimum length of the bytes. + max_length: The maximum length of the bytes. + strict: Whether to validate the bytes in strict mode. + + Returns: + The wrapped bytes type. + """ + return Annotated[ # pyright: ignore[reportReturnType] + bytes, + Strict(strict) if strict is not None else None, + annotated_types.Len(min_length or 0, max_length), + ] + + +StrictBytes = Annotated[bytes, Strict()] +"""A bytes that must be validated in strict mode.""" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ STRING TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +@_dataclasses.dataclass(frozen=True) +class StringConstraints(annotated_types.GroupedMetadata): + """Usage docs: https://docs.pydantic.dev/2.8/concepts/fields/#string-constraints + + Apply constraints to `str` types. + + Attributes: + strip_whitespace: Whether to remove leading and trailing whitespace. + to_upper: Whether to convert the string to uppercase. + to_lower: Whether to convert the string to lowercase. + strict: Whether to validate the string in strict mode. + min_length: The minimum length of the string. + max_length: The maximum length of the string. + pattern: A regex pattern that the string must match. + """ + + strip_whitespace: bool | None = None + to_upper: bool | None = None + to_lower: bool | None = None + strict: bool | None = None + min_length: int | None = None + max_length: int | None = None + pattern: str | Pattern[str] | None = None + + def __iter__(self) -> Iterator[BaseMetadata]: + if self.min_length is not None: + yield MinLen(self.min_length) + if self.max_length is not None: + yield MaxLen(self.max_length) + if self.strict is not None: + yield Strict(self.strict) + if ( + self.strip_whitespace is not None + or self.pattern is not None + or self.to_lower is not None + or self.to_upper is not None + ): + yield _fields.pydantic_general_metadata( + strip_whitespace=self.strip_whitespace, + to_upper=self.to_upper, + to_lower=self.to_lower, + pattern=self.pattern, + ) + + +def constr( + *, + strip_whitespace: bool | None = None, + to_upper: bool | None = None, + to_lower: bool | None = None, + strict: bool | None = None, + min_length: int | None = None, + max_length: int | None = None, + pattern: str | Pattern[str] | None = None, +) -> type[str]: + """ + !!! warning "Discouraged" + This function is **discouraged** in favor of using + [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with + [`StringConstraints`][pydantic.types.StringConstraints] instead. + + This function will be **deprecated** in Pydantic 3.0. + + The reason is that `constr` returns a type, which doesn't play well with static analysis tools. + + === ":x: Don't do this" + ```py + from pydantic import BaseModel, constr + + class Foo(BaseModel): + bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$') + ``` + + === ":white_check_mark: Do this" + ```py + from typing_extensions import Annotated + + from pydantic import BaseModel, StringConstraints + + class Foo(BaseModel): + bar: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$')] + ``` + + A wrapper around `str` that allows for additional constraints. + + ```py + from pydantic import BaseModel, constr + + class Foo(BaseModel): + bar: constr(strip_whitespace=True, to_upper=True, pattern=r'^[A-Z]+$') + + + foo = Foo(bar=' hello ') + print(foo) + #> bar='HELLO' + ``` + + Args: + strip_whitespace: Whether to remove leading and trailing whitespace. + to_upper: Whether to turn all characters to uppercase. + to_lower: Whether to turn all characters to lowercase. + strict: Whether to validate the string in strict mode. + min_length: The minimum length of the string. + max_length: The maximum length of the string. + pattern: A regex pattern to validate the string against. + + Returns: + The wrapped string type. + """ # noqa: D212 + return Annotated[ # pyright: ignore[reportReturnType] + str, + StringConstraints( + strip_whitespace=strip_whitespace, + to_upper=to_upper, + to_lower=to_lower, + strict=strict, + min_length=min_length, + max_length=max_length, + pattern=pattern, + ), + ] + + +StrictStr = Annotated[str, Strict()] +"""A string that must be validated in strict mode.""" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~ COLLECTION TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +HashableItemType = TypeVar('HashableItemType', bound=Hashable) + + +def conset( + item_type: type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None +) -> type[set[HashableItemType]]: + """A wrapper around `typing.Set` that allows for additional constraints. + + Args: + item_type: The type of the items in the set. + min_length: The minimum length of the set. + max_length: The maximum length of the set. + + Returns: + The wrapped set type. + """ + return Annotated[Set[item_type], annotated_types.Len(min_length or 0, max_length)] # pyright: ignore[reportReturnType] + + +def confrozenset( + item_type: type[HashableItemType], *, min_length: int | None = None, max_length: int | None = None +) -> type[frozenset[HashableItemType]]: + """A wrapper around `typing.FrozenSet` that allows for additional constraints. + + Args: + item_type: The type of the items in the frozenset. + min_length: The minimum length of the frozenset. + max_length: The maximum length of the frozenset. + + Returns: + The wrapped frozenset type. + """ + return Annotated[FrozenSet[item_type], annotated_types.Len(min_length or 0, max_length)] # pyright: ignore[reportReturnType] + + +AnyItemType = TypeVar('AnyItemType') + + +def conlist( + item_type: type[AnyItemType], + *, + min_length: int | None = None, + max_length: int | None = None, + unique_items: bool | None = None, +) -> type[list[AnyItemType]]: + """A wrapper around typing.List that adds validation. + + Args: + item_type: The type of the items in the list. + min_length: The minimum length of the list. Defaults to None. + max_length: The maximum length of the list. Defaults to None. + unique_items: Whether the items in the list must be unique. Defaults to None. + !!! warning Deprecated + The `unique_items` parameter is deprecated, use `Set` instead. + See [this issue](https://github.com/pydantic/pydantic-core/issues/296) for more details. + + Returns: + The wrapped list type. + """ + if unique_items is not None: + raise PydanticUserError( + ( + '`unique_items` is removed, use `Set` instead' + '(this feature is discussed in https://github.com/pydantic/pydantic-core/issues/296)' + ), + code='removed-kwargs', + ) + return Annotated[List[item_type], annotated_types.Len(min_length or 0, max_length)] # pyright: ignore[reportReturnType] + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~ IMPORT STRING TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +AnyType = TypeVar('AnyType') +if TYPE_CHECKING: + ImportString = Annotated[AnyType, ...] +else: + + class ImportString: + """A type that can be used to import a type from a string. + + `ImportString` expects a string and loads the Python object importable at that dotted path. + Attributes of modules may be separated from the module by `:` or `.`, e.g. if `'math:cos'` was provided, + the resulting field value would be the function`cos`. If a `.` is used and both an attribute and submodule + are present at the same path, the module will be preferred. + + On model instantiation, pointers will be evaluated and imported. There is + some nuance to this behavior, demonstrated in the examples below. + + **Good behavior:** + ```py + from math import cos + + from pydantic import BaseModel, Field, ImportString, ValidationError + + + class ImportThings(BaseModel): + obj: ImportString + + + # A string value will cause an automatic import + my_cos = ImportThings(obj='math.cos') + + # You can use the imported function as you would expect + cos_of_0 = my_cos.obj(0) + assert cos_of_0 == 1 + + + # A string whose value cannot be imported will raise an error + try: + ImportThings(obj='foo.bar') + except ValidationError as e: + print(e) + ''' + 1 validation error for ImportThings + obj + Invalid python path: No module named 'foo.bar' [type=import_error, input_value='foo.bar', input_type=str] + ''' + + + # Actual python objects can be assigned as well + my_cos = ImportThings(obj=cos) + my_cos_2 = ImportThings(obj='math.cos') + my_cos_3 = ImportThings(obj='math:cos') + assert my_cos == my_cos_2 == my_cos_3 + + + # You can set default field value either as Python object: + class ImportThingsDefaultPyObj(BaseModel): + obj: ImportString = math.cos + + + # or as a string value (but only if used with `validate_default=True`) + class ImportThingsDefaultString(BaseModel): + obj: ImportString = Field(default='math.cos', validate_default=True) + + + my_cos_default1 = ImportThingsDefaultPyObj() + my_cos_default2 = ImportThingsDefaultString() + assert my_cos_default1.obj == my_cos_default2.obj == math.cos + + + # note: this will not work! + class ImportThingsMissingValidateDefault(BaseModel): + obj: ImportString = 'math.cos' + + my_cos_default3 = ImportThingsMissingValidateDefault() + assert my_cos_default3.obj == 'math.cos' # just string, not evaluated + ``` + + Serializing an `ImportString` type to json is also possible. + + ```py + from pydantic import BaseModel, ImportString + + + class ImportThings(BaseModel): + obj: ImportString + + + # Create an instance + m = ImportThings(obj='math.cos') + print(m) + #> obj= + print(m.model_dump_json()) + #> {"obj":"math.cos"} + ``` + """ + + @classmethod + def __class_getitem__(cls, item: AnyType) -> AnyType: + return Annotated[item, cls()] + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + serializer = core_schema.plain_serializer_function_ser_schema(cls._serialize, when_used='json') + if cls is source: + # Treat bare usage of ImportString (`schema is None`) as the same as ImportString[Any] + return core_schema.no_info_plain_validator_function( + function=_validators.import_string, serialization=serializer + ) + else: + return core_schema.no_info_before_validator_function( + function=_validators.import_string, schema=handler(source), serialization=serializer + ) + + @classmethod + def __get_pydantic_json_schema__(cls, cs: CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue: + return handler(core_schema.str_schema()) + + @staticmethod + def _serialize(v: Any) -> str: + if isinstance(v, ModuleType): + return v.__name__ + elif hasattr(v, '__module__') and hasattr(v, '__name__'): + return f'{v.__module__}.{v.__name__}' + else: + return v + + def __repr__(self) -> str: + return 'ImportString' + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DECIMAL TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +def condecimal( + *, + strict: bool | None = None, + gt: int | Decimal | None = None, + ge: int | Decimal | None = None, + lt: int | Decimal | None = None, + le: int | Decimal | None = None, + multiple_of: int | Decimal | None = None, + max_digits: int | None = None, + decimal_places: int | None = None, + allow_inf_nan: bool | None = None, +) -> type[Decimal]: + """ + !!! warning "Discouraged" + This function is **discouraged** in favor of using + [`Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated) with + [`Field`][pydantic.fields.Field] instead. + + This function will be **deprecated** in Pydantic 3.0. + + The reason is that `condecimal` returns a type, which doesn't play well with static analysis tools. + + === ":x: Don't do this" + ```py + from pydantic import BaseModel, condecimal + + class Foo(BaseModel): + bar: condecimal(strict=True, allow_inf_nan=True) + ``` + + === ":white_check_mark: Do this" + ```py + from decimal import Decimal + + from typing_extensions import Annotated + + from pydantic import BaseModel, Field + + class Foo(BaseModel): + bar: Annotated[Decimal, Field(strict=True, allow_inf_nan=True)] + ``` + + A wrapper around Decimal that adds validation. + + Args: + strict: Whether to validate the value in strict mode. Defaults to `None`. + gt: The value must be greater than this. Defaults to `None`. + ge: The value must be greater than or equal to this. Defaults to `None`. + lt: The value must be less than this. Defaults to `None`. + le: The value must be less than or equal to this. Defaults to `None`. + multiple_of: The value must be a multiple of this. Defaults to `None`. + max_digits: The maximum number of digits. Defaults to `None`. + decimal_places: The number of decimal places. Defaults to `None`. + allow_inf_nan: Whether to allow infinity and NaN. Defaults to `None`. + + ```py + from decimal import Decimal + + from pydantic import BaseModel, ValidationError, condecimal + + class ConstrainedExample(BaseModel): + constrained_decimal: condecimal(gt=Decimal('1.0')) + + m = ConstrainedExample(constrained_decimal=Decimal('1.1')) + print(repr(m)) + #> ConstrainedExample(constrained_decimal=Decimal('1.1')) + + try: + ConstrainedExample(constrained_decimal=Decimal('0.9')) + except ValidationError as e: + print(e.errors()) + ''' + [ + { + 'type': 'greater_than', + 'loc': ('constrained_decimal',), + 'msg': 'Input should be greater than 1.0', + 'input': Decimal('0.9'), + 'ctx': {'gt': Decimal('1.0')}, + 'url': 'https://errors.pydantic.dev/2/v/greater_than', + } + ] + ''' + ``` + """ # noqa: D212 + return Annotated[ # pyright: ignore[reportReturnType] + Decimal, + Strict(strict) if strict is not None else None, + annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le), + annotated_types.MultipleOf(multiple_of) if multiple_of is not None else None, + _fields.pydantic_general_metadata(max_digits=max_digits, decimal_places=decimal_places), + AllowInfNan(allow_inf_nan) if allow_inf_nan is not None else None, + ] + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UUID TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +@_dataclasses.dataclass(**_internal_dataclass.slots_true) +class UuidVersion: + """A field metadata class to indicate a [UUID](https://docs.python.org/3/library/uuid.html) version.""" + + uuid_version: Literal[1, 3, 4, 5] + + def __get_pydantic_json_schema__( + self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = handler(core_schema) + field_schema.pop('anyOf', None) # remove the bytes/str union + field_schema.update(type='string', format=f'uuid{self.uuid_version}') + return field_schema + + def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + if isinstance(self, source): + # used directly as a type + return core_schema.uuid_schema(version=self.uuid_version) + else: + # update existing schema with self.uuid_version + schema = handler(source) + _check_annotated_type(schema['type'], 'uuid', self.__class__.__name__) + schema['version'] = self.uuid_version # type: ignore + return schema + + def __hash__(self) -> int: + return hash(type(self.uuid_version)) + + +UUID1 = Annotated[UUID, UuidVersion(1)] +"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 1. + +```py +import uuid + +from pydantic import UUID1, BaseModel + +class Model(BaseModel): + uuid1: UUID1 + +Model(uuid1=uuid.uuid1()) +``` +""" +UUID3 = Annotated[UUID, UuidVersion(3)] +"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 3. + +```py +import uuid + +from pydantic import UUID3, BaseModel + +class Model(BaseModel): + uuid3: UUID3 + +Model(uuid3=uuid.uuid3(uuid.NAMESPACE_DNS, 'pydantic.org')) +``` +""" +UUID4 = Annotated[UUID, UuidVersion(4)] +"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 4. + +```py +import uuid + +from pydantic import UUID4, BaseModel + +class Model(BaseModel): + uuid4: UUID4 + +Model(uuid4=uuid.uuid4()) +``` +""" +UUID5 = Annotated[UUID, UuidVersion(5)] +"""A [UUID](https://docs.python.org/3/library/uuid.html) that must be version 5. + +```py +import uuid + +from pydantic import UUID5, BaseModel + +class Model(BaseModel): + uuid5: UUID5 + +Model(uuid5=uuid.uuid5(uuid.NAMESPACE_DNS, 'pydantic.org')) +``` +""" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PATH TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +@_dataclasses.dataclass +class PathType: + path_type: Literal['file', 'dir', 'new'] + + def __get_pydantic_json_schema__( + self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = handler(core_schema) + format_conversion = {'file': 'file-path', 'dir': 'directory-path'} + field_schema.update(format=format_conversion.get(self.path_type, 'path'), type='string') + return field_schema + + def __get_pydantic_core_schema__(self, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + function_lookup = { + 'file': cast(core_schema.WithInfoValidatorFunction, self.validate_file), + 'dir': cast(core_schema.WithInfoValidatorFunction, self.validate_directory), + 'new': cast(core_schema.WithInfoValidatorFunction, self.validate_new), + } + + return core_schema.with_info_after_validator_function( + function_lookup[self.path_type], + handler(source), + ) + + @staticmethod + def validate_file(path: Path, _: core_schema.ValidationInfo) -> Path: + if path.is_file(): + return path + else: + raise PydanticCustomError('path_not_file', 'Path does not point to a file') + + @staticmethod + def validate_directory(path: Path, _: core_schema.ValidationInfo) -> Path: + if path.is_dir(): + return path + else: + raise PydanticCustomError('path_not_directory', 'Path does not point to a directory') + + @staticmethod + def validate_new(path: Path, _: core_schema.ValidationInfo) -> Path: + if path.exists(): + raise PydanticCustomError('path_exists', 'Path already exists') + elif not path.parent.exists(): + raise PydanticCustomError('parent_does_not_exist', 'Parent directory does not exist') + else: + return path + + def __hash__(self) -> int: + return hash(type(self.path_type)) + + +FilePath = Annotated[Path, PathType('file')] +"""A path that must point to a file. + +```py +from pathlib import Path + +from pydantic import BaseModel, FilePath, ValidationError + +class Model(BaseModel): + f: FilePath + +path = Path('text.txt') +path.touch() +m = Model(f='text.txt') +print(m.model_dump()) +#> {'f': PosixPath('text.txt')} +path.unlink() + +path = Path('directory') +path.mkdir(exist_ok=True) +try: + Model(f='directory') # directory +except ValidationError as e: + print(e) + ''' + 1 validation error for Model + f + Path does not point to a file [type=path_not_file, input_value='directory', input_type=str] + ''' +path.rmdir() + +try: + Model(f='not-exists-file') +except ValidationError as e: + print(e) + ''' + 1 validation error for Model + f + Path does not point to a file [type=path_not_file, input_value='not-exists-file', input_type=str] + ''' +``` +""" +DirectoryPath = Annotated[Path, PathType('dir')] +"""A path that must point to a directory. + +```py +from pathlib import Path + +from pydantic import BaseModel, DirectoryPath, ValidationError + +class Model(BaseModel): + f: DirectoryPath + +path = Path('directory/') +path.mkdir() +m = Model(f='directory/') +print(m.model_dump()) +#> {'f': PosixPath('directory')} +path.rmdir() + +path = Path('file.txt') +path.touch() +try: + Model(f='file.txt') # file +except ValidationError as e: + print(e) + ''' + 1 validation error for Model + f + Path does not point to a directory [type=path_not_directory, input_value='file.txt', input_type=str] + ''' +path.unlink() + +try: + Model(f='not-exists-directory') +except ValidationError as e: + print(e) + ''' + 1 validation error for Model + f + Path does not point to a directory [type=path_not_directory, input_value='not-exists-directory', input_type=str] + ''' +``` +""" +NewPath = Annotated[Path, PathType('new')] +"""A path for a new file or directory that must not already exist. The parent directory must already exist.""" + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JSON TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +if TYPE_CHECKING: + # Json[list[str]] will be recognized by type checkers as list[str] + Json = Annotated[AnyType, ...] + +else: + + class Json: + """A special type wrapper which loads JSON before parsing. + + You can use the `Json` data type to make Pydantic first load a raw JSON string before + validating the loaded data into the parametrized type: + + ```py + from typing import Any, List + + from pydantic import BaseModel, Json, ValidationError + + + class AnyJsonModel(BaseModel): + json_obj: Json[Any] + + + class ConstrainedJsonModel(BaseModel): + json_obj: Json[List[int]] + + + print(AnyJsonModel(json_obj='{"b": 1}')) + #> json_obj={'b': 1} + print(ConstrainedJsonModel(json_obj='[1, 2, 3]')) + #> json_obj=[1, 2, 3] + + try: + ConstrainedJsonModel(json_obj=12) + except ValidationError as e: + print(e) + ''' + 1 validation error for ConstrainedJsonModel + json_obj + JSON input should be string, bytes or bytearray [type=json_type, input_value=12, input_type=int] + ''' + + try: + ConstrainedJsonModel(json_obj='[a, b]') + except ValidationError as e: + print(e) + ''' + 1 validation error for ConstrainedJsonModel + json_obj + Invalid JSON: expected value at line 1 column 2 [type=json_invalid, input_value='[a, b]', input_type=str] + ''' + + try: + ConstrainedJsonModel(json_obj='["a", "b"]') + except ValidationError as e: + print(e) + ''' + 2 validation errors for ConstrainedJsonModel + json_obj.0 + Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str] + json_obj.1 + Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='b', input_type=str] + ''' + ``` + + When you dump the model using `model_dump` or `model_dump_json`, the dumped value will be the result of validation, + not the original JSON string. However, you can use the argument `round_trip=True` to get the original JSON string back: + + ```py + from typing import List + + from pydantic import BaseModel, Json + + + class ConstrainedJsonModel(BaseModel): + json_obj: Json[List[int]] + + + print(ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json()) + #> {"json_obj":[1,2,3]} + print( + ConstrainedJsonModel(json_obj='[1, 2, 3]').model_dump_json(round_trip=True) + ) + #> {"json_obj":"[1,2,3]"} + ``` + """ + + @classmethod + def __class_getitem__(cls, item: AnyType) -> AnyType: + return Annotated[item, cls()] + + @classmethod + def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + if cls is source: + return core_schema.json_schema(None) + else: + return core_schema.json_schema(handler(source)) + + def __repr__(self) -> str: + return 'Json' + + def __hash__(self) -> int: + return hash(type(self)) + + def __eq__(self, other: Any) -> bool: + return type(other) == type(self) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SECRET TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +SecretType = TypeVar('SecretType') + + +class _SecretBase(Generic[SecretType]): + def __init__(self, secret_value: SecretType) -> None: + self._secret_value: SecretType = secret_value + + def get_secret_value(self) -> SecretType: + """Get the secret value. + + Returns: + The secret value. + """ + return self._secret_value + + def __eq__(self, other: Any) -> bool: + return isinstance(other, self.__class__) and self.get_secret_value() == other.get_secret_value() + + def __hash__(self) -> int: + return hash(self.get_secret_value()) + + def __str__(self) -> str: + return str(self._display()) + + def __repr__(self) -> str: + return f'{self.__class__.__name__}({self._display()!r})' + + def _display(self) -> str | bytes: + raise NotImplementedError + + +class Secret(_SecretBase[SecretType]): + """A generic base class used for defining a field with sensitive information that you do not want to be visible in logging or tracebacks. + + You may either directly parametrize `Secret` with a type, or subclass from `Secret` with a parametrized type. The benefit of subclassing + is that you can define a custom `_display` method, which will be used for `repr()` and `str()` methods. The examples below demonstrate both + ways of using `Secret` to create a new secret type. + + 1. Directly parametrizing `Secret` with a type: + + ```py + from pydantic import BaseModel, Secret + + SecretBool = Secret[bool] + + class Model(BaseModel): + secret_bool: SecretBool + + m = Model(secret_bool=True) + print(m.model_dump()) + #> {'secret_bool': Secret('**********')} + + print(m.model_dump_json()) + #> {"secret_bool":"**********"} + + print(m.secret_bool.get_secret_value()) + #> True + ``` + + 2. Subclassing from parametrized `Secret`: + + ```py + from datetime import date + + from pydantic import BaseModel, Secret + + class SecretDate(Secret[date]): + def _display(self) -> str: + return '****/**/**' + + class Model(BaseModel): + secret_date: SecretDate + + m = Model(secret_date=date(2022, 1, 1)) + print(m.model_dump()) + #> {'secret_date': SecretDate('****/**/**')} + + print(m.model_dump_json()) + #> {"secret_date":"****/**/**"} + + print(m.secret_date.get_secret_value()) + #> 2022-01-01 + ``` + + The value returned by the `_display` method will be used for `repr()` and `str()`. + """ + + def _display(self) -> str | bytes: + return '**********' if self.get_secret_value() else '' + + @classmethod + def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + inner_type = None + # if origin_type is Secret, then cls is a GenericAlias, and we can extract the inner type directly + origin_type = get_origin(source) + if origin_type is not None: + inner_type = get_args(source)[0] + # otherwise, we need to get the inner type from the base class + else: + bases = getattr(cls, '__orig_bases__', getattr(cls, '__bases__', [])) + for base in bases: + if get_origin(base) is Secret: + inner_type = get_args(base)[0] + if bases == [] or inner_type is None: + raise TypeError( + f"Can't get secret type from {cls.__name__}. " + 'Please use Secret[], or subclass from Secret[] instead.' + ) + + inner_schema = handler.generate_schema(inner_type) # type: ignore + + def validate_secret_value(value, handler) -> Secret[SecretType]: + if isinstance(value, Secret): + value = value.get_secret_value() + validated_inner = handler(value) + return cls(validated_inner) + + def serialize(value: Secret[SecretType], info: core_schema.SerializationInfo) -> str | Secret[SecretType]: + if info.mode == 'json': + return str(value) + else: + return value + + return core_schema.json_or_python_schema( + python_schema=core_schema.no_info_wrap_validator_function( + validate_secret_value, + inner_schema, + ), + json_schema=core_schema.no_info_after_validator_function(lambda x: cls(x), inner_schema), + serialization=core_schema.plain_serializer_function_ser_schema( + serialize, + info_arg=True, + when_used='always', + ), + ) + + +def _secret_display(value: SecretType) -> str: # type: ignore + return '**********' if value else '' + + +class _SecretField(_SecretBase[SecretType]): + _inner_schema: ClassVar[CoreSchema] + _error_kind: ClassVar[str] + + @classmethod + def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + def serialize( + value: _SecretField[SecretType], info: core_schema.SerializationInfo + ) -> str | _SecretField[SecretType]: + if info.mode == 'json': + # we want the output to always be string without the `b'` prefix for bytes, + # hence we just use `secret_display` + return _secret_display(value.get_secret_value()) + else: + return value + + def get_json_schema(_core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler) -> JsonSchemaValue: + json_schema = handler(cls._inner_schema) + _utils.update_not_none( + json_schema, + type='string', + writeOnly=True, + format='password', + ) + return json_schema + + json_schema = core_schema.no_info_after_validator_function( + source, # construct the type + cls._inner_schema, + ) + + def get_secret_schema(strict: bool) -> CoreSchema: + return core_schema.json_or_python_schema( + python_schema=core_schema.union_schema( + [ + core_schema.is_instance_schema(source), + json_schema, + ], + custom_error_type=cls._error_kind, + strict=strict, + ), + json_schema=json_schema, + serialization=core_schema.plain_serializer_function_ser_schema( + serialize, + info_arg=True, + return_schema=core_schema.str_schema(), + when_used='json', + ), + ) + + return core_schema.lax_or_strict_schema( + lax_schema=get_secret_schema(strict=False), + strict_schema=get_secret_schema(strict=True), + metadata={'pydantic_js_functions': [get_json_schema]}, + ) + + +class SecretStr(_SecretField[str]): + """A string used for storing sensitive information that you do not want to be visible in logging or tracebacks. + + When the secret value is nonempty, it is displayed as `'**********'` instead of the underlying value in + calls to `repr()` and `str()`. If the value _is_ empty, it is displayed as `''`. + + ```py + from pydantic import BaseModel, SecretStr + + class User(BaseModel): + username: str + password: SecretStr + + user = User(username='scolvin', password='password1') + + print(user) + #> username='scolvin' password=SecretStr('**********') + print(user.password.get_secret_value()) + #> password1 + print((SecretStr('password'), SecretStr(''))) + #> (SecretStr('**********'), SecretStr('')) + ``` + """ + + _inner_schema: ClassVar[CoreSchema] = core_schema.str_schema() + _error_kind: ClassVar[str] = 'string_type' + + def __len__(self) -> int: + return len(self._secret_value) + + def _display(self) -> str: + return _secret_display(self._secret_value) + + +class SecretBytes(_SecretField[bytes]): + """A bytes used for storing sensitive information that you do not want to be visible in logging or tracebacks. + + It displays `b'**********'` instead of the string value on `repr()` and `str()` calls. + When the secret value is nonempty, it is displayed as `b'**********'` instead of the underlying value in + calls to `repr()` and `str()`. If the value _is_ empty, it is displayed as `b''`. + + ```py + from pydantic import BaseModel, SecretBytes + + class User(BaseModel): + username: str + password: SecretBytes + + user = User(username='scolvin', password=b'password1') + #> username='scolvin' password=SecretBytes(b'**********') + print(user.password.get_secret_value()) + #> b'password1' + print((SecretBytes(b'password'), SecretBytes(b''))) + #> (SecretBytes(b'**********'), SecretBytes(b'')) + ``` + """ + + _inner_schema: ClassVar[CoreSchema] = core_schema.bytes_schema() + _error_kind: ClassVar[str] = 'bytes_type' + + def __len__(self) -> int: + return len(self._secret_value) + + def _display(self) -> bytes: + return _secret_display(self._secret_value).encode() + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PAYMENT CARD TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class PaymentCardBrand(str, Enum): + amex = 'American Express' + mastercard = 'Mastercard' + visa = 'Visa' + other = 'other' + + def __str__(self) -> str: + return self.value + + +@deprecated( + 'The `PaymentCardNumber` class is deprecated, use `pydantic_extra_types` instead. ' + 'See https://docs.pydantic.dev/latest/api/pydantic_extra_types_payment/#pydantic_extra_types.payment.PaymentCardNumber.', + category=PydanticDeprecatedSince20, +) +class PaymentCardNumber(str): + """Based on: https://en.wikipedia.org/wiki/Payment_card_number.""" + + strip_whitespace: ClassVar[bool] = True + min_length: ClassVar[int] = 12 + max_length: ClassVar[int] = 19 + bin: str + last4: str + brand: PaymentCardBrand + + def __init__(self, card_number: str): + self.validate_digits(card_number) + + card_number = self.validate_luhn_check_digit(card_number) + + self.bin = card_number[:6] + self.last4 = card_number[-4:] + self.brand = self.validate_brand(card_number) + + @classmethod + def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + return core_schema.with_info_after_validator_function( + cls.validate, + core_schema.str_schema( + min_length=cls.min_length, max_length=cls.max_length, strip_whitespace=cls.strip_whitespace + ), + ) + + @classmethod + def validate(cls, input_value: str, /, _: core_schema.ValidationInfo) -> PaymentCardNumber: + """Validate the card number and return a `PaymentCardNumber` instance.""" + return cls(input_value) + + @property + def masked(self) -> str: + """Mask all but the last 4 digits of the card number. + + Returns: + A masked card number string. + """ + num_masked = len(self) - 10 # len(bin) + len(last4) == 10 + return f'{self.bin}{"*" * num_masked}{self.last4}' + + @classmethod + def validate_digits(cls, card_number: str) -> None: + """Validate that the card number is all digits.""" + if not card_number.isdigit(): + raise PydanticCustomError('payment_card_number_digits', 'Card number is not all digits') + + @classmethod + def validate_luhn_check_digit(cls, card_number: str) -> str: + """Based on: https://en.wikipedia.org/wiki/Luhn_algorithm.""" + sum_ = int(card_number[-1]) + length = len(card_number) + parity = length % 2 + for i in range(length - 1): + digit = int(card_number[i]) + if i % 2 == parity: + digit *= 2 + if digit > 9: + digit -= 9 + sum_ += digit + valid = sum_ % 10 == 0 + if not valid: + raise PydanticCustomError('payment_card_number_luhn', 'Card number is not luhn valid') + return card_number + + @staticmethod + def validate_brand(card_number: str) -> PaymentCardBrand: + """Validate length based on BIN for major brands: + https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN). + """ + if card_number[0] == '4': + brand = PaymentCardBrand.visa + elif 51 <= int(card_number[:2]) <= 55: + brand = PaymentCardBrand.mastercard + elif card_number[:2] in {'34', '37'}: + brand = PaymentCardBrand.amex + else: + brand = PaymentCardBrand.other + + required_length: None | int | str = None + if brand in PaymentCardBrand.mastercard: + required_length = 16 + valid = len(card_number) == required_length + elif brand == PaymentCardBrand.visa: + required_length = '13, 16 or 19' + valid = len(card_number) in {13, 16, 19} + elif brand == PaymentCardBrand.amex: + required_length = 15 + valid = len(card_number) == required_length + else: + valid = True + + if not valid: + raise PydanticCustomError( + 'payment_card_number_brand', + 'Length for a {brand} card must be {required_length}', + {'brand': brand, 'required_length': required_length}, + ) + return brand + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTE SIZE TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class ByteSize(int): + """Converts a string representing a number of bytes with units (such as `'1KB'` or `'11.5MiB'`) into an integer. + + You can use the `ByteSize` data type to (case-insensitively) convert a string representation of a number of bytes into + an integer, and also to print out human-readable strings representing a number of bytes. + + In conformance with [IEC 80000-13 Standard](https://en.wikipedia.org/wiki/ISO/IEC_80000) we interpret `'1KB'` to mean 1000 bytes, + and `'1KiB'` to mean 1024 bytes. In general, including a middle `'i'` will cause the unit to be interpreted as a power of 2, + rather than a power of 10 (so, for example, `'1 MB'` is treated as `1_000_000` bytes, whereas `'1 MiB'` is treated as `1_048_576` bytes). + + !!! info + Note that `1b` will be parsed as "1 byte" and not "1 bit". + + ```py + from pydantic import BaseModel, ByteSize + + class MyModel(BaseModel): + size: ByteSize + + print(MyModel(size=52000).size) + #> 52000 + print(MyModel(size='3000 KiB').size) + #> 3072000 + + m = MyModel(size='50 PB') + print(m.size.human_readable()) + #> 44.4PiB + print(m.size.human_readable(decimal=True)) + #> 50.0PB + print(m.size.human_readable(separator=' ')) + #> 44.4 PiB + + print(m.size.to('TiB')) + #> 45474.73508864641 + ``` + """ + + byte_sizes = { + 'b': 1, + 'kb': 10**3, + 'mb': 10**6, + 'gb': 10**9, + 'tb': 10**12, + 'pb': 10**15, + 'eb': 10**18, + 'kib': 2**10, + 'mib': 2**20, + 'gib': 2**30, + 'tib': 2**40, + 'pib': 2**50, + 'eib': 2**60, + 'bit': 1 / 8, + 'kbit': 10**3 / 8, + 'mbit': 10**6 / 8, + 'gbit': 10**9 / 8, + 'tbit': 10**12 / 8, + 'pbit': 10**15 / 8, + 'ebit': 10**18 / 8, + 'kibit': 2**10 / 8, + 'mibit': 2**20 / 8, + 'gibit': 2**30 / 8, + 'tibit': 2**40 / 8, + 'pibit': 2**50 / 8, + 'eibit': 2**60 / 8, + } + byte_sizes.update({k.lower()[0]: v for k, v in byte_sizes.items() if 'i' not in k}) + + byte_string_pattern = r'^\s*(\d*\.?\d+)\s*(\w+)?' + byte_string_re = re.compile(byte_string_pattern, re.IGNORECASE) + + @classmethod + def __get_pydantic_core_schema__(cls, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + return core_schema.with_info_after_validator_function( + function=cls._validate, + schema=core_schema.union_schema( + [ + core_schema.str_schema(pattern=cls.byte_string_pattern), + core_schema.int_schema(ge=0), + ], + custom_error_type='byte_size', + custom_error_message='could not parse value and unit from byte string', + ), + serialization=core_schema.plain_serializer_function_ser_schema( + int, return_schema=core_schema.int_schema(ge=0) + ), + ) + + @classmethod + def _validate(cls, input_value: Any, /, _: core_schema.ValidationInfo) -> ByteSize: + try: + return cls(int(input_value)) + except ValueError: + pass + + str_match = cls.byte_string_re.match(str(input_value)) + if str_match is None: + raise PydanticCustomError('byte_size', 'could not parse value and unit from byte string') + + scalar, unit = str_match.groups() + if unit is None: + unit = 'b' + + try: + unit_mult = cls.byte_sizes[unit.lower()] + except KeyError: + raise PydanticCustomError('byte_size_unit', 'could not interpret byte unit: {unit}', {'unit': unit}) + + return cls(int(float(scalar) * unit_mult)) + + def human_readable(self, decimal: bool = False, separator: str = '') -> str: + """Converts a byte size to a human readable string. + + Args: + decimal: If True, use decimal units (e.g. 1000 bytes per KB). If False, use binary units + (e.g. 1024 bytes per KiB). + separator: A string used to split the value and unit. Defaults to an empty string (''). + + Returns: + A human readable string representation of the byte size. + """ + if decimal: + divisor = 1000 + units = 'B', 'KB', 'MB', 'GB', 'TB', 'PB' + final_unit = 'EB' + else: + divisor = 1024 + units = 'B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB' + final_unit = 'EiB' + + num = float(self) + for unit in units: + if abs(num) < divisor: + if unit == 'B': + return f'{num:0.0f}{separator}{unit}' + else: + return f'{num:0.1f}{separator}{unit}' + num /= divisor + + return f'{num:0.1f}{separator}{final_unit}' + + def to(self, unit: str) -> float: + """Converts a byte size to another unit, including both byte and bit units. + + Args: + unit: The unit to convert to. Must be one of the following: B, KB, MB, GB, TB, PB, EB, + KiB, MiB, GiB, TiB, PiB, EiB (byte units) and + bit, kbit, mbit, gbit, tbit, pbit, ebit, + kibit, mibit, gibit, tibit, pibit, eibit (bit units). + + Returns: + The byte size in the new unit. + """ + try: + unit_div = self.byte_sizes[unit.lower()] + except KeyError: + raise PydanticCustomError('byte_size_unit', 'Could not interpret byte unit: {unit}', {'unit': unit}) + + return self / unit_div + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATE TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +def _check_annotated_type(annotated_type: str, expected_type: str, annotation: str) -> None: + if annotated_type != expected_type: + raise PydanticUserError(f"'{annotation}' cannot annotate '{annotated_type}'.", code='invalid_annotated_type') + + +if TYPE_CHECKING: + PastDate = Annotated[date, ...] + FutureDate = Annotated[date, ...] +else: + + class PastDate: + """A date in the past.""" + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + if cls is source: + # used directly as a type + return core_schema.date_schema(now_op='past') + else: + schema = handler(source) + _check_annotated_type(schema['type'], 'date', cls.__name__) + schema['now_op'] = 'past' + return schema + + def __repr__(self) -> str: + return 'PastDate' + + class FutureDate: + """A date in the future.""" + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + if cls is source: + # used directly as a type + return core_schema.date_schema(now_op='future') + else: + schema = handler(source) + _check_annotated_type(schema['type'], 'date', cls.__name__) + schema['now_op'] = 'future' + return schema + + def __repr__(self) -> str: + return 'FutureDate' + + +def condate( + *, + strict: bool | None = None, + gt: date | None = None, + ge: date | None = None, + lt: date | None = None, + le: date | None = None, +) -> type[date]: + """A wrapper for date that adds constraints. + + Args: + strict: Whether to validate the date value in strict mode. Defaults to `None`. + gt: The value must be greater than this. Defaults to `None`. + ge: The value must be greater than or equal to this. Defaults to `None`. + lt: The value must be less than this. Defaults to `None`. + le: The value must be less than or equal to this. Defaults to `None`. + + Returns: + A date type with the specified constraints. + """ + return Annotated[ # pyright: ignore[reportReturnType] + date, + Strict(strict) if strict is not None else None, + annotated_types.Interval(gt=gt, ge=ge, lt=lt, le=le), + ] + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATETIME TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +if TYPE_CHECKING: + AwareDatetime = Annotated[datetime, ...] + NaiveDatetime = Annotated[datetime, ...] + PastDatetime = Annotated[datetime, ...] + FutureDatetime = Annotated[datetime, ...] + +else: + + class AwareDatetime: + """A datetime that requires timezone info.""" + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + if cls is source: + # used directly as a type + return core_schema.datetime_schema(tz_constraint='aware') + else: + schema = handler(source) + _check_annotated_type(schema['type'], 'datetime', cls.__name__) + schema['tz_constraint'] = 'aware' + return schema + + def __repr__(self) -> str: + return 'AwareDatetime' + + class NaiveDatetime: + """A datetime that doesn't require timezone info.""" + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + if cls is source: + # used directly as a type + return core_schema.datetime_schema(tz_constraint='naive') + else: + schema = handler(source) + _check_annotated_type(schema['type'], 'datetime', cls.__name__) + schema['tz_constraint'] = 'naive' + return schema + + def __repr__(self) -> str: + return 'NaiveDatetime' + + class PastDatetime: + """A datetime that must be in the past.""" + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + if cls is source: + # used directly as a type + return core_schema.datetime_schema(now_op='past') + else: + schema = handler(source) + _check_annotated_type(schema['type'], 'datetime', cls.__name__) + schema['now_op'] = 'past' + return schema + + def __repr__(self) -> str: + return 'PastDatetime' + + class FutureDatetime: + """A datetime that must be in the future.""" + + @classmethod + def __get_pydantic_core_schema__( + cls, source: type[Any], handler: GetCoreSchemaHandler + ) -> core_schema.CoreSchema: + if cls is source: + # used directly as a type + return core_schema.datetime_schema(now_op='future') + else: + schema = handler(source) + _check_annotated_type(schema['type'], 'datetime', cls.__name__) + schema['now_op'] = 'future' + return schema + + def __repr__(self) -> str: + return 'FutureDatetime' + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Encoded TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class EncoderProtocol(Protocol): + """Protocol for encoding and decoding data to and from bytes.""" + + @classmethod + def decode(cls, data: bytes) -> bytes: + """Decode the data using the encoder. + + Args: + data: The data to decode. + + Returns: + The decoded data. + """ + ... + + @classmethod + def encode(cls, value: bytes) -> bytes: + """Encode the data using the encoder. + + Args: + value: The data to encode. + + Returns: + The encoded data. + """ + ... + + @classmethod + def get_json_format(cls) -> str: + """Get the JSON format for the encoded data. + + Returns: + The JSON format for the encoded data. + """ + ... + + +class Base64Encoder(EncoderProtocol): + """Standard (non-URL-safe) Base64 encoder.""" + + @classmethod + def decode(cls, data: bytes) -> bytes: + """Decode the data from base64 encoded bytes to original bytes data. + + Args: + data: The data to decode. + + Returns: + The decoded data. + """ + try: + return base64.decodebytes(data) + except ValueError as e: + raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)}) + + @classmethod + def encode(cls, value: bytes) -> bytes: + """Encode the data from bytes to a base64 encoded bytes. + + Args: + value: The data to encode. + + Returns: + The encoded data. + """ + return base64.encodebytes(value) + + @classmethod + def get_json_format(cls) -> Literal['base64']: + """Get the JSON format for the encoded data. + + Returns: + The JSON format for the encoded data. + """ + return 'base64' + + +class Base64UrlEncoder(EncoderProtocol): + """URL-safe Base64 encoder.""" + + @classmethod + def decode(cls, data: bytes) -> bytes: + """Decode the data from base64 encoded bytes to original bytes data. + + Args: + data: The data to decode. + + Returns: + The decoded data. + """ + try: + return base64.urlsafe_b64decode(data) + except ValueError as e: + raise PydanticCustomError('base64_decode', "Base64 decoding error: '{error}'", {'error': str(e)}) + + @classmethod + def encode(cls, value: bytes) -> bytes: + """Encode the data from bytes to a base64 encoded bytes. + + Args: + value: The data to encode. + + Returns: + The encoded data. + """ + return base64.urlsafe_b64encode(value) + + @classmethod + def get_json_format(cls) -> Literal['base64url']: + """Get the JSON format for the encoded data. + + Returns: + The JSON format for the encoded data. + """ + return 'base64url' + + +@_dataclasses.dataclass(**_internal_dataclass.slots_true) +class EncodedBytes: + """A bytes type that is encoded and decoded using the specified encoder. + + `EncodedBytes` needs an encoder that implements `EncoderProtocol` to operate. + + ```py + from typing_extensions import Annotated + + from pydantic import BaseModel, EncodedBytes, EncoderProtocol, ValidationError + + class MyEncoder(EncoderProtocol): + @classmethod + def decode(cls, data: bytes) -> bytes: + if data == b'**undecodable**': + raise ValueError('Cannot decode data') + return data[13:] + + @classmethod + def encode(cls, value: bytes) -> bytes: + return b'**encoded**: ' + value + + @classmethod + def get_json_format(cls) -> str: + return 'my-encoder' + + MyEncodedBytes = Annotated[bytes, EncodedBytes(encoder=MyEncoder)] + + class Model(BaseModel): + my_encoded_bytes: MyEncodedBytes + + # Initialize the model with encoded data + m = Model(my_encoded_bytes=b'**encoded**: some bytes') + + # Access decoded value + print(m.my_encoded_bytes) + #> b'some bytes' + + # Serialize into the encoded form + print(m.model_dump()) + #> {'my_encoded_bytes': b'**encoded**: some bytes'} + + # Validate encoded data + try: + Model(my_encoded_bytes=b'**undecodable**') + except ValidationError as e: + print(e) + ''' + 1 validation error for Model + my_encoded_bytes + Value error, Cannot decode data [type=value_error, input_value=b'**undecodable**', input_type=bytes] + ''' + ``` + """ + + encoder: type[EncoderProtocol] + + def __get_pydantic_json_schema__( + self, core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler + ) -> JsonSchemaValue: + field_schema = handler(core_schema) + field_schema.update(type='string', format=self.encoder.get_json_format()) + return field_schema + + def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + return core_schema.with_info_after_validator_function( + function=self.decode, + schema=core_schema.bytes_schema(), + serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode), + ) + + def decode(self, data: bytes, _: core_schema.ValidationInfo) -> bytes: + """Decode the data using the specified encoder. + + Args: + data: The data to decode. + + Returns: + The decoded data. + """ + return self.encoder.decode(data) + + def encode(self, value: bytes) -> bytes: + """Encode the data using the specified encoder. + + Args: + value: The data to encode. + + Returns: + The encoded data. + """ + return self.encoder.encode(value) + + def __hash__(self) -> int: + return hash(self.encoder) + + +@_dataclasses.dataclass(**_internal_dataclass.slots_true) +class EncodedStr(EncodedBytes): + """A str type that is encoded and decoded using the specified encoder. + + `EncodedStr` needs an encoder that implements `EncoderProtocol` to operate. + + ```py + from typing_extensions import Annotated + + from pydantic import BaseModel, EncodedStr, EncoderProtocol, ValidationError + + class MyEncoder(EncoderProtocol): + @classmethod + def decode(cls, data: bytes) -> bytes: + if data == b'**undecodable**': + raise ValueError('Cannot decode data') + return data[13:] + + @classmethod + def encode(cls, value: bytes) -> bytes: + return b'**encoded**: ' + value + + @classmethod + def get_json_format(cls) -> str: + return 'my-encoder' + + MyEncodedStr = Annotated[str, EncodedStr(encoder=MyEncoder)] + + class Model(BaseModel): + my_encoded_str: MyEncodedStr + + # Initialize the model with encoded data + m = Model(my_encoded_str='**encoded**: some str') + + # Access decoded value + print(m.my_encoded_str) + #> some str + + # Serialize into the encoded form + print(m.model_dump()) + #> {'my_encoded_str': '**encoded**: some str'} + + # Validate encoded data + try: + Model(my_encoded_str='**undecodable**') + except ValidationError as e: + print(e) + ''' + 1 validation error for Model + my_encoded_str + Value error, Cannot decode data [type=value_error, input_value='**undecodable**', input_type=str] + ''' + ``` + """ + + def __get_pydantic_core_schema__(self, source: type[Any], handler: GetCoreSchemaHandler) -> core_schema.CoreSchema: + return core_schema.with_info_after_validator_function( + function=self.decode_str, + schema=super(EncodedStr, self).__get_pydantic_core_schema__(source=source, handler=handler), # noqa: UP008 + serialization=core_schema.plain_serializer_function_ser_schema(function=self.encode_str), + ) + + def decode_str(self, data: bytes, _: core_schema.ValidationInfo) -> str: + """Decode the data using the specified encoder. + + Args: + data: The data to decode. + + Returns: + The decoded data. + """ + return data.decode() + + def encode_str(self, value: str) -> str: + """Encode the data using the specified encoder. + + Args: + value: The data to encode. + + Returns: + The encoded data. + """ + return super(EncodedStr, self).encode(value=value.encode()).decode() # noqa: UP008 + + def __hash__(self) -> int: + return hash(self.encoder) + + +Base64Bytes = Annotated[bytes, EncodedBytes(encoder=Base64Encoder)] +"""A bytes type that is encoded and decoded using the standard (non-URL-safe) base64 encoder. + +Note: + Under the hood, `Base64Bytes` use standard library `base64.encodebytes` and `base64.decodebytes` functions. + + As a result, attempting to decode url-safe base64 data using the `Base64Bytes` type may fail or produce an incorrect + decoding. + +```py +from pydantic import Base64Bytes, BaseModel, ValidationError + +class Model(BaseModel): + base64_bytes: Base64Bytes + +# Initialize the model with base64 data +m = Model(base64_bytes=b'VGhpcyBpcyB0aGUgd2F5') + +# Access decoded value +print(m.base64_bytes) +#> b'This is the way' + +# Serialize into the base64 form +print(m.model_dump()) +#> {'base64_bytes': b'VGhpcyBpcyB0aGUgd2F5\n'} + +# Validate base64 data +try: + print(Model(base64_bytes=b'undecodable').base64_bytes) +except ValidationError as e: + print(e) + ''' + 1 validation error for Model + base64_bytes + Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value=b'undecodable', input_type=bytes] + ''' +``` +""" +Base64Str = Annotated[str, EncodedStr(encoder=Base64Encoder)] +"""A str type that is encoded and decoded using the standard (non-URL-safe) base64 encoder. + +Note: + Under the hood, `Base64Bytes` use standard library `base64.encodebytes` and `base64.decodebytes` functions. + + As a result, attempting to decode url-safe base64 data using the `Base64Str` type may fail or produce an incorrect + decoding. + +```py +from pydantic import Base64Str, BaseModel, ValidationError + +class Model(BaseModel): + base64_str: Base64Str + +# Initialize the model with base64 data +m = Model(base64_str='VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y') + +# Access decoded value +print(m.base64_str) +#> These aren't the droids you're looking for + +# Serialize into the base64 form +print(m.model_dump()) +#> {'base64_str': 'VGhlc2UgYXJlbid0IHRoZSBkcm9pZHMgeW91J3JlIGxvb2tpbmcgZm9y\n'} + +# Validate base64 data +try: + print(Model(base64_str='undecodable').base64_str) +except ValidationError as e: + print(e) + ''' + 1 validation error for Model + base64_str + Base64 decoding error: 'Incorrect padding' [type=base64_decode, input_value='undecodable', input_type=str] + ''' +``` +""" +Base64UrlBytes = Annotated[bytes, EncodedBytes(encoder=Base64UrlEncoder)] +"""A bytes type that is encoded and decoded using the URL-safe base64 encoder. + +Note: + Under the hood, `Base64UrlBytes` use standard library `base64.urlsafe_b64encode` and `base64.urlsafe_b64decode` + functions. + + As a result, the `Base64UrlBytes` type can be used to faithfully decode "vanilla" base64 data + (using `'+'` and `'/'`). + +```py +from pydantic import Base64UrlBytes, BaseModel + +class Model(BaseModel): + base64url_bytes: Base64UrlBytes + +# Initialize the model with base64 data +m = Model(base64url_bytes=b'SHc_dHc-TXc==') +print(m) +#> base64url_bytes=b'Hw?tw>Mw' +``` +""" +Base64UrlStr = Annotated[str, EncodedStr(encoder=Base64UrlEncoder)] +"""A str type that is encoded and decoded using the URL-safe base64 encoder. + +Note: + Under the hood, `Base64UrlStr` use standard library `base64.urlsafe_b64encode` and `base64.urlsafe_b64decode` + functions. + + As a result, the `Base64UrlStr` type can be used to faithfully decode "vanilla" base64 data (using `'+'` and `'/'`). + +```py +from pydantic import Base64UrlStr, BaseModel + +class Model(BaseModel): + base64url_str: Base64UrlStr + +# Initialize the model with base64 data +m = Model(base64url_str='SHc_dHc-TXc==') +print(m) +#> base64url_str='Hw?tw>Mw' +``` +""" + + +__getattr__ = getattr_migration(__name__) + + +@_dataclasses.dataclass(**_internal_dataclass.slots_true) +class GetPydanticSchema: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/types/#using-getpydanticschema-to-reduce-boilerplate + + A convenience class for creating an annotation that provides pydantic custom type hooks. + + This class is intended to eliminate the need to create a custom "marker" which defines the + `__get_pydantic_core_schema__` and `__get_pydantic_json_schema__` custom hook methods. + + For example, to have a field treated by type checkers as `int`, but by pydantic as `Any`, you can do: + ```python + from typing import Any + + from typing_extensions import Annotated + + from pydantic import BaseModel, GetPydanticSchema + + HandleAsAny = GetPydanticSchema(lambda _s, h: h(Any)) + + class Model(BaseModel): + x: Annotated[int, HandleAsAny] # pydantic sees `x: Any` + + print(repr(Model(x='abc').x)) + #> 'abc' + ``` + """ + + get_pydantic_core_schema: Callable[[Any, GetCoreSchemaHandler], CoreSchema] | None = None + get_pydantic_json_schema: Callable[[Any, GetJsonSchemaHandler], JsonSchemaValue] | None = None + + # Note: we may want to consider adding a convenience staticmethod `def for_type(type_: Any) -> GetPydanticSchema:` + # which returns `GetPydanticSchema(lambda _s, h: h(type_))` + + if not TYPE_CHECKING: + # We put `__getattr__` in a non-TYPE_CHECKING block because otherwise, mypy allows arbitrary attribute access + + def __getattr__(self, item: str) -> Any: + """Use this rather than defining `__get_pydantic_core_schema__` etc. to reduce the number of nested calls.""" + if item == '__get_pydantic_core_schema__' and self.get_pydantic_core_schema: + return self.get_pydantic_core_schema + elif item == '__get_pydantic_json_schema__' and self.get_pydantic_json_schema: + return self.get_pydantic_json_schema + else: + return object.__getattribute__(self, item) + + __hash__ = object.__hash__ + + +@_dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True) +class Tag: + """Provides a way to specify the expected tag to use for a case of a (callable) discriminated union. + + Also provides a way to label a union case in error messages. + + When using a callable `Discriminator`, attach a `Tag` to each case in the `Union` to specify the tag that + should be used to identify that case. For example, in the below example, the `Tag` is used to specify that + if `get_discriminator_value` returns `'apple'`, the input should be validated as an `ApplePie`, and if it + returns `'pumpkin'`, the input should be validated as a `PumpkinPie`. + + The primary role of the `Tag` here is to map the return value from the callable `Discriminator` function to + the appropriate member of the `Union` in question. + + ```py + from typing import Any, Union + + from typing_extensions import Annotated, Literal + + from pydantic import BaseModel, Discriminator, Tag + + class Pie(BaseModel): + time_to_cook: int + num_ingredients: int + + class ApplePie(Pie): + fruit: Literal['apple'] = 'apple' + + class PumpkinPie(Pie): + filling: Literal['pumpkin'] = 'pumpkin' + + def get_discriminator_value(v: Any) -> str: + if isinstance(v, dict): + return v.get('fruit', v.get('filling')) + return getattr(v, 'fruit', getattr(v, 'filling', None)) + + class ThanksgivingDinner(BaseModel): + dessert: Annotated[ + Union[ + Annotated[ApplePie, Tag('apple')], + Annotated[PumpkinPie, Tag('pumpkin')], + ], + Discriminator(get_discriminator_value), + ] + + apple_variation = ThanksgivingDinner.model_validate( + {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}} + ) + print(repr(apple_variation)) + ''' + ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple')) + ''' + + pumpkin_variation = ThanksgivingDinner.model_validate( + { + 'dessert': { + 'filling': 'pumpkin', + 'time_to_cook': 40, + 'num_ingredients': 6, + } + } + ) + print(repr(pumpkin_variation)) + ''' + ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin')) + ''' + ``` + + !!! note + You must specify a `Tag` for every case in a `Tag` that is associated with a + callable `Discriminator`. Failing to do so will result in a `PydanticUserError` with code + [`callable-discriminator-no-tag`](../errors/usage_errors.md#callable-discriminator-no-tag). + + See the [Discriminated Unions] concepts docs for more details on how to use `Tag`s. + + [Discriminated Unions]: ../concepts/unions.md#discriminated-unions + """ + + tag: str + + def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: + schema = handler(source_type) + metadata = schema.setdefault('metadata', {}) + assert isinstance(metadata, dict) + metadata[_core_utils.TAGGED_UNION_TAG_KEY] = self.tag + return schema + + +@_dataclasses.dataclass(**_internal_dataclass.slots_true, frozen=True) +class Discriminator: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/unions/#discriminated-unions-with-callable-discriminator + + Provides a way to use a custom callable as the way to extract the value of a union discriminator. + + This allows you to get validation behavior like you'd get from `Field(discriminator=)`, + but without needing to have a single shared field across all the union choices. This also makes it + possible to handle unions of models and primitive types with discriminated-union-style validation errors. + Finally, this allows you to use a custom callable as the way to identify which member of a union a value + belongs to, while still seeing all the performance benefits of a discriminated union. + + Consider this example, which is much more performant with the use of `Discriminator` and thus a `TaggedUnion` + than it would be as a normal `Union`. + + ```py + from typing import Any, Union + + from typing_extensions import Annotated, Literal + + from pydantic import BaseModel, Discriminator, Tag + + class Pie(BaseModel): + time_to_cook: int + num_ingredients: int + + class ApplePie(Pie): + fruit: Literal['apple'] = 'apple' + + class PumpkinPie(Pie): + filling: Literal['pumpkin'] = 'pumpkin' + + def get_discriminator_value(v: Any) -> str: + if isinstance(v, dict): + return v.get('fruit', v.get('filling')) + return getattr(v, 'fruit', getattr(v, 'filling', None)) + + class ThanksgivingDinner(BaseModel): + dessert: Annotated[ + Union[ + Annotated[ApplePie, Tag('apple')], + Annotated[PumpkinPie, Tag('pumpkin')], + ], + Discriminator(get_discriminator_value), + ] + + apple_variation = ThanksgivingDinner.model_validate( + {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}} + ) + print(repr(apple_variation)) + ''' + ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple')) + ''' + + pumpkin_variation = ThanksgivingDinner.model_validate( + { + 'dessert': { + 'filling': 'pumpkin', + 'time_to_cook': 40, + 'num_ingredients': 6, + } + } + ) + print(repr(pumpkin_variation)) + ''' + ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin')) + ''' + ``` + + See the [Discriminated Unions] concepts docs for more details on how to use `Discriminator`s. + + [Discriminated Unions]: ../concepts/unions.md#discriminated-unions + """ + + discriminator: str | Callable[[Any], Hashable] + """The callable or field name for discriminating the type in a tagged union. + + A `Callable` discriminator must extract the value of the discriminator from the input. + A `str` discriminator must be the name of a field to discriminate against. + """ + custom_error_type: str | None = None + """Type to use in [custom errors](../errors/errors.md#custom-errors) replacing the standard discriminated union + validation errors. + """ + custom_error_message: str | None = None + """Message to use in custom errors.""" + custom_error_context: dict[str, int | str | float] | None = None + """Context to use in custom errors.""" + + def __get_pydantic_core_schema__(self, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: + origin = _typing_extra.get_origin(source_type) + if not origin or not _typing_extra.origin_is_union(origin): + raise TypeError(f'{type(self).__name__} must be used with a Union type, not {source_type}') + + if isinstance(self.discriminator, str): + from pydantic import Field + + return handler(Annotated[source_type, Field(discriminator=self.discriminator)]) + else: + original_schema = handler(source_type) + return self._convert_schema(original_schema) + + def _convert_schema(self, original_schema: core_schema.CoreSchema) -> core_schema.TaggedUnionSchema: + if original_schema['type'] != 'union': + # This likely indicates that the schema was a single-item union that was simplified. + # In this case, we do the same thing we do in + # `pydantic._internal._discriminated_union._ApplyInferredDiscriminator._apply_to_root`, namely, + # package the generated schema back into a single-item union. + original_schema = core_schema.union_schema([original_schema]) + + tagged_union_choices = {} + for i, choice in enumerate(original_schema['choices']): + tag = None + if isinstance(choice, tuple): + choice, tag = choice + metadata = choice.get('metadata') + if metadata is not None: + metadata_tag = metadata.get(_core_utils.TAGGED_UNION_TAG_KEY) + if metadata_tag is not None: + tag = metadata_tag + if tag is None: + raise PydanticUserError( + f'`Tag` not provided for choice {choice} used with `Discriminator`', + code='callable-discriminator-no-tag', + ) + tagged_union_choices[tag] = choice + + # Have to do these verbose checks to ensure falsy values ('' and {}) don't get ignored + custom_error_type = self.custom_error_type + if custom_error_type is None: + custom_error_type = original_schema.get('custom_error_type') + + custom_error_message = self.custom_error_message + if custom_error_message is None: + custom_error_message = original_schema.get('custom_error_message') + + custom_error_context = self.custom_error_context + if custom_error_context is None: + custom_error_context = original_schema.get('custom_error_context') + + custom_error_type = original_schema.get('custom_error_type') if custom_error_type is None else custom_error_type + return core_schema.tagged_union_schema( + tagged_union_choices, + self.discriminator, + custom_error_type=custom_error_type, + custom_error_message=custom_error_message, + custom_error_context=custom_error_context, + strict=original_schema.get('strict'), + ref=original_schema.get('ref'), + metadata=original_schema.get('metadata'), + serialization=original_schema.get('serialization'), + ) + + +_JSON_TYPES = {int, float, str, bool, list, dict, type(None)} + + +def _get_type_name(x: Any) -> str: + type_ = type(x) + if type_ in _JSON_TYPES: + return type_.__name__ + + # Handle proper subclasses; note we don't need to handle None or bool here + if isinstance(x, int): + return 'int' + if isinstance(x, float): + return 'float' + if isinstance(x, str): + return 'str' + if isinstance(x, list): + return 'list' + if isinstance(x, dict): + return 'dict' + + # Fail by returning the type's actual name + return getattr(type_, '__name__', '') + + +class _AllowAnyJson: + @classmethod + def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: + python_schema = handler(source_type) + return core_schema.json_or_python_schema(json_schema=core_schema.any_schema(), python_schema=python_schema) + + +if TYPE_CHECKING: + # This seems to only be necessary for mypy + JsonValue: TypeAlias = Union[ + List['JsonValue'], + Dict[str, 'JsonValue'], + str, + bool, + int, + float, + None, + ] + """A `JsonValue` is used to represent a value that can be serialized to JSON. + + It may be one of: + + * `List['JsonValue']` + * `Dict[str, 'JsonValue']` + * `str` + * `bool` + * `int` + * `float` + * `None` + + The following example demonstrates how to use `JsonValue` to validate JSON data, + and what kind of errors to expect when input data is not json serializable. + + ```py + import json + + from pydantic import BaseModel, JsonValue, ValidationError + + class Model(BaseModel): + j: JsonValue + + valid_json_data = {'j': {'a': {'b': {'c': 1, 'd': [2, None]}}}} + invalid_json_data = {'j': {'a': {'b': ...}}} + + print(repr(Model.model_validate(valid_json_data))) + #> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}}) + print(repr(Model.model_validate_json(json.dumps(valid_json_data)))) + #> Model(j={'a': {'b': {'c': 1, 'd': [2, None]}}}) + + try: + Model.model_validate(invalid_json_data) + except ValidationError as e: + print(e) + ''' + 1 validation error for Model + j.dict.a.dict.b + input was not a valid JSON value [type=invalid-json-value, input_value=Ellipsis, input_type=ellipsis] + ''' + ``` + """ + +else: + JsonValue = TypeAliasType( + 'JsonValue', + Annotated[ + Union[ + Annotated[List['JsonValue'], Tag('list')], + Annotated[Dict[str, 'JsonValue'], Tag('dict')], + Annotated[str, Tag('str')], + Annotated[bool, Tag('bool')], + Annotated[int, Tag('int')], + Annotated[float, Tag('float')], + Annotated[None, Tag('NoneType')], + ], + Discriminator( + _get_type_name, + custom_error_type='invalid-json-value', + custom_error_message='input was not a valid JSON value', + ), + _AllowAnyJson, + ], + ) + + +class _OnErrorOmit: + @classmethod + def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema: + # there is no actual default value here but we use with_default_schema since it already has the on_error + # behavior implemented and it would be no more efficient to implement it on every other validator + # or as a standalone validator + return core_schema.with_default_schema(schema=handler(source_type), on_error='omit') + + +OnErrorOmit = Annotated[T, _OnErrorOmit] +""" +When used as an item in a list, the key type in a dict, optional values of a TypedDict, etc. +this annotation omits the item from the iteration if there is any error validating it. +That is, instead of a [`ValidationError`][pydantic_core.ValidationError] being propagated up and the entire iterable being discarded +any invalid items are discarded and the valid ones are returned. +""" + + +@_dataclasses.dataclass +class FailFast(_fields.PydanticMetadata, BaseMetadata): + """A `FailFast` annotation can be used to specify that validation should stop at the first error. + + This can be useful when you want to validate a large amount of data and you only need to know if it's valid or not. + + You might want to enable this setting if you want to validate your data faster (basically, if you use this, + validation will be more performant with the caveat that you get less information). + + ```py + from typing import List + from typing_extensions import Annotated + from pydantic import BaseModel, FailFast, ValidationError + + class Model(BaseModel): + x: Annotated[List[int], FailFast()] + + # This will raise a single error for the first invalid value and stop validation + try: + obj = Model(x=[1, 2, 'a', 4, 5, 'b', 7, 8, 9, 'c']) + except ValidationError as e: + print(e) + ''' + 1 validation error for Model + x.2 + Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str] + ''' + ``` + """ + + fail_fast: bool = True diff --git a/env/Lib/site-packages/pydantic/typing.py b/env/Lib/site-packages/pydantic/typing.py new file mode 100644 index 0000000..0bda22d --- /dev/null +++ b/env/Lib/site-packages/pydantic/typing.py @@ -0,0 +1,5 @@ +"""`typing` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/utils.py b/env/Lib/site-packages/pydantic/utils.py new file mode 100644 index 0000000..8d1e2a8 --- /dev/null +++ b/env/Lib/site-packages/pydantic/utils.py @@ -0,0 +1,5 @@ +"""The `utils` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/v1/__init__.py b/env/Lib/site-packages/pydantic/v1/__init__.py new file mode 100644 index 0000000..6ad3f46 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/__init__.py @@ -0,0 +1,131 @@ +# flake8: noqa +from pydantic.v1 import dataclasses +from pydantic.v1.annotated_types import create_model_from_namedtuple, create_model_from_typeddict +from pydantic.v1.class_validators import root_validator, validator +from pydantic.v1.config import BaseConfig, ConfigDict, Extra +from pydantic.v1.decorator import validate_arguments +from pydantic.v1.env_settings import BaseSettings +from pydantic.v1.error_wrappers import ValidationError +from pydantic.v1.errors import * +from pydantic.v1.fields import Field, PrivateAttr, Required +from pydantic.v1.main import * +from pydantic.v1.networks import * +from pydantic.v1.parse import Protocol +from pydantic.v1.tools import * +from pydantic.v1.types import * +from pydantic.v1.version import VERSION, compiled + +__version__ = VERSION + +# WARNING __all__ from pydantic.errors is not included here, it will be removed as an export here in v2 +# please use "from pydantic.v1.errors import ..." instead +__all__ = [ + # annotated types utils + 'create_model_from_namedtuple', + 'create_model_from_typeddict', + # dataclasses + 'dataclasses', + # class_validators + 'root_validator', + 'validator', + # config + 'BaseConfig', + 'ConfigDict', + 'Extra', + # decorator + 'validate_arguments', + # env_settings + 'BaseSettings', + # error_wrappers + 'ValidationError', + # fields + 'Field', + 'Required', + # main + 'BaseModel', + 'create_model', + 'validate_model', + # network + 'AnyUrl', + 'AnyHttpUrl', + 'FileUrl', + 'HttpUrl', + 'stricturl', + 'EmailStr', + 'NameEmail', + 'IPvAnyAddress', + 'IPvAnyInterface', + 'IPvAnyNetwork', + 'PostgresDsn', + 'CockroachDsn', + 'AmqpDsn', + 'RedisDsn', + 'MongoDsn', + 'KafkaDsn', + 'validate_email', + # parse + 'Protocol', + # tools + 'parse_file_as', + 'parse_obj_as', + 'parse_raw_as', + 'schema_of', + 'schema_json_of', + # types + 'NoneStr', + 'NoneBytes', + 'StrBytes', + 'NoneStrBytes', + 'StrictStr', + 'ConstrainedBytes', + 'conbytes', + 'ConstrainedList', + 'conlist', + 'ConstrainedSet', + 'conset', + 'ConstrainedFrozenSet', + 'confrozenset', + 'ConstrainedStr', + 'constr', + 'PyObject', + 'ConstrainedInt', + 'conint', + 'PositiveInt', + 'NegativeInt', + 'NonNegativeInt', + 'NonPositiveInt', + 'ConstrainedFloat', + 'confloat', + 'PositiveFloat', + 'NegativeFloat', + 'NonNegativeFloat', + 'NonPositiveFloat', + 'FiniteFloat', + 'ConstrainedDecimal', + 'condecimal', + 'ConstrainedDate', + 'condate', + 'UUID1', + 'UUID3', + 'UUID4', + 'UUID5', + 'FilePath', + 'DirectoryPath', + 'Json', + 'JsonWrapper', + 'SecretField', + 'SecretStr', + 'SecretBytes', + 'StrictBool', + 'StrictBytes', + 'StrictInt', + 'StrictFloat', + 'PaymentCardNumber', + 'PrivateAttr', + 'ByteSize', + 'PastDate', + 'FutureDate', + # version + 'compiled', + 'VERSION', +] diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..7856ad5 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/_hypothesis_plugin.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/_hypothesis_plugin.cpython-311.pyc new file mode 100644 index 0000000..68d1914 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/_hypothesis_plugin.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-311.pyc new file mode 100644 index 0000000..a7fe218 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/annotated_types.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/class_validators.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/class_validators.cpython-311.pyc new file mode 100644 index 0000000..b69820a Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/class_validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/color.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/color.cpython-311.pyc new file mode 100644 index 0000000..4c48d40 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/color.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/config.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000..869dcaa Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/config.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-311.pyc new file mode 100644 index 0000000..f1eabc2 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/dataclasses.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-311.pyc new file mode 100644 index 0000000..98c7ea6 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/datetime_parse.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/decorator.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/decorator.cpython-311.pyc new file mode 100644 index 0000000..46678a1 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/decorator.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/env_settings.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/env_settings.cpython-311.pyc new file mode 100644 index 0000000..2afb759 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/env_settings.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/error_wrappers.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/error_wrappers.cpython-311.pyc new file mode 100644 index 0000000..50f01b6 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/error_wrappers.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/errors.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/errors.cpython-311.pyc new file mode 100644 index 0000000..1e102d7 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/errors.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/fields.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/fields.cpython-311.pyc new file mode 100644 index 0000000..74a8687 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/fields.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/generics.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/generics.cpython-311.pyc new file mode 100644 index 0000000..06a2800 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/generics.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/json.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/json.cpython-311.pyc new file mode 100644 index 0000000..be58105 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/json.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/main.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/main.cpython-311.pyc new file mode 100644 index 0000000..e2454e0 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/main.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/mypy.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/mypy.cpython-311.pyc new file mode 100644 index 0000000..fa3ca63 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/mypy.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/networks.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/networks.cpython-311.pyc new file mode 100644 index 0000000..3a424fe Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/networks.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/parse.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/parse.cpython-311.pyc new file mode 100644 index 0000000..a4a9ed5 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/parse.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/schema.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/schema.cpython-311.pyc new file mode 100644 index 0000000..dbfabff Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/schema.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/tools.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/tools.cpython-311.pyc new file mode 100644 index 0000000..204a914 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/tools.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/types.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/types.cpython-311.pyc new file mode 100644 index 0000000..becdb1c Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/types.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/typing.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/typing.cpython-311.pyc new file mode 100644 index 0000000..5449f69 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/typing.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/utils.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/utils.cpython-311.pyc new file mode 100644 index 0000000..fa01e0a Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/utils.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/validators.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/validators.cpython-311.pyc new file mode 100644 index 0000000..28f6bd6 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/validators.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/__pycache__/version.cpython-311.pyc b/env/Lib/site-packages/pydantic/v1/__pycache__/version.cpython-311.pyc new file mode 100644 index 0000000..4ec3a20 Binary files /dev/null and b/env/Lib/site-packages/pydantic/v1/__pycache__/version.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic/v1/_hypothesis_plugin.py b/env/Lib/site-packages/pydantic/v1/_hypothesis_plugin.py new file mode 100644 index 0000000..b62234d --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/_hypothesis_plugin.py @@ -0,0 +1,391 @@ +""" +Register Hypothesis strategies for Pydantic custom types. + +This enables fully-automatic generation of test data for most Pydantic classes. + +Note that this module has *no* runtime impact on Pydantic itself; instead it +is registered as a setuptools entry point and Hypothesis will import it if +Pydantic is installed. See also: + +https://hypothesis.readthedocs.io/en/latest/strategies.html#registering-strategies-via-setuptools-entry-points +https://hypothesis.readthedocs.io/en/latest/data.html#hypothesis.strategies.register_type_strategy +https://hypothesis.readthedocs.io/en/latest/strategies.html#interaction-with-pytest-cov +https://docs.pydantic.dev/usage/types/#pydantic-types + +Note that because our motivation is to *improve user experience*, the strategies +are always sound (never generate invalid data) but sacrifice completeness for +maintainability (ie may be unable to generate some tricky but valid data). + +Finally, this module makes liberal use of `# type: ignore[]` pragmas. +This is because Hypothesis annotates `register_type_strategy()` with +`(T, SearchStrategy[T])`, but in most cases we register e.g. `ConstrainedInt` +to generate instances of the builtin `int` type which match the constraints. +""" + +import contextlib +import datetime +import ipaddress +import json +import math +from fractions import Fraction +from typing import Callable, Dict, Type, Union, cast, overload + +import hypothesis.strategies as st + +import pydantic +import pydantic.color +import pydantic.types +from pydantic.v1.utils import lenient_issubclass + +# FilePath and DirectoryPath are explicitly unsupported, as we'd have to create +# them on-disk, and that's unsafe in general without being told *where* to do so. +# +# URLs are unsupported because it's easy for users to define their own strategy for +# "normal" URLs, and hard for us to define a general strategy which includes "weird" +# URLs but doesn't also have unpredictable performance problems. +# +# conlist() and conset() are unsupported for now, because the workarounds for +# Cython and Hypothesis to handle parametrized generic types are incompatible. +# We are rethinking Hypothesis compatibility in Pydantic v2. + +# Emails +try: + import email_validator +except ImportError: # pragma: no cover + pass +else: + + def is_valid_email(s: str) -> bool: + # Hypothesis' st.emails() occasionally generates emails like 0@A0--0.ac + # that are invalid according to email-validator, so we filter those out. + try: + email_validator.validate_email(s, check_deliverability=False) + return True + except email_validator.EmailNotValidError: # pragma: no cover + return False + + # Note that these strategies deliberately stay away from any tricky Unicode + # or other encoding issues; we're just trying to generate *something* valid. + st.register_type_strategy(pydantic.EmailStr, st.emails().filter(is_valid_email)) # type: ignore[arg-type] + st.register_type_strategy( + pydantic.NameEmail, + st.builds( + '{} <{}>'.format, # type: ignore[arg-type] + st.from_regex('[A-Za-z0-9_]+( [A-Za-z0-9_]+){0,5}', fullmatch=True), + st.emails().filter(is_valid_email), + ), + ) + +# PyObject - dotted names, in this case taken from the math module. +st.register_type_strategy( + pydantic.PyObject, # type: ignore[arg-type] + st.sampled_from( + [cast(pydantic.PyObject, f'math.{name}') for name in sorted(vars(math)) if not name.startswith('_')] + ), +) + +# CSS3 Colors; as name, hex, rgb(a) tuples or strings, or hsl strings +_color_regexes = ( + '|'.join( + ( + pydantic.color.r_hex_short, + pydantic.color.r_hex_long, + pydantic.color.r_rgb, + pydantic.color.r_rgba, + pydantic.color.r_hsl, + pydantic.color.r_hsla, + ) + ) + # Use more precise regex patterns to avoid value-out-of-range errors + .replace(pydantic.color._r_sl, r'(?:(\d\d?(?:\.\d+)?|100(?:\.0+)?)%)') + .replace(pydantic.color._r_alpha, r'(?:(0(?:\.\d+)?|1(?:\.0+)?|\.\d+|\d{1,2}%))') + .replace(pydantic.color._r_255, r'(?:((?:\d|\d\d|[01]\d\d|2[0-4]\d|25[0-4])(?:\.\d+)?|255(?:\.0+)?))') +) +st.register_type_strategy( + pydantic.color.Color, + st.one_of( + st.sampled_from(sorted(pydantic.color.COLORS_BY_NAME)), + st.tuples( + st.integers(0, 255), + st.integers(0, 255), + st.integers(0, 255), + st.none() | st.floats(0, 1) | st.floats(0, 100).map('{}%'.format), + ), + st.from_regex(_color_regexes, fullmatch=True), + ), +) + + +# Card numbers, valid according to the Luhn algorithm + + +def add_luhn_digit(card_number: str) -> str: + # See https://en.wikipedia.org/wiki/Luhn_algorithm + for digit in '0123456789': + with contextlib.suppress(Exception): + pydantic.PaymentCardNumber.validate_luhn_check_digit(card_number + digit) + return card_number + digit + raise AssertionError('Unreachable') # pragma: no cover + + +card_patterns = ( + # Note that these patterns omit the Luhn check digit; that's added by the function above + '4[0-9]{14}', # Visa + '5[12345][0-9]{13}', # Mastercard + '3[47][0-9]{12}', # American Express + '[0-26-9][0-9]{10,17}', # other (incomplete to avoid overlap) +) +st.register_type_strategy( + pydantic.PaymentCardNumber, + st.from_regex('|'.join(card_patterns), fullmatch=True).map(add_luhn_digit), # type: ignore[arg-type] +) + +# UUIDs +st.register_type_strategy(pydantic.UUID1, st.uuids(version=1)) +st.register_type_strategy(pydantic.UUID3, st.uuids(version=3)) +st.register_type_strategy(pydantic.UUID4, st.uuids(version=4)) +st.register_type_strategy(pydantic.UUID5, st.uuids(version=5)) + +# Secrets +st.register_type_strategy(pydantic.SecretBytes, st.binary().map(pydantic.SecretBytes)) +st.register_type_strategy(pydantic.SecretStr, st.text().map(pydantic.SecretStr)) + +# IP addresses, networks, and interfaces +st.register_type_strategy(pydantic.IPvAnyAddress, st.ip_addresses()) # type: ignore[arg-type] +st.register_type_strategy( + pydantic.IPvAnyInterface, + st.from_type(ipaddress.IPv4Interface) | st.from_type(ipaddress.IPv6Interface), # type: ignore[arg-type] +) +st.register_type_strategy( + pydantic.IPvAnyNetwork, + st.from_type(ipaddress.IPv4Network) | st.from_type(ipaddress.IPv6Network), # type: ignore[arg-type] +) + +# We hook into the con***() functions and the ConstrainedNumberMeta metaclass, +# so here we only have to register subclasses for other constrained types which +# don't go via those mechanisms. Then there are the registration hooks below. +st.register_type_strategy(pydantic.StrictBool, st.booleans()) +st.register_type_strategy(pydantic.StrictStr, st.text()) + + +# FutureDate, PastDate +st.register_type_strategy(pydantic.FutureDate, st.dates(min_value=datetime.date.today() + datetime.timedelta(days=1))) +st.register_type_strategy(pydantic.PastDate, st.dates(max_value=datetime.date.today() - datetime.timedelta(days=1))) + + +# Constrained-type resolver functions +# +# For these ones, we actually want to inspect the type in order to work out a +# satisfying strategy. First up, the machinery for tracking resolver functions: + +RESOLVERS: Dict[type, Callable[[type], st.SearchStrategy]] = {} # type: ignore[type-arg] + + +@overload +def _registered(typ: Type[pydantic.types.T]) -> Type[pydantic.types.T]: + pass + + +@overload +def _registered(typ: pydantic.types.ConstrainedNumberMeta) -> pydantic.types.ConstrainedNumberMeta: + pass + + +def _registered( + typ: Union[Type[pydantic.types.T], pydantic.types.ConstrainedNumberMeta] +) -> Union[Type[pydantic.types.T], pydantic.types.ConstrainedNumberMeta]: + # This function replaces the version in `pydantic.types`, in order to + # effect the registration of new constrained types so that Hypothesis + # can generate valid examples. + pydantic.types._DEFINED_TYPES.add(typ) + for supertype, resolver in RESOLVERS.items(): + if issubclass(typ, supertype): + st.register_type_strategy(typ, resolver(typ)) # type: ignore + return typ + raise NotImplementedError(f'Unknown type {typ!r} has no resolver to register') # pragma: no cover + + +def resolves( + typ: Union[type, pydantic.types.ConstrainedNumberMeta] +) -> Callable[[Callable[..., st.SearchStrategy]], Callable[..., st.SearchStrategy]]: # type: ignore[type-arg] + def inner(f): # type: ignore + assert f not in RESOLVERS + RESOLVERS[typ] = f + return f + + return inner + + +# Type-to-strategy resolver functions + + +@resolves(pydantic.JsonWrapper) +def resolve_json(cls): # type: ignore[no-untyped-def] + try: + inner = st.none() if cls.inner_type is None else st.from_type(cls.inner_type) + except Exception: # pragma: no cover + finite = st.floats(allow_infinity=False, allow_nan=False) + inner = st.recursive( + base=st.one_of(st.none(), st.booleans(), st.integers(), finite, st.text()), + extend=lambda x: st.lists(x) | st.dictionaries(st.text(), x), # type: ignore + ) + inner_type = getattr(cls, 'inner_type', None) + return st.builds( + cls.inner_type.json if lenient_issubclass(inner_type, pydantic.BaseModel) else json.dumps, + inner, + ensure_ascii=st.booleans(), + indent=st.none() | st.integers(0, 16), + sort_keys=st.booleans(), + ) + + +@resolves(pydantic.ConstrainedBytes) +def resolve_conbytes(cls): # type: ignore[no-untyped-def] # pragma: no cover + min_size = cls.min_length or 0 + max_size = cls.max_length + if not cls.strip_whitespace: + return st.binary(min_size=min_size, max_size=max_size) + # Fun with regex to ensure we neither start nor end with whitespace + repeats = '{{{},{}}}'.format( + min_size - 2 if min_size > 2 else 0, + max_size - 2 if (max_size or 0) > 2 else '', + ) + if min_size >= 2: + pattern = rf'\W.{repeats}\W' + elif min_size == 1: + pattern = rf'\W(.{repeats}\W)?' + else: + assert min_size == 0 + pattern = rf'(\W(.{repeats}\W)?)?' + return st.from_regex(pattern.encode(), fullmatch=True) + + +@resolves(pydantic.ConstrainedDecimal) +def resolve_condecimal(cls): # type: ignore[no-untyped-def] + min_value = cls.ge + max_value = cls.le + if cls.gt is not None: + assert min_value is None, 'Set `gt` or `ge`, but not both' + min_value = cls.gt + if cls.lt is not None: + assert max_value is None, 'Set `lt` or `le`, but not both' + max_value = cls.lt + s = st.decimals(min_value, max_value, allow_nan=False, places=cls.decimal_places) + if cls.lt is not None: + s = s.filter(lambda d: d < cls.lt) + if cls.gt is not None: + s = s.filter(lambda d: cls.gt < d) + return s + + +@resolves(pydantic.ConstrainedFloat) +def resolve_confloat(cls): # type: ignore[no-untyped-def] + min_value = cls.ge + max_value = cls.le + exclude_min = False + exclude_max = False + + if cls.gt is not None: + assert min_value is None, 'Set `gt` or `ge`, but not both' + min_value = cls.gt + exclude_min = True + if cls.lt is not None: + assert max_value is None, 'Set `lt` or `le`, but not both' + max_value = cls.lt + exclude_max = True + + if cls.multiple_of is None: + return st.floats(min_value, max_value, exclude_min=exclude_min, exclude_max=exclude_max, allow_nan=False) + + if min_value is not None: + min_value = math.ceil(min_value / cls.multiple_of) + if exclude_min: + min_value = min_value + 1 + if max_value is not None: + assert max_value >= cls.multiple_of, 'Cannot build model with max value smaller than multiple of' + max_value = math.floor(max_value / cls.multiple_of) + if exclude_max: + max_value = max_value - 1 + + return st.integers(min_value, max_value).map(lambda x: x * cls.multiple_of) + + +@resolves(pydantic.ConstrainedInt) +def resolve_conint(cls): # type: ignore[no-untyped-def] + min_value = cls.ge + max_value = cls.le + if cls.gt is not None: + assert min_value is None, 'Set `gt` or `ge`, but not both' + min_value = cls.gt + 1 + if cls.lt is not None: + assert max_value is None, 'Set `lt` or `le`, but not both' + max_value = cls.lt - 1 + + if cls.multiple_of is None or cls.multiple_of == 1: + return st.integers(min_value, max_value) + + # These adjustments and the .map handle integer-valued multiples, while the + # .filter handles trickier cases as for confloat. + if min_value is not None: + min_value = math.ceil(Fraction(min_value) / Fraction(cls.multiple_of)) + if max_value is not None: + max_value = math.floor(Fraction(max_value) / Fraction(cls.multiple_of)) + return st.integers(min_value, max_value).map(lambda x: x * cls.multiple_of) + + +@resolves(pydantic.ConstrainedDate) +def resolve_condate(cls): # type: ignore[no-untyped-def] + if cls.ge is not None: + assert cls.gt is None, 'Set `gt` or `ge`, but not both' + min_value = cls.ge + elif cls.gt is not None: + min_value = cls.gt + datetime.timedelta(days=1) + else: + min_value = datetime.date.min + if cls.le is not None: + assert cls.lt is None, 'Set `lt` or `le`, but not both' + max_value = cls.le + elif cls.lt is not None: + max_value = cls.lt - datetime.timedelta(days=1) + else: + max_value = datetime.date.max + return st.dates(min_value, max_value) + + +@resolves(pydantic.ConstrainedStr) +def resolve_constr(cls): # type: ignore[no-untyped-def] # pragma: no cover + min_size = cls.min_length or 0 + max_size = cls.max_length + + if cls.regex is None and not cls.strip_whitespace: + return st.text(min_size=min_size, max_size=max_size) + + if cls.regex is not None: + strategy = st.from_regex(cls.regex) + if cls.strip_whitespace: + strategy = strategy.filter(lambda s: s == s.strip()) + elif cls.strip_whitespace: + repeats = '{{{},{}}}'.format( + min_size - 2 if min_size > 2 else 0, + max_size - 2 if (max_size or 0) > 2 else '', + ) + if min_size >= 2: + strategy = st.from_regex(rf'\W.{repeats}\W') + elif min_size == 1: + strategy = st.from_regex(rf'\W(.{repeats}\W)?') + else: + assert min_size == 0 + strategy = st.from_regex(rf'(\W(.{repeats}\W)?)?') + + if min_size == 0 and max_size is None: + return strategy + elif max_size is None: + return strategy.filter(lambda s: min_size <= len(s)) + return strategy.filter(lambda s: min_size <= len(s) <= max_size) + + +# Finally, register all previously-defined types, and patch in our new function +for typ in list(pydantic.types._DEFINED_TYPES): + _registered(typ) +pydantic.types._registered = _registered +st.register_type_strategy(pydantic.Json, resolve_json) diff --git a/env/Lib/site-packages/pydantic/v1/annotated_types.py b/env/Lib/site-packages/pydantic/v1/annotated_types.py new file mode 100644 index 0000000..d9eaaaf --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/annotated_types.py @@ -0,0 +1,72 @@ +import sys +from typing import TYPE_CHECKING, Any, Dict, FrozenSet, NamedTuple, Type + +from pydantic.v1.fields import Required +from pydantic.v1.main import BaseModel, create_model +from pydantic.v1.typing import is_typeddict, is_typeddict_special + +if TYPE_CHECKING: + from typing_extensions import TypedDict + +if sys.version_info < (3, 11): + + def is_legacy_typeddict(typeddict_cls: Type['TypedDict']) -> bool: # type: ignore[valid-type] + return is_typeddict(typeddict_cls) and type(typeddict_cls).__module__ == 'typing' + +else: + + def is_legacy_typeddict(_: Any) -> Any: + return False + + +def create_model_from_typeddict( + # Mypy bug: `Type[TypedDict]` is resolved as `Any` https://github.com/python/mypy/issues/11030 + typeddict_cls: Type['TypedDict'], # type: ignore[valid-type] + **kwargs: Any, +) -> Type['BaseModel']: + """ + Create a `BaseModel` based on the fields of a `TypedDict`. + Since `typing.TypedDict` in Python 3.8 does not store runtime information about optional keys, + we raise an error if this happens (see https://bugs.python.org/issue38834). + """ + field_definitions: Dict[str, Any] + + # Best case scenario: with python 3.9+ or when `TypedDict` is imported from `typing_extensions` + if not hasattr(typeddict_cls, '__required_keys__'): + raise TypeError( + 'You should use `typing_extensions.TypedDict` instead of `typing.TypedDict` with Python < 3.9.2. ' + 'Without it, there is no way to differentiate required and optional fields when subclassed.' + ) + + if is_legacy_typeddict(typeddict_cls) and any( + is_typeddict_special(t) for t in typeddict_cls.__annotations__.values() + ): + raise TypeError( + 'You should use `typing_extensions.TypedDict` instead of `typing.TypedDict` with Python < 3.11. ' + 'Without it, there is no way to reflect Required/NotRequired keys.' + ) + + required_keys: FrozenSet[str] = typeddict_cls.__required_keys__ # type: ignore[attr-defined] + field_definitions = { + field_name: (field_type, Required if field_name in required_keys else None) + for field_name, field_type in typeddict_cls.__annotations__.items() + } + + return create_model(typeddict_cls.__name__, **kwargs, **field_definitions) + + +def create_model_from_namedtuple(namedtuple_cls: Type['NamedTuple'], **kwargs: Any) -> Type['BaseModel']: + """ + Create a `BaseModel` based on the fields of a named tuple. + A named tuple can be created with `typing.NamedTuple` and declared annotations + but also with `collections.namedtuple`, in this case we consider all fields + to have type `Any`. + """ + # With python 3.10+, `__annotations__` always exists but can be empty hence the `getattr... or...` logic + namedtuple_annotations: Dict[str, Type[Any]] = getattr(namedtuple_cls, '__annotations__', None) or { + k: Any for k in namedtuple_cls._fields + } + field_definitions: Dict[str, Any] = { + field_name: (field_type, Required) for field_name, field_type in namedtuple_annotations.items() + } + return create_model(namedtuple_cls.__name__, **kwargs, **field_definitions) diff --git a/env/Lib/site-packages/pydantic/v1/class_validators.py b/env/Lib/site-packages/pydantic/v1/class_validators.py new file mode 100644 index 0000000..2f68fc8 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/class_validators.py @@ -0,0 +1,361 @@ +import warnings +from collections import ChainMap +from functools import partial, partialmethod, wraps +from itertools import chain +from types import FunctionType +from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Type, Union, overload + +from pydantic.v1.errors import ConfigError +from pydantic.v1.typing import AnyCallable +from pydantic.v1.utils import ROOT_KEY, in_ipython + +if TYPE_CHECKING: + from pydantic.v1.typing import AnyClassMethod + + +class Validator: + __slots__ = 'func', 'pre', 'each_item', 'always', 'check_fields', 'skip_on_failure' + + def __init__( + self, + func: AnyCallable, + pre: bool = False, + each_item: bool = False, + always: bool = False, + check_fields: bool = False, + skip_on_failure: bool = False, + ): + self.func = func + self.pre = pre + self.each_item = each_item + self.always = always + self.check_fields = check_fields + self.skip_on_failure = skip_on_failure + + +if TYPE_CHECKING: + from inspect import Signature + + from pydantic.v1.config import BaseConfig + from pydantic.v1.fields import ModelField + from pydantic.v1.types import ModelOrDc + + ValidatorCallable = Callable[[Optional[ModelOrDc], Any, Dict[str, Any], ModelField, Type[BaseConfig]], Any] + ValidatorsList = List[ValidatorCallable] + ValidatorListDict = Dict[str, List[Validator]] + +_FUNCS: Set[str] = set() +VALIDATOR_CONFIG_KEY = '__validator_config__' +ROOT_VALIDATOR_CONFIG_KEY = '__root_validator_config__' + + +def validator( + *fields: str, + pre: bool = False, + each_item: bool = False, + always: bool = False, + check_fields: bool = True, + whole: Optional[bool] = None, + allow_reuse: bool = False, +) -> Callable[[AnyCallable], 'AnyClassMethod']: + """ + Decorate methods on the class indicating that they should be used to validate fields + :param fields: which field(s) the method should be called on + :param pre: whether or not this validator should be called before the standard validators (else after) + :param each_item: for complex objects (sets, lists etc.) whether to validate individual elements rather than the + whole object + :param always: whether this method and other validators should be called even if the value is missing + :param check_fields: whether to check that the fields actually exist on the model + :param allow_reuse: whether to track and raise an error if another validator refers to the decorated function + """ + if not fields: + raise ConfigError('validator with no fields specified') + elif isinstance(fields[0], FunctionType): + raise ConfigError( + "validators should be used with fields and keyword arguments, not bare. " # noqa: Q000 + "E.g. usage should be `@validator('', ...)`" + ) + elif not all(isinstance(field, str) for field in fields): + raise ConfigError( + "validator fields should be passed as separate string args. " # noqa: Q000 + "E.g. usage should be `@validator('', '', ...)`" + ) + + if whole is not None: + warnings.warn( + 'The "whole" keyword argument is deprecated, use "each_item" (inverse meaning, default False) instead', + DeprecationWarning, + ) + assert each_item is False, '"each_item" and "whole" conflict, remove "whole"' + each_item = not whole + + def dec(f: AnyCallable) -> 'AnyClassMethod': + f_cls = _prepare_validator(f, allow_reuse) + setattr( + f_cls, + VALIDATOR_CONFIG_KEY, + ( + fields, + Validator(func=f_cls.__func__, pre=pre, each_item=each_item, always=always, check_fields=check_fields), + ), + ) + return f_cls + + return dec + + +@overload +def root_validator(_func: AnyCallable) -> 'AnyClassMethod': + ... + + +@overload +def root_validator( + *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False +) -> Callable[[AnyCallable], 'AnyClassMethod']: + ... + + +def root_validator( + _func: Optional[AnyCallable] = None, *, pre: bool = False, allow_reuse: bool = False, skip_on_failure: bool = False +) -> Union['AnyClassMethod', Callable[[AnyCallable], 'AnyClassMethod']]: + """ + Decorate methods on a model indicating that they should be used to validate (and perhaps modify) data either + before or after standard model parsing/validation is performed. + """ + if _func: + f_cls = _prepare_validator(_func, allow_reuse) + setattr( + f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre, skip_on_failure=skip_on_failure) + ) + return f_cls + + def dec(f: AnyCallable) -> 'AnyClassMethod': + f_cls = _prepare_validator(f, allow_reuse) + setattr( + f_cls, ROOT_VALIDATOR_CONFIG_KEY, Validator(func=f_cls.__func__, pre=pre, skip_on_failure=skip_on_failure) + ) + return f_cls + + return dec + + +def _prepare_validator(function: AnyCallable, allow_reuse: bool) -> 'AnyClassMethod': + """ + Avoid validators with duplicated names since without this, validators can be overwritten silently + which generally isn't the intended behaviour, don't run in ipython (see #312) or if allow_reuse is False. + """ + f_cls = function if isinstance(function, classmethod) else classmethod(function) + if not in_ipython() and not allow_reuse: + ref = ( + getattr(f_cls.__func__, '__module__', '') + + '.' + + getattr(f_cls.__func__, '__qualname__', f'') + ) + if ref in _FUNCS: + raise ConfigError(f'duplicate validator function "{ref}"; if this is intended, set `allow_reuse=True`') + _FUNCS.add(ref) + return f_cls + + +class ValidatorGroup: + def __init__(self, validators: 'ValidatorListDict') -> None: + self.validators = validators + self.used_validators = {'*'} + + def get_validators(self, name: str) -> Optional[Dict[str, Validator]]: + self.used_validators.add(name) + validators = self.validators.get(name, []) + if name != ROOT_KEY: + validators += self.validators.get('*', []) + if validators: + return {getattr(v.func, '__name__', f''): v for v in validators} + else: + return None + + def check_for_unused(self) -> None: + unused_validators = set( + chain.from_iterable( + ( + getattr(v.func, '__name__', f'') + for v in self.validators[f] + if v.check_fields + ) + for f in (self.validators.keys() - self.used_validators) + ) + ) + if unused_validators: + fn = ', '.join(unused_validators) + raise ConfigError( + f"Validators defined with incorrect fields: {fn} " # noqa: Q000 + f"(use check_fields=False if you're inheriting from the model and intended this)" + ) + + +def extract_validators(namespace: Dict[str, Any]) -> Dict[str, List[Validator]]: + validators: Dict[str, List[Validator]] = {} + for var_name, value in namespace.items(): + validator_config = getattr(value, VALIDATOR_CONFIG_KEY, None) + if validator_config: + fields, v = validator_config + for field in fields: + if field in validators: + validators[field].append(v) + else: + validators[field] = [v] + return validators + + +def extract_root_validators(namespace: Dict[str, Any]) -> Tuple[List[AnyCallable], List[Tuple[bool, AnyCallable]]]: + from inspect import signature + + pre_validators: List[AnyCallable] = [] + post_validators: List[Tuple[bool, AnyCallable]] = [] + for name, value in namespace.items(): + validator_config: Optional[Validator] = getattr(value, ROOT_VALIDATOR_CONFIG_KEY, None) + if validator_config: + sig = signature(validator_config.func) + args = list(sig.parameters.keys()) + if args[0] == 'self': + raise ConfigError( + f'Invalid signature for root validator {name}: {sig}, "self" not permitted as first argument, ' + f'should be: (cls, values).' + ) + if len(args) != 2: + raise ConfigError(f'Invalid signature for root validator {name}: {sig}, should be: (cls, values).') + # check function signature + if validator_config.pre: + pre_validators.append(validator_config.func) + else: + post_validators.append((validator_config.skip_on_failure, validator_config.func)) + return pre_validators, post_validators + + +def inherit_validators(base_validators: 'ValidatorListDict', validators: 'ValidatorListDict') -> 'ValidatorListDict': + for field, field_validators in base_validators.items(): + if field not in validators: + validators[field] = [] + validators[field] += field_validators + return validators + + +def make_generic_validator(validator: AnyCallable) -> 'ValidatorCallable': + """ + Make a generic function which calls a validator with the right arguments. + + Unfortunately other approaches (eg. return a partial of a function that builds the arguments) is slow, + hence this laborious way of doing things. + + It's done like this so validators don't all need **kwargs in their signature, eg. any combination of + the arguments "values", "fields" and/or "config" are permitted. + """ + from inspect import signature + + if not isinstance(validator, (partial, partialmethod)): + # This should be the default case, so overhead is reduced + sig = signature(validator) + args = list(sig.parameters.keys()) + else: + # Fix the generated argument lists of partial methods + sig = signature(validator.func) + args = [ + k + for k in signature(validator.func).parameters.keys() + if k not in validator.args | validator.keywords.keys() + ] + + first_arg = args.pop(0) + if first_arg == 'self': + raise ConfigError( + f'Invalid signature for validator {validator}: {sig}, "self" not permitted as first argument, ' + f'should be: (cls, value, values, config, field), "values", "config" and "field" are all optional.' + ) + elif first_arg == 'cls': + # assume the second argument is value + return wraps(validator)(_generic_validator_cls(validator, sig, set(args[1:]))) + else: + # assume the first argument was value which has already been removed + return wraps(validator)(_generic_validator_basic(validator, sig, set(args))) + + +def prep_validators(v_funcs: Iterable[AnyCallable]) -> 'ValidatorsList': + return [make_generic_validator(f) for f in v_funcs if f] + + +all_kwargs = {'values', 'field', 'config'} + + +def _generic_validator_cls(validator: AnyCallable, sig: 'Signature', args: Set[str]) -> 'ValidatorCallable': + # assume the first argument is value + has_kwargs = False + if 'kwargs' in args: + has_kwargs = True + args -= {'kwargs'} + + if not args.issubset(all_kwargs): + raise ConfigError( + f'Invalid signature for validator {validator}: {sig}, should be: ' + f'(cls, value, values, config, field), "values", "config" and "field" are all optional.' + ) + + if has_kwargs: + return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field, config=config) + elif args == set(): + return lambda cls, v, values, field, config: validator(cls, v) + elif args == {'values'}: + return lambda cls, v, values, field, config: validator(cls, v, values=values) + elif args == {'field'}: + return lambda cls, v, values, field, config: validator(cls, v, field=field) + elif args == {'config'}: + return lambda cls, v, values, field, config: validator(cls, v, config=config) + elif args == {'values', 'field'}: + return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field) + elif args == {'values', 'config'}: + return lambda cls, v, values, field, config: validator(cls, v, values=values, config=config) + elif args == {'field', 'config'}: + return lambda cls, v, values, field, config: validator(cls, v, field=field, config=config) + else: + # args == {'values', 'field', 'config'} + return lambda cls, v, values, field, config: validator(cls, v, values=values, field=field, config=config) + + +def _generic_validator_basic(validator: AnyCallable, sig: 'Signature', args: Set[str]) -> 'ValidatorCallable': + has_kwargs = False + if 'kwargs' in args: + has_kwargs = True + args -= {'kwargs'} + + if not args.issubset(all_kwargs): + raise ConfigError( + f'Invalid signature for validator {validator}: {sig}, should be: ' + f'(value, values, config, field), "values", "config" and "field" are all optional.' + ) + + if has_kwargs: + return lambda cls, v, values, field, config: validator(v, values=values, field=field, config=config) + elif args == set(): + return lambda cls, v, values, field, config: validator(v) + elif args == {'values'}: + return lambda cls, v, values, field, config: validator(v, values=values) + elif args == {'field'}: + return lambda cls, v, values, field, config: validator(v, field=field) + elif args == {'config'}: + return lambda cls, v, values, field, config: validator(v, config=config) + elif args == {'values', 'field'}: + return lambda cls, v, values, field, config: validator(v, values=values, field=field) + elif args == {'values', 'config'}: + return lambda cls, v, values, field, config: validator(v, values=values, config=config) + elif args == {'field', 'config'}: + return lambda cls, v, values, field, config: validator(v, field=field, config=config) + else: + # args == {'values', 'field', 'config'} + return lambda cls, v, values, field, config: validator(v, values=values, field=field, config=config) + + +def gather_all_validators(type_: 'ModelOrDc') -> Dict[str, 'AnyClassMethod']: + all_attributes = ChainMap(*[cls.__dict__ for cls in type_.__mro__]) # type: ignore[arg-type,var-annotated] + return { + k: v + for k, v in all_attributes.items() + if hasattr(v, VALIDATOR_CONFIG_KEY) or hasattr(v, ROOT_VALIDATOR_CONFIG_KEY) + } diff --git a/env/Lib/site-packages/pydantic/v1/color.py b/env/Lib/site-packages/pydantic/v1/color.py new file mode 100644 index 0000000..b0bbf78 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/color.py @@ -0,0 +1,494 @@ +""" +Color definitions are used as per CSS3 specification: +http://www.w3.org/TR/css3-color/#svg-color + +A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`. + +In these cases the LAST color when sorted alphabetically takes preferences, +eg. Color((0, 255, 255)).as_named() == 'cyan' because "cyan" comes after "aqua". +""" +import math +import re +from colorsys import hls_to_rgb, rgb_to_hls +from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union, cast + +from pydantic.v1.errors import ColorError +from pydantic.v1.utils import Representation, almost_equal_floats + +if TYPE_CHECKING: + from pydantic.v1.typing import CallableGenerator, ReprArgs + +ColorTuple = Union[Tuple[int, int, int], Tuple[int, int, int, float]] +ColorType = Union[ColorTuple, str] +HslColorTuple = Union[Tuple[float, float, float], Tuple[float, float, float, float]] + + +class RGBA: + """ + Internal use only as a representation of a color. + """ + + __slots__ = 'r', 'g', 'b', 'alpha', '_tuple' + + def __init__(self, r: float, g: float, b: float, alpha: Optional[float]): + self.r = r + self.g = g + self.b = b + self.alpha = alpha + + self._tuple: Tuple[float, float, float, Optional[float]] = (r, g, b, alpha) + + def __getitem__(self, item: Any) -> Any: + return self._tuple[item] + + +# these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached +r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*' +r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*' +_r_255 = r'(\d{1,3}(?:\.\d+)?)' +_r_comma = r'\s*,\s*' +r_rgb = fr'\s*rgb\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}\)\s*' +_r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)' +r_rgba = fr'\s*rgba\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_alpha}\s*\)\s*' +_r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?' +_r_sl = r'(\d{1,3}(?:\.\d+)?)%' +r_hsl = fr'\s*hsl\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}\s*\)\s*' +r_hsla = fr'\s*hsl\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}{_r_comma}{_r_alpha}\s*\)\s*' + +# colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used +repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'} +rads = 2 * math.pi + + +class Color(Representation): + __slots__ = '_original', '_rgba' + + def __init__(self, value: ColorType) -> None: + self._rgba: RGBA + self._original: ColorType + if isinstance(value, (tuple, list)): + self._rgba = parse_tuple(value) + elif isinstance(value, str): + self._rgba = parse_str(value) + elif isinstance(value, Color): + self._rgba = value._rgba + value = value._original + else: + raise ColorError(reason='value must be a tuple, list or string') + + # if we've got here value must be a valid color + self._original = value + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='string', format='color') + + def original(self) -> ColorType: + """ + Original value passed to Color + """ + return self._original + + def as_named(self, *, fallback: bool = False) -> str: + if self._rgba.alpha is None: + rgb = cast(Tuple[int, int, int], self.as_rgb_tuple()) + try: + return COLORS_BY_VALUE[rgb] + except KeyError as e: + if fallback: + return self.as_hex() + else: + raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e + else: + return self.as_hex() + + def as_hex(self) -> str: + """ + Hex string representing the color can be 3, 4, 6 or 8 characters depending on whether the string + a "short" representation of the color is possible and whether there's an alpha channel. + """ + values = [float_to_255(c) for c in self._rgba[:3]] + if self._rgba.alpha is not None: + values.append(float_to_255(self._rgba.alpha)) + + as_hex = ''.join(f'{v:02x}' for v in values) + if all(c in repeat_colors for c in values): + as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2)) + return '#' + as_hex + + def as_rgb(self) -> str: + """ + Color as an rgb(, , ) or rgba(, , , ) string. + """ + if self._rgba.alpha is None: + return f'rgb({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)})' + else: + return ( + f'rgba({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)}, ' + f'{round(self._alpha_float(), 2)})' + ) + + def as_rgb_tuple(self, *, alpha: Optional[bool] = None) -> ColorTuple: + """ + Color as an RGB or RGBA tuple; red, green and blue are in the range 0 to 255, alpha if included is + in the range 0 to 1. + + :param alpha: whether to include the alpha channel, options are + None - (default) include alpha only if it's set (e.g. not None) + True - always include alpha, + False - always omit alpha, + """ + r, g, b = (float_to_255(c) for c in self._rgba[:3]) + if alpha is None: + if self._rgba.alpha is None: + return r, g, b + else: + return r, g, b, self._alpha_float() + elif alpha: + return r, g, b, self._alpha_float() + else: + # alpha is False + return r, g, b + + def as_hsl(self) -> str: + """ + Color as an hsl(, , ) or hsl(, , , ) string. + """ + if self._rgba.alpha is None: + h, s, li = self.as_hsl_tuple(alpha=False) # type: ignore + return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})' + else: + h, s, li, a = self.as_hsl_tuple(alpha=True) # type: ignore + return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})' + + def as_hsl_tuple(self, *, alpha: Optional[bool] = None) -> HslColorTuple: + """ + Color as an HSL or HSLA tuple, e.g. hue, saturation, lightness and optionally alpha; all elements are in + the range 0 to 1. + + NOTE: this is HSL as used in HTML and most other places, not HLS as used in python's colorsys. + + :param alpha: whether to include the alpha channel, options are + None - (default) include alpha only if it's set (e.g. not None) + True - always include alpha, + False - always omit alpha, + """ + h, l, s = rgb_to_hls(self._rgba.r, self._rgba.g, self._rgba.b) + if alpha is None: + if self._rgba.alpha is None: + return h, s, l + else: + return h, s, l, self._alpha_float() + if alpha: + return h, s, l, self._alpha_float() + else: + # alpha is False + return h, s, l + + def _alpha_float(self) -> float: + return 1 if self._rgba.alpha is None else self._rgba.alpha + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls + + def __str__(self) -> str: + return self.as_named(fallback=True) + + def __repr_args__(self) -> 'ReprArgs': + return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())] # type: ignore + + def __eq__(self, other: Any) -> bool: + return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple() + + def __hash__(self) -> int: + return hash(self.as_rgb_tuple()) + + +def parse_tuple(value: Tuple[Any, ...]) -> RGBA: + """ + Parse a tuple or list as a color. + """ + if len(value) == 3: + r, g, b = (parse_color_value(v) for v in value) + return RGBA(r, g, b, None) + elif len(value) == 4: + r, g, b = (parse_color_value(v) for v in value[:3]) + return RGBA(r, g, b, parse_float_alpha(value[3])) + else: + raise ColorError(reason='tuples must have length 3 or 4') + + +def parse_str(value: str) -> RGBA: + """ + Parse a string to an RGBA tuple, trying the following formats (in this order): + * named color, see COLORS_BY_NAME below + * hex short eg. `fff` (prefix can be `#`, `0x` or nothing) + * hex long eg. `ffffff` (prefix can be `#`, `0x` or nothing) + * `rgb(, , ) ` + * `rgba(, , , )` + """ + value_lower = value.lower() + try: + r, g, b = COLORS_BY_NAME[value_lower] + except KeyError: + pass + else: + return ints_to_rgba(r, g, b, None) + + m = re.fullmatch(r_hex_short, value_lower) + if m: + *rgb, a = m.groups() + r, g, b = (int(v * 2, 16) for v in rgb) + if a: + alpha: Optional[float] = int(a * 2, 16) / 255 + else: + alpha = None + return ints_to_rgba(r, g, b, alpha) + + m = re.fullmatch(r_hex_long, value_lower) + if m: + *rgb, a = m.groups() + r, g, b = (int(v, 16) for v in rgb) + if a: + alpha = int(a, 16) / 255 + else: + alpha = None + return ints_to_rgba(r, g, b, alpha) + + m = re.fullmatch(r_rgb, value_lower) + if m: + return ints_to_rgba(*m.groups(), None) # type: ignore + + m = re.fullmatch(r_rgba, value_lower) + if m: + return ints_to_rgba(*m.groups()) # type: ignore + + m = re.fullmatch(r_hsl, value_lower) + if m: + h, h_units, s, l_ = m.groups() + return parse_hsl(h, h_units, s, l_) + + m = re.fullmatch(r_hsla, value_lower) + if m: + h, h_units, s, l_, a = m.groups() + return parse_hsl(h, h_units, s, l_, parse_float_alpha(a)) + + raise ColorError(reason='string not recognised as a valid color') + + +def ints_to_rgba(r: Union[int, str], g: Union[int, str], b: Union[int, str], alpha: Optional[float]) -> RGBA: + return RGBA(parse_color_value(r), parse_color_value(g), parse_color_value(b), parse_float_alpha(alpha)) + + +def parse_color_value(value: Union[int, str], max_val: int = 255) -> float: + """ + Parse a value checking it's a valid int in the range 0 to max_val and divide by max_val to give a number + in the range 0 to 1 + """ + try: + color = float(value) + except ValueError: + raise ColorError(reason='color values must be a valid number') + if 0 <= color <= max_val: + return color / max_val + else: + raise ColorError(reason=f'color values must be in the range 0 to {max_val}') + + +def parse_float_alpha(value: Union[None, str, float, int]) -> Optional[float]: + """ + Parse a value checking it's a valid float in the range 0 to 1 + """ + if value is None: + return None + try: + if isinstance(value, str) and value.endswith('%'): + alpha = float(value[:-1]) / 100 + else: + alpha = float(value) + except ValueError: + raise ColorError(reason='alpha values must be a valid float') + + if almost_equal_floats(alpha, 1): + return None + elif 0 <= alpha <= 1: + return alpha + else: + raise ColorError(reason='alpha values must be in the range 0 to 1') + + +def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: Optional[float] = None) -> RGBA: + """ + Parse raw hue, saturation, lightness and alpha values and convert to RGBA. + """ + s_value, l_value = parse_color_value(sat, 100), parse_color_value(light, 100) + + h_value = float(h) + if h_units in {None, 'deg'}: + h_value = h_value % 360 / 360 + elif h_units == 'rad': + h_value = h_value % rads / rads + else: + # turns + h_value = h_value % 1 + + r, g, b = hls_to_rgb(h_value, l_value, s_value) + return RGBA(r, g, b, alpha) + + +def float_to_255(c: float) -> int: + return int(round(c * 255)) + + +COLORS_BY_NAME = { + 'aliceblue': (240, 248, 255), + 'antiquewhite': (250, 235, 215), + 'aqua': (0, 255, 255), + 'aquamarine': (127, 255, 212), + 'azure': (240, 255, 255), + 'beige': (245, 245, 220), + 'bisque': (255, 228, 196), + 'black': (0, 0, 0), + 'blanchedalmond': (255, 235, 205), + 'blue': (0, 0, 255), + 'blueviolet': (138, 43, 226), + 'brown': (165, 42, 42), + 'burlywood': (222, 184, 135), + 'cadetblue': (95, 158, 160), + 'chartreuse': (127, 255, 0), + 'chocolate': (210, 105, 30), + 'coral': (255, 127, 80), + 'cornflowerblue': (100, 149, 237), + 'cornsilk': (255, 248, 220), + 'crimson': (220, 20, 60), + 'cyan': (0, 255, 255), + 'darkblue': (0, 0, 139), + 'darkcyan': (0, 139, 139), + 'darkgoldenrod': (184, 134, 11), + 'darkgray': (169, 169, 169), + 'darkgreen': (0, 100, 0), + 'darkgrey': (169, 169, 169), + 'darkkhaki': (189, 183, 107), + 'darkmagenta': (139, 0, 139), + 'darkolivegreen': (85, 107, 47), + 'darkorange': (255, 140, 0), + 'darkorchid': (153, 50, 204), + 'darkred': (139, 0, 0), + 'darksalmon': (233, 150, 122), + 'darkseagreen': (143, 188, 143), + 'darkslateblue': (72, 61, 139), + 'darkslategray': (47, 79, 79), + 'darkslategrey': (47, 79, 79), + 'darkturquoise': (0, 206, 209), + 'darkviolet': (148, 0, 211), + 'deeppink': (255, 20, 147), + 'deepskyblue': (0, 191, 255), + 'dimgray': (105, 105, 105), + 'dimgrey': (105, 105, 105), + 'dodgerblue': (30, 144, 255), + 'firebrick': (178, 34, 34), + 'floralwhite': (255, 250, 240), + 'forestgreen': (34, 139, 34), + 'fuchsia': (255, 0, 255), + 'gainsboro': (220, 220, 220), + 'ghostwhite': (248, 248, 255), + 'gold': (255, 215, 0), + 'goldenrod': (218, 165, 32), + 'gray': (128, 128, 128), + 'green': (0, 128, 0), + 'greenyellow': (173, 255, 47), + 'grey': (128, 128, 128), + 'honeydew': (240, 255, 240), + 'hotpink': (255, 105, 180), + 'indianred': (205, 92, 92), + 'indigo': (75, 0, 130), + 'ivory': (255, 255, 240), + 'khaki': (240, 230, 140), + 'lavender': (230, 230, 250), + 'lavenderblush': (255, 240, 245), + 'lawngreen': (124, 252, 0), + 'lemonchiffon': (255, 250, 205), + 'lightblue': (173, 216, 230), + 'lightcoral': (240, 128, 128), + 'lightcyan': (224, 255, 255), + 'lightgoldenrodyellow': (250, 250, 210), + 'lightgray': (211, 211, 211), + 'lightgreen': (144, 238, 144), + 'lightgrey': (211, 211, 211), + 'lightpink': (255, 182, 193), + 'lightsalmon': (255, 160, 122), + 'lightseagreen': (32, 178, 170), + 'lightskyblue': (135, 206, 250), + 'lightslategray': (119, 136, 153), + 'lightslategrey': (119, 136, 153), + 'lightsteelblue': (176, 196, 222), + 'lightyellow': (255, 255, 224), + 'lime': (0, 255, 0), + 'limegreen': (50, 205, 50), + 'linen': (250, 240, 230), + 'magenta': (255, 0, 255), + 'maroon': (128, 0, 0), + 'mediumaquamarine': (102, 205, 170), + 'mediumblue': (0, 0, 205), + 'mediumorchid': (186, 85, 211), + 'mediumpurple': (147, 112, 219), + 'mediumseagreen': (60, 179, 113), + 'mediumslateblue': (123, 104, 238), + 'mediumspringgreen': (0, 250, 154), + 'mediumturquoise': (72, 209, 204), + 'mediumvioletred': (199, 21, 133), + 'midnightblue': (25, 25, 112), + 'mintcream': (245, 255, 250), + 'mistyrose': (255, 228, 225), + 'moccasin': (255, 228, 181), + 'navajowhite': (255, 222, 173), + 'navy': (0, 0, 128), + 'oldlace': (253, 245, 230), + 'olive': (128, 128, 0), + 'olivedrab': (107, 142, 35), + 'orange': (255, 165, 0), + 'orangered': (255, 69, 0), + 'orchid': (218, 112, 214), + 'palegoldenrod': (238, 232, 170), + 'palegreen': (152, 251, 152), + 'paleturquoise': (175, 238, 238), + 'palevioletred': (219, 112, 147), + 'papayawhip': (255, 239, 213), + 'peachpuff': (255, 218, 185), + 'peru': (205, 133, 63), + 'pink': (255, 192, 203), + 'plum': (221, 160, 221), + 'powderblue': (176, 224, 230), + 'purple': (128, 0, 128), + 'red': (255, 0, 0), + 'rosybrown': (188, 143, 143), + 'royalblue': (65, 105, 225), + 'saddlebrown': (139, 69, 19), + 'salmon': (250, 128, 114), + 'sandybrown': (244, 164, 96), + 'seagreen': (46, 139, 87), + 'seashell': (255, 245, 238), + 'sienna': (160, 82, 45), + 'silver': (192, 192, 192), + 'skyblue': (135, 206, 235), + 'slateblue': (106, 90, 205), + 'slategray': (112, 128, 144), + 'slategrey': (112, 128, 144), + 'snow': (255, 250, 250), + 'springgreen': (0, 255, 127), + 'steelblue': (70, 130, 180), + 'tan': (210, 180, 140), + 'teal': (0, 128, 128), + 'thistle': (216, 191, 216), + 'tomato': (255, 99, 71), + 'turquoise': (64, 224, 208), + 'violet': (238, 130, 238), + 'wheat': (245, 222, 179), + 'white': (255, 255, 255), + 'whitesmoke': (245, 245, 245), + 'yellow': (255, 255, 0), + 'yellowgreen': (154, 205, 50), +} + +COLORS_BY_VALUE = {v: k for k, v in COLORS_BY_NAME.items()} diff --git a/env/Lib/site-packages/pydantic/v1/dataclasses.py b/env/Lib/site-packages/pydantic/v1/dataclasses.py new file mode 100644 index 0000000..bd16702 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/dataclasses.py @@ -0,0 +1,500 @@ +""" +The main purpose is to enhance stdlib dataclasses by adding validation +A pydantic dataclass can be generated from scratch or from a stdlib one. + +Behind the scene, a pydantic dataclass is just like a regular one on which we attach +a `BaseModel` and magic methods to trigger the validation of the data. +`__init__` and `__post_init__` are hence overridden and have extra logic to be +able to validate input data. + +When a pydantic dataclass is generated from scratch, it's just a plain dataclass +with validation triggered at initialization + +The tricky part if for stdlib dataclasses that are converted after into pydantic ones e.g. + +```py +@dataclasses.dataclass +class M: + x: int + +ValidatedM = pydantic.dataclasses.dataclass(M) +``` + +We indeed still want to support equality, hashing, repr, ... as if it was the stdlib one! + +```py +assert isinstance(ValidatedM(x=1), M) +assert ValidatedM(x=1) == M(x=1) +``` + +This means we **don't want to create a new dataclass that inherits from it** +The trick is to create a wrapper around `M` that will act as a proxy to trigger +validation without altering default `M` behaviour. +""" +import copy +import dataclasses +import sys +from contextlib import contextmanager +from functools import wraps + +try: + from functools import cached_property +except ImportError: + # cached_property available only for python3.8+ + pass + +from typing import TYPE_CHECKING, Any, Callable, ClassVar, Dict, Generator, Optional, Type, TypeVar, Union, overload + +from typing_extensions import dataclass_transform + +from pydantic.v1.class_validators import gather_all_validators +from pydantic.v1.config import BaseConfig, ConfigDict, Extra, get_config +from pydantic.v1.error_wrappers import ValidationError +from pydantic.v1.errors import DataclassTypeError +from pydantic.v1.fields import Field, FieldInfo, Required, Undefined +from pydantic.v1.main import create_model, validate_model +from pydantic.v1.utils import ClassAttribute + +if TYPE_CHECKING: + from pydantic.v1.main import BaseModel + from pydantic.v1.typing import CallableGenerator, NoArgAnyCallable + + DataclassT = TypeVar('DataclassT', bound='Dataclass') + + DataclassClassOrWrapper = Union[Type['Dataclass'], 'DataclassProxy'] + + class Dataclass: + # stdlib attributes + __dataclass_fields__: ClassVar[Dict[str, Any]] + __dataclass_params__: ClassVar[Any] # in reality `dataclasses._DataclassParams` + __post_init__: ClassVar[Callable[..., None]] + + # Added by pydantic + __pydantic_run_validation__: ClassVar[bool] + __post_init_post_parse__: ClassVar[Callable[..., None]] + __pydantic_initialised__: ClassVar[bool] + __pydantic_model__: ClassVar[Type[BaseModel]] + __pydantic_validate_values__: ClassVar[Callable[['Dataclass'], None]] + __pydantic_has_field_info_default__: ClassVar[bool] # whether a `pydantic.Field` is used as default value + + def __init__(self, *args: object, **kwargs: object) -> None: + pass + + @classmethod + def __get_validators__(cls: Type['Dataclass']) -> 'CallableGenerator': + pass + + @classmethod + def __validate__(cls: Type['DataclassT'], v: Any) -> 'DataclassT': + pass + + +__all__ = [ + 'dataclass', + 'set_validation', + 'create_pydantic_model_from_dataclass', + 'is_builtin_dataclass', + 'make_dataclass_validator', +] + +_T = TypeVar('_T') + +if sys.version_info >= (3, 10): + + @dataclass_transform(field_specifiers=(dataclasses.field, Field)) + @overload + def dataclass( + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: Union[ConfigDict, Type[object], None] = None, + validate_on_init: Optional[bool] = None, + use_proxy: Optional[bool] = None, + kw_only: bool = ..., + ) -> Callable[[Type[_T]], 'DataclassClassOrWrapper']: + ... + + @dataclass_transform(field_specifiers=(dataclasses.field, Field)) + @overload + def dataclass( + _cls: Type[_T], + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: Union[ConfigDict, Type[object], None] = None, + validate_on_init: Optional[bool] = None, + use_proxy: Optional[bool] = None, + kw_only: bool = ..., + ) -> 'DataclassClassOrWrapper': + ... + +else: + + @dataclass_transform(field_specifiers=(dataclasses.field, Field)) + @overload + def dataclass( + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: Union[ConfigDict, Type[object], None] = None, + validate_on_init: Optional[bool] = None, + use_proxy: Optional[bool] = None, + ) -> Callable[[Type[_T]], 'DataclassClassOrWrapper']: + ... + + @dataclass_transform(field_specifiers=(dataclasses.field, Field)) + @overload + def dataclass( + _cls: Type[_T], + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: Union[ConfigDict, Type[object], None] = None, + validate_on_init: Optional[bool] = None, + use_proxy: Optional[bool] = None, + ) -> 'DataclassClassOrWrapper': + ... + + +@dataclass_transform(field_specifiers=(dataclasses.field, Field)) +def dataclass( + _cls: Optional[Type[_T]] = None, + *, + init: bool = True, + repr: bool = True, + eq: bool = True, + order: bool = False, + unsafe_hash: bool = False, + frozen: bool = False, + config: Union[ConfigDict, Type[object], None] = None, + validate_on_init: Optional[bool] = None, + use_proxy: Optional[bool] = None, + kw_only: bool = False, +) -> Union[Callable[[Type[_T]], 'DataclassClassOrWrapper'], 'DataclassClassOrWrapper']: + """ + Like the python standard lib dataclasses but with type validation. + The result is either a pydantic dataclass that will validate input data + or a wrapper that will trigger validation around a stdlib dataclass + to avoid modifying it directly + """ + the_config = get_config(config) + + def wrap(cls: Type[Any]) -> 'DataclassClassOrWrapper': + should_use_proxy = ( + use_proxy + if use_proxy is not None + else ( + is_builtin_dataclass(cls) + and (cls.__bases__[0] is object or set(dir(cls)) == set(dir(cls.__bases__[0]))) + ) + ) + if should_use_proxy: + dc_cls_doc = '' + dc_cls = DataclassProxy(cls) + default_validate_on_init = False + else: + dc_cls_doc = cls.__doc__ or '' # needs to be done before generating dataclass + if sys.version_info >= (3, 10): + dc_cls = dataclasses.dataclass( + cls, + init=init, + repr=repr, + eq=eq, + order=order, + unsafe_hash=unsafe_hash, + frozen=frozen, + kw_only=kw_only, + ) + else: + dc_cls = dataclasses.dataclass( # type: ignore + cls, init=init, repr=repr, eq=eq, order=order, unsafe_hash=unsafe_hash, frozen=frozen + ) + default_validate_on_init = True + + should_validate_on_init = default_validate_on_init if validate_on_init is None else validate_on_init + _add_pydantic_validation_attributes(cls, the_config, should_validate_on_init, dc_cls_doc) + dc_cls.__pydantic_model__.__try_update_forward_refs__(**{cls.__name__: cls}) + return dc_cls + + if _cls is None: + return wrap + + return wrap(_cls) + + +@contextmanager +def set_validation(cls: Type['DataclassT'], value: bool) -> Generator[Type['DataclassT'], None, None]: + original_run_validation = cls.__pydantic_run_validation__ + try: + cls.__pydantic_run_validation__ = value + yield cls + finally: + cls.__pydantic_run_validation__ = original_run_validation + + +class DataclassProxy: + __slots__ = '__dataclass__' + + def __init__(self, dc_cls: Type['Dataclass']) -> None: + object.__setattr__(self, '__dataclass__', dc_cls) + + def __call__(self, *args: Any, **kwargs: Any) -> Any: + with set_validation(self.__dataclass__, True): + return self.__dataclass__(*args, **kwargs) + + def __getattr__(self, name: str) -> Any: + return getattr(self.__dataclass__, name) + + def __setattr__(self, __name: str, __value: Any) -> None: + return setattr(self.__dataclass__, __name, __value) + + def __instancecheck__(self, instance: Any) -> bool: + return isinstance(instance, self.__dataclass__) + + def __copy__(self) -> 'DataclassProxy': + return DataclassProxy(copy.copy(self.__dataclass__)) + + def __deepcopy__(self, memo: Any) -> 'DataclassProxy': + return DataclassProxy(copy.deepcopy(self.__dataclass__, memo)) + + +def _add_pydantic_validation_attributes( # noqa: C901 (ignore complexity) + dc_cls: Type['Dataclass'], + config: Type[BaseConfig], + validate_on_init: bool, + dc_cls_doc: str, +) -> None: + """ + We need to replace the right method. If no `__post_init__` has been set in the stdlib dataclass + it won't even exist (code is generated on the fly by `dataclasses`) + By default, we run validation after `__init__` or `__post_init__` if defined + """ + init = dc_cls.__init__ + + @wraps(init) + def handle_extra_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None: + if config.extra == Extra.ignore: + init(self, *args, **{k: v for k, v in kwargs.items() if k in self.__dataclass_fields__}) + + elif config.extra == Extra.allow: + for k, v in kwargs.items(): + self.__dict__.setdefault(k, v) + init(self, *args, **{k: v for k, v in kwargs.items() if k in self.__dataclass_fields__}) + + else: + init(self, *args, **kwargs) + + if hasattr(dc_cls, '__post_init__'): + try: + post_init = dc_cls.__post_init__.__wrapped__ # type: ignore[attr-defined] + except AttributeError: + post_init = dc_cls.__post_init__ + + @wraps(post_init) + def new_post_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None: + if config.post_init_call == 'before_validation': + post_init(self, *args, **kwargs) + + if self.__class__.__pydantic_run_validation__: + self.__pydantic_validate_values__() + if hasattr(self, '__post_init_post_parse__'): + self.__post_init_post_parse__(*args, **kwargs) + + if config.post_init_call == 'after_validation': + post_init(self, *args, **kwargs) + + setattr(dc_cls, '__init__', handle_extra_init) + setattr(dc_cls, '__post_init__', new_post_init) + + else: + + @wraps(init) + def new_init(self: 'Dataclass', *args: Any, **kwargs: Any) -> None: + handle_extra_init(self, *args, **kwargs) + + if self.__class__.__pydantic_run_validation__: + self.__pydantic_validate_values__() + + if hasattr(self, '__post_init_post_parse__'): + # We need to find again the initvars. To do that we use `__dataclass_fields__` instead of + # public method `dataclasses.fields` + + # get all initvars and their default values + initvars_and_values: Dict[str, Any] = {} + for i, f in enumerate(self.__class__.__dataclass_fields__.values()): + if f._field_type is dataclasses._FIELD_INITVAR: # type: ignore[attr-defined] + try: + # set arg value by default + initvars_and_values[f.name] = args[i] + except IndexError: + initvars_and_values[f.name] = kwargs.get(f.name, f.default) + + self.__post_init_post_parse__(**initvars_and_values) + + setattr(dc_cls, '__init__', new_init) + + setattr(dc_cls, '__pydantic_run_validation__', ClassAttribute('__pydantic_run_validation__', validate_on_init)) + setattr(dc_cls, '__pydantic_initialised__', False) + setattr(dc_cls, '__pydantic_model__', create_pydantic_model_from_dataclass(dc_cls, config, dc_cls_doc)) + setattr(dc_cls, '__pydantic_validate_values__', _dataclass_validate_values) + setattr(dc_cls, '__validate__', classmethod(_validate_dataclass)) + setattr(dc_cls, '__get_validators__', classmethod(_get_validators)) + + if dc_cls.__pydantic_model__.__config__.validate_assignment and not dc_cls.__dataclass_params__.frozen: + setattr(dc_cls, '__setattr__', _dataclass_validate_assignment_setattr) + + +def _get_validators(cls: 'DataclassClassOrWrapper') -> 'CallableGenerator': + yield cls.__validate__ + + +def _validate_dataclass(cls: Type['DataclassT'], v: Any) -> 'DataclassT': + with set_validation(cls, True): + if isinstance(v, cls): + v.__pydantic_validate_values__() + return v + elif isinstance(v, (list, tuple)): + return cls(*v) + elif isinstance(v, dict): + return cls(**v) + else: + raise DataclassTypeError(class_name=cls.__name__) + + +def create_pydantic_model_from_dataclass( + dc_cls: Type['Dataclass'], + config: Type[Any] = BaseConfig, + dc_cls_doc: Optional[str] = None, +) -> Type['BaseModel']: + field_definitions: Dict[str, Any] = {} + for field in dataclasses.fields(dc_cls): + default: Any = Undefined + default_factory: Optional['NoArgAnyCallable'] = None + field_info: FieldInfo + + if field.default is not dataclasses.MISSING: + default = field.default + elif field.default_factory is not dataclasses.MISSING: + default_factory = field.default_factory + else: + default = Required + + if isinstance(default, FieldInfo): + field_info = default + dc_cls.__pydantic_has_field_info_default__ = True + else: + field_info = Field(default=default, default_factory=default_factory, **field.metadata) + + field_definitions[field.name] = (field.type, field_info) + + validators = gather_all_validators(dc_cls) + model: Type['BaseModel'] = create_model( + dc_cls.__name__, + __config__=config, + __module__=dc_cls.__module__, + __validators__=validators, + __cls_kwargs__={'__resolve_forward_refs__': False}, + **field_definitions, + ) + model.__doc__ = dc_cls_doc if dc_cls_doc is not None else dc_cls.__doc__ or '' + return model + + +if sys.version_info >= (3, 8): + + def _is_field_cached_property(obj: 'Dataclass', k: str) -> bool: + return isinstance(getattr(type(obj), k, None), cached_property) + +else: + + def _is_field_cached_property(obj: 'Dataclass', k: str) -> bool: + return False + + +def _dataclass_validate_values(self: 'Dataclass') -> None: + # validation errors can occur if this function is called twice on an already initialised dataclass. + # for example if Extra.forbid is enabled, it would consider __pydantic_initialised__ an invalid extra property + if getattr(self, '__pydantic_initialised__'): + return + if getattr(self, '__pydantic_has_field_info_default__', False): + # We need to remove `FieldInfo` values since they are not valid as input + # It's ok to do that because they are obviously the default values! + input_data = { + k: v + for k, v in self.__dict__.items() + if not (isinstance(v, FieldInfo) or _is_field_cached_property(self, k)) + } + else: + input_data = {k: v for k, v in self.__dict__.items() if not _is_field_cached_property(self, k)} + d, _, validation_error = validate_model(self.__pydantic_model__, input_data, cls=self.__class__) + if validation_error: + raise validation_error + self.__dict__.update(d) + object.__setattr__(self, '__pydantic_initialised__', True) + + +def _dataclass_validate_assignment_setattr(self: 'Dataclass', name: str, value: Any) -> None: + if self.__pydantic_initialised__: + d = dict(self.__dict__) + d.pop(name, None) + known_field = self.__pydantic_model__.__fields__.get(name, None) + if known_field: + value, error_ = known_field.validate(value, d, loc=name, cls=self.__class__) + if error_: + raise ValidationError([error_], self.__class__) + + object.__setattr__(self, name, value) + + +def is_builtin_dataclass(_cls: Type[Any]) -> bool: + """ + Whether a class is a stdlib dataclass + (useful to discriminated a pydantic dataclass that is actually a wrapper around a stdlib dataclass) + + we check that + - `_cls` is a dataclass + - `_cls` is not a processed pydantic dataclass (with a basemodel attached) + - `_cls` is not a pydantic dataclass inheriting directly from a stdlib dataclass + e.g. + ``` + @dataclasses.dataclass + class A: + x: int + + @pydantic.dataclasses.dataclass + class B(A): + y: int + ``` + In this case, when we first check `B`, we make an extra check and look at the annotations ('y'), + which won't be a superset of all the dataclass fields (only the stdlib fields i.e. 'x') + """ + return ( + dataclasses.is_dataclass(_cls) + and not hasattr(_cls, '__pydantic_model__') + and set(_cls.__dataclass_fields__).issuperset(set(getattr(_cls, '__annotations__', {}))) + ) + + +def make_dataclass_validator(dc_cls: Type['Dataclass'], config: Type[BaseConfig]) -> 'CallableGenerator': + """ + Create a pydantic.dataclass from a builtin dataclass to add type validation + and yield the validators + It retrieves the parameters of the dataclass and forwards them to the newly created dataclass + """ + yield from _get_validators(dataclass(dc_cls, config=config, use_proxy=True)) diff --git a/env/Lib/site-packages/pydantic/v1/datetime_parse.py b/env/Lib/site-packages/pydantic/v1/datetime_parse.py new file mode 100644 index 0000000..a7598fc --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/datetime_parse.py @@ -0,0 +1,248 @@ +""" +Functions to parse datetime objects. + +We're using regular expressions rather than time.strptime because: +- They provide both validation and parsing. +- They're more flexible for datetimes. +- The date/datetime/time constructors produce friendlier error messages. + +Stolen from https://raw.githubusercontent.com/django/django/main/django/utils/dateparse.py at +9718fa2e8abe430c3526a9278dd976443d4ae3c6 + +Changed to: +* use standard python datetime types not django.utils.timezone +* raise ValueError when regex doesn't match rather than returning None +* support parsing unix timestamps for dates and datetimes +""" +import re +from datetime import date, datetime, time, timedelta, timezone +from typing import Dict, Optional, Type, Union + +from pydantic.v1 import errors + +date_expr = r'(?P\d{4})-(?P\d{1,2})-(?P\d{1,2})' +time_expr = ( + r'(?P\d{1,2}):(?P\d{1,2})' + r'(?::(?P\d{1,2})(?:\.(?P\d{1,6})\d{0,6})?)?' + r'(?PZ|[+-]\d{2}(?::?\d{2})?)?$' +) + +date_re = re.compile(f'{date_expr}$') +time_re = re.compile(time_expr) +datetime_re = re.compile(f'{date_expr}[T ]{time_expr}') + +standard_duration_re = re.compile( + r'^' + r'(?:(?P-?\d+) (days?, )?)?' + r'((?:(?P-?\d+):)(?=\d+:\d+))?' + r'(?:(?P-?\d+):)?' + r'(?P-?\d+)' + r'(?:\.(?P\d{1,6})\d{0,6})?' + r'$' +) + +# Support the sections of ISO 8601 date representation that are accepted by timedelta +iso8601_duration_re = re.compile( + r'^(?P[-+]?)' + r'P' + r'(?:(?P\d+(.\d+)?)D)?' + r'(?:T' + r'(?:(?P\d+(.\d+)?)H)?' + r'(?:(?P\d+(.\d+)?)M)?' + r'(?:(?P\d+(.\d+)?)S)?' + r')?' + r'$' +) + +EPOCH = datetime(1970, 1, 1) +# if greater than this, the number is in ms, if less than or equal it's in seconds +# (in seconds this is 11th October 2603, in ms it's 20th August 1970) +MS_WATERSHED = int(2e10) +# slightly more than datetime.max in ns - (datetime.max - EPOCH).total_seconds() * 1e9 +MAX_NUMBER = int(3e20) +StrBytesIntFloat = Union[str, bytes, int, float] + + +def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[None, int, float]: + if isinstance(value, (int, float)): + return value + try: + return float(value) + except ValueError: + return None + except TypeError: + raise TypeError(f'invalid type; expected {native_expected_type}, string, bytes, int or float') + + +def from_unix_seconds(seconds: Union[int, float]) -> datetime: + if seconds > MAX_NUMBER: + return datetime.max + elif seconds < -MAX_NUMBER: + return datetime.min + + while abs(seconds) > MS_WATERSHED: + seconds /= 1000 + dt = EPOCH + timedelta(seconds=seconds) + return dt.replace(tzinfo=timezone.utc) + + +def _parse_timezone(value: Optional[str], error: Type[Exception]) -> Union[None, int, timezone]: + if value == 'Z': + return timezone.utc + elif value is not None: + offset_mins = int(value[-2:]) if len(value) > 3 else 0 + offset = 60 * int(value[1:3]) + offset_mins + if value[0] == '-': + offset = -offset + try: + return timezone(timedelta(minutes=offset)) + except ValueError: + raise error() + else: + return None + + +def parse_date(value: Union[date, StrBytesIntFloat]) -> date: + """ + Parse a date/int/float/string and return a datetime.date. + + Raise ValueError if the input is well formatted but not a valid date. + Raise ValueError if the input isn't well formatted. + """ + if isinstance(value, date): + if isinstance(value, datetime): + return value.date() + else: + return value + + number = get_numeric(value, 'date') + if number is not None: + return from_unix_seconds(number).date() + + if isinstance(value, bytes): + value = value.decode() + + match = date_re.match(value) # type: ignore + if match is None: + raise errors.DateError() + + kw = {k: int(v) for k, v in match.groupdict().items()} + + try: + return date(**kw) + except ValueError: + raise errors.DateError() + + +def parse_time(value: Union[time, StrBytesIntFloat]) -> time: + """ + Parse a time/string and return a datetime.time. + + Raise ValueError if the input is well formatted but not a valid time. + Raise ValueError if the input isn't well formatted, in particular if it contains an offset. + """ + if isinstance(value, time): + return value + + number = get_numeric(value, 'time') + if number is not None: + if number >= 86400: + # doesn't make sense since the time time loop back around to 0 + raise errors.TimeError() + return (datetime.min + timedelta(seconds=number)).time() + + if isinstance(value, bytes): + value = value.decode() + + match = time_re.match(value) # type: ignore + if match is None: + raise errors.TimeError() + + kw = match.groupdict() + if kw['microsecond']: + kw['microsecond'] = kw['microsecond'].ljust(6, '0') + + tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.TimeError) + kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None} + kw_['tzinfo'] = tzinfo + + try: + return time(**kw_) # type: ignore + except ValueError: + raise errors.TimeError() + + +def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: + """ + Parse a datetime/int/float/string and return a datetime.datetime. + + This function supports time zone offsets. When the input contains one, + the output uses a timezone with a fixed offset from UTC. + + Raise ValueError if the input is well formatted but not a valid datetime. + Raise ValueError if the input isn't well formatted. + """ + if isinstance(value, datetime): + return value + + number = get_numeric(value, 'datetime') + if number is not None: + return from_unix_seconds(number) + + if isinstance(value, bytes): + value = value.decode() + + match = datetime_re.match(value) # type: ignore + if match is None: + raise errors.DateTimeError() + + kw = match.groupdict() + if kw['microsecond']: + kw['microsecond'] = kw['microsecond'].ljust(6, '0') + + tzinfo = _parse_timezone(kw.pop('tzinfo'), errors.DateTimeError) + kw_: Dict[str, Union[None, int, timezone]] = {k: int(v) for k, v in kw.items() if v is not None} + kw_['tzinfo'] = tzinfo + + try: + return datetime(**kw_) # type: ignore + except ValueError: + raise errors.DateTimeError() + + +def parse_duration(value: StrBytesIntFloat) -> timedelta: + """ + Parse a duration int/float/string and return a datetime.timedelta. + + The preferred format for durations in Django is '%d %H:%M:%S.%f'. + + Also supports ISO 8601 representation. + """ + if isinstance(value, timedelta): + return value + + if isinstance(value, (int, float)): + # below code requires a string + value = f'{value:f}' + elif isinstance(value, bytes): + value = value.decode() + + try: + match = standard_duration_re.match(value) or iso8601_duration_re.match(value) + except TypeError: + raise TypeError('invalid type; expected timedelta, string, bytes, int or float') + + if not match: + raise errors.DurationError() + + kw = match.groupdict() + sign = -1 if kw.pop('sign', '+') == '-' else 1 + if kw.get('microseconds'): + kw['microseconds'] = kw['microseconds'].ljust(6, '0') + + if kw.get('seconds') and kw.get('microseconds') and kw['seconds'].startswith('-'): + kw['microseconds'] = '-' + kw['microseconds'] + + kw_ = {k: float(v) for k, v in kw.items() if v is not None} + + return sign * timedelta(**kw_) diff --git a/env/Lib/site-packages/pydantic/v1/decorator.py b/env/Lib/site-packages/pydantic/v1/decorator.py new file mode 100644 index 0000000..2c7c2c2 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/decorator.py @@ -0,0 +1,264 @@ +from functools import wraps +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, TypeVar, Union, overload + +from pydantic.v1 import validator +from pydantic.v1.config import Extra +from pydantic.v1.errors import ConfigError +from pydantic.v1.main import BaseModel, create_model +from pydantic.v1.typing import get_all_type_hints +from pydantic.v1.utils import to_camel + +__all__ = ('validate_arguments',) + +if TYPE_CHECKING: + from pydantic.v1.typing import AnyCallable + + AnyCallableT = TypeVar('AnyCallableT', bound=AnyCallable) + ConfigType = Union[None, Type[Any], Dict[str, Any]] + + +@overload +def validate_arguments(func: None = None, *, config: 'ConfigType' = None) -> Callable[['AnyCallableT'], 'AnyCallableT']: + ... + + +@overload +def validate_arguments(func: 'AnyCallableT') -> 'AnyCallableT': + ... + + +def validate_arguments(func: Optional['AnyCallableT'] = None, *, config: 'ConfigType' = None) -> Any: + """ + Decorator to validate the arguments passed to a function. + """ + + def validate(_func: 'AnyCallable') -> 'AnyCallable': + vd = ValidatedFunction(_func, config) + + @wraps(_func) + def wrapper_function(*args: Any, **kwargs: Any) -> Any: + return vd.call(*args, **kwargs) + + wrapper_function.vd = vd # type: ignore + wrapper_function.validate = vd.init_model_instance # type: ignore + wrapper_function.raw_function = vd.raw_function # type: ignore + wrapper_function.model = vd.model # type: ignore + return wrapper_function + + if func: + return validate(func) + else: + return validate + + +ALT_V_ARGS = 'v__args' +ALT_V_KWARGS = 'v__kwargs' +V_POSITIONAL_ONLY_NAME = 'v__positional_only' +V_DUPLICATE_KWARGS = 'v__duplicate_kwargs' + + +class ValidatedFunction: + def __init__(self, function: 'AnyCallableT', config: 'ConfigType'): # noqa C901 + from inspect import Parameter, signature + + parameters: Mapping[str, Parameter] = signature(function).parameters + + if parameters.keys() & {ALT_V_ARGS, ALT_V_KWARGS, V_POSITIONAL_ONLY_NAME, V_DUPLICATE_KWARGS}: + raise ConfigError( + f'"{ALT_V_ARGS}", "{ALT_V_KWARGS}", "{V_POSITIONAL_ONLY_NAME}" and "{V_DUPLICATE_KWARGS}" ' + f'are not permitted as argument names when using the "{validate_arguments.__name__}" decorator' + ) + + self.raw_function = function + self.arg_mapping: Dict[int, str] = {} + self.positional_only_args = set() + self.v_args_name = 'args' + self.v_kwargs_name = 'kwargs' + + type_hints = get_all_type_hints(function) + takes_args = False + takes_kwargs = False + fields: Dict[str, Tuple[Any, Any]] = {} + for i, (name, p) in enumerate(parameters.items()): + if p.annotation is p.empty: + annotation = Any + else: + annotation = type_hints[name] + + default = ... if p.default is p.empty else p.default + if p.kind == Parameter.POSITIONAL_ONLY: + self.arg_mapping[i] = name + fields[name] = annotation, default + fields[V_POSITIONAL_ONLY_NAME] = List[str], None + self.positional_only_args.add(name) + elif p.kind == Parameter.POSITIONAL_OR_KEYWORD: + self.arg_mapping[i] = name + fields[name] = annotation, default + fields[V_DUPLICATE_KWARGS] = List[str], None + elif p.kind == Parameter.KEYWORD_ONLY: + fields[name] = annotation, default + elif p.kind == Parameter.VAR_POSITIONAL: + self.v_args_name = name + fields[name] = Tuple[annotation, ...], None + takes_args = True + else: + assert p.kind == Parameter.VAR_KEYWORD, p.kind + self.v_kwargs_name = name + fields[name] = Dict[str, annotation], None # type: ignore + takes_kwargs = True + + # these checks avoid a clash between "args" and a field with that name + if not takes_args and self.v_args_name in fields: + self.v_args_name = ALT_V_ARGS + + # same with "kwargs" + if not takes_kwargs and self.v_kwargs_name in fields: + self.v_kwargs_name = ALT_V_KWARGS + + if not takes_args: + # we add the field so validation below can raise the correct exception + fields[self.v_args_name] = List[Any], None + + if not takes_kwargs: + # same with kwargs + fields[self.v_kwargs_name] = Dict[Any, Any], None + + self.create_model(fields, takes_args, takes_kwargs, config) + + def init_model_instance(self, *args: Any, **kwargs: Any) -> BaseModel: + values = self.build_values(args, kwargs) + return self.model(**values) + + def call(self, *args: Any, **kwargs: Any) -> Any: + m = self.init_model_instance(*args, **kwargs) + return self.execute(m) + + def build_values(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> Dict[str, Any]: + values: Dict[str, Any] = {} + if args: + arg_iter = enumerate(args) + while True: + try: + i, a = next(arg_iter) + except StopIteration: + break + arg_name = self.arg_mapping.get(i) + if arg_name is not None: + values[arg_name] = a + else: + values[self.v_args_name] = [a] + [a for _, a in arg_iter] + break + + var_kwargs: Dict[str, Any] = {} + wrong_positional_args = [] + duplicate_kwargs = [] + fields_alias = [ + field.alias + for name, field in self.model.__fields__.items() + if name not in (self.v_args_name, self.v_kwargs_name) + ] + non_var_fields = set(self.model.__fields__) - {self.v_args_name, self.v_kwargs_name} + for k, v in kwargs.items(): + if k in non_var_fields or k in fields_alias: + if k in self.positional_only_args: + wrong_positional_args.append(k) + if k in values: + duplicate_kwargs.append(k) + values[k] = v + else: + var_kwargs[k] = v + + if var_kwargs: + values[self.v_kwargs_name] = var_kwargs + if wrong_positional_args: + values[V_POSITIONAL_ONLY_NAME] = wrong_positional_args + if duplicate_kwargs: + values[V_DUPLICATE_KWARGS] = duplicate_kwargs + return values + + def execute(self, m: BaseModel) -> Any: + d = {k: v for k, v in m._iter() if k in m.__fields_set__ or m.__fields__[k].default_factory} + var_kwargs = d.pop(self.v_kwargs_name, {}) + + if self.v_args_name in d: + args_: List[Any] = [] + in_kwargs = False + kwargs = {} + for name, value in d.items(): + if in_kwargs: + kwargs[name] = value + elif name == self.v_args_name: + args_ += value + in_kwargs = True + else: + args_.append(value) + return self.raw_function(*args_, **kwargs, **var_kwargs) + elif self.positional_only_args: + args_ = [] + kwargs = {} + for name, value in d.items(): + if name in self.positional_only_args: + args_.append(value) + else: + kwargs[name] = value + return self.raw_function(*args_, **kwargs, **var_kwargs) + else: + return self.raw_function(**d, **var_kwargs) + + def create_model(self, fields: Dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None: + pos_args = len(self.arg_mapping) + + class CustomConfig: + pass + + if not TYPE_CHECKING: # pragma: no branch + if isinstance(config, dict): + CustomConfig = type('Config', (), config) # noqa: F811 + elif config is not None: + CustomConfig = config # noqa: F811 + + if hasattr(CustomConfig, 'fields') or hasattr(CustomConfig, 'alias_generator'): + raise ConfigError( + 'Setting the "fields" and "alias_generator" property on custom Config for ' + '@validate_arguments is not yet supported, please remove.' + ) + + class DecoratorBaseModel(BaseModel): + @validator(self.v_args_name, check_fields=False, allow_reuse=True) + def check_args(cls, v: Optional[List[Any]]) -> Optional[List[Any]]: + if takes_args or v is None: + return v + + raise TypeError(f'{pos_args} positional arguments expected but {pos_args + len(v)} given') + + @validator(self.v_kwargs_name, check_fields=False, allow_reuse=True) + def check_kwargs(cls, v: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]: + if takes_kwargs or v is None: + return v + + plural = '' if len(v) == 1 else 's' + keys = ', '.join(map(repr, v.keys())) + raise TypeError(f'unexpected keyword argument{plural}: {keys}') + + @validator(V_POSITIONAL_ONLY_NAME, check_fields=False, allow_reuse=True) + def check_positional_only(cls, v: Optional[List[str]]) -> None: + if v is None: + return + + plural = '' if len(v) == 1 else 's' + keys = ', '.join(map(repr, v)) + raise TypeError(f'positional-only argument{plural} passed as keyword argument{plural}: {keys}') + + @validator(V_DUPLICATE_KWARGS, check_fields=False, allow_reuse=True) + def check_duplicate_kwargs(cls, v: Optional[List[str]]) -> None: + if v is None: + return + + plural = '' if len(v) == 1 else 's' + keys = ', '.join(map(repr, v)) + raise TypeError(f'multiple values for argument{plural}: {keys}') + + class Config(CustomConfig): + extra = getattr(CustomConfig, 'extra', Extra.forbid) + + self.model = create_model(to_camel(self.raw_function.__name__), __base__=DecoratorBaseModel, **fields) diff --git a/env/Lib/site-packages/pydantic/v1/env_settings.py b/env/Lib/site-packages/pydantic/v1/env_settings.py new file mode 100644 index 0000000..5f6f217 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/env_settings.py @@ -0,0 +1,350 @@ +import os +import warnings +from pathlib import Path +from typing import AbstractSet, Any, Callable, ClassVar, Dict, List, Mapping, Optional, Tuple, Type, Union + +from pydantic.v1.config import BaseConfig, Extra +from pydantic.v1.fields import ModelField +from pydantic.v1.main import BaseModel +from pydantic.v1.types import JsonWrapper +from pydantic.v1.typing import StrPath, display_as_type, get_origin, is_union +from pydantic.v1.utils import deep_update, lenient_issubclass, path_type, sequence_like + +env_file_sentinel = str(object()) + +SettingsSourceCallable = Callable[['BaseSettings'], Dict[str, Any]] +DotenvType = Union[StrPath, List[StrPath], Tuple[StrPath, ...]] + + +class SettingsError(ValueError): + pass + + +class BaseSettings(BaseModel): + """ + Base class for settings, allowing values to be overridden by environment variables. + + This is useful in production for secrets you do not wish to save in code, it plays nicely with docker(-compose), + Heroku and any 12 factor app design. + """ + + def __init__( + __pydantic_self__, + _env_file: Optional[DotenvType] = env_file_sentinel, + _env_file_encoding: Optional[str] = None, + _env_nested_delimiter: Optional[str] = None, + _secrets_dir: Optional[StrPath] = None, + **values: Any, + ) -> None: + # Uses something other than `self` the first arg to allow "self" as a settable attribute + super().__init__( + **__pydantic_self__._build_values( + values, + _env_file=_env_file, + _env_file_encoding=_env_file_encoding, + _env_nested_delimiter=_env_nested_delimiter, + _secrets_dir=_secrets_dir, + ) + ) + + def _build_values( + self, + init_kwargs: Dict[str, Any], + _env_file: Optional[DotenvType] = None, + _env_file_encoding: Optional[str] = None, + _env_nested_delimiter: Optional[str] = None, + _secrets_dir: Optional[StrPath] = None, + ) -> Dict[str, Any]: + # Configure built-in sources + init_settings = InitSettingsSource(init_kwargs=init_kwargs) + env_settings = EnvSettingsSource( + env_file=(_env_file if _env_file != env_file_sentinel else self.__config__.env_file), + env_file_encoding=( + _env_file_encoding if _env_file_encoding is not None else self.__config__.env_file_encoding + ), + env_nested_delimiter=( + _env_nested_delimiter if _env_nested_delimiter is not None else self.__config__.env_nested_delimiter + ), + env_prefix_len=len(self.__config__.env_prefix), + ) + file_secret_settings = SecretsSettingsSource(secrets_dir=_secrets_dir or self.__config__.secrets_dir) + # Provide a hook to set built-in sources priority and add / remove sources + sources = self.__config__.customise_sources( + init_settings=init_settings, env_settings=env_settings, file_secret_settings=file_secret_settings + ) + if sources: + return deep_update(*reversed([source(self) for source in sources])) + else: + # no one should mean to do this, but I think returning an empty dict is marginally preferable + # to an informative error and much better than a confusing error + return {} + + class Config(BaseConfig): + env_prefix: str = '' + env_file: Optional[DotenvType] = None + env_file_encoding: Optional[str] = None + env_nested_delimiter: Optional[str] = None + secrets_dir: Optional[StrPath] = None + validate_all: bool = True + extra: Extra = Extra.forbid + arbitrary_types_allowed: bool = True + case_sensitive: bool = False + + @classmethod + def prepare_field(cls, field: ModelField) -> None: + env_names: Union[List[str], AbstractSet[str]] + field_info_from_config = cls.get_field_info(field.name) + + env = field_info_from_config.get('env') or field.field_info.extra.get('env') + if env is None: + if field.has_alias: + warnings.warn( + 'aliases are no longer used by BaseSettings to define which environment variables to read. ' + 'Instead use the "env" field setting. ' + 'See https://pydantic-docs.helpmanual.io/usage/settings/#environment-variable-names', + FutureWarning, + ) + env_names = {cls.env_prefix + field.name} + elif isinstance(env, str): + env_names = {env} + elif isinstance(env, (set, frozenset)): + env_names = env + elif sequence_like(env): + env_names = list(env) + else: + raise TypeError(f'invalid field env: {env!r} ({display_as_type(env)}); should be string, list or set') + + if not cls.case_sensitive: + env_names = env_names.__class__(n.lower() for n in env_names) + field.field_info.extra['env_names'] = env_names + + @classmethod + def customise_sources( + cls, + init_settings: SettingsSourceCallable, + env_settings: SettingsSourceCallable, + file_secret_settings: SettingsSourceCallable, + ) -> Tuple[SettingsSourceCallable, ...]: + return init_settings, env_settings, file_secret_settings + + @classmethod + def parse_env_var(cls, field_name: str, raw_val: str) -> Any: + return cls.json_loads(raw_val) + + # populated by the metaclass using the Config class defined above, annotated here to help IDEs only + __config__: ClassVar[Type[Config]] + + +class InitSettingsSource: + __slots__ = ('init_kwargs',) + + def __init__(self, init_kwargs: Dict[str, Any]): + self.init_kwargs = init_kwargs + + def __call__(self, settings: BaseSettings) -> Dict[str, Any]: + return self.init_kwargs + + def __repr__(self) -> str: + return f'InitSettingsSource(init_kwargs={self.init_kwargs!r})' + + +class EnvSettingsSource: + __slots__ = ('env_file', 'env_file_encoding', 'env_nested_delimiter', 'env_prefix_len') + + def __init__( + self, + env_file: Optional[DotenvType], + env_file_encoding: Optional[str], + env_nested_delimiter: Optional[str] = None, + env_prefix_len: int = 0, + ): + self.env_file: Optional[DotenvType] = env_file + self.env_file_encoding: Optional[str] = env_file_encoding + self.env_nested_delimiter: Optional[str] = env_nested_delimiter + self.env_prefix_len: int = env_prefix_len + + def __call__(self, settings: BaseSettings) -> Dict[str, Any]: # noqa C901 + """ + Build environment variables suitable for passing to the Model. + """ + d: Dict[str, Any] = {} + + if settings.__config__.case_sensitive: + env_vars: Mapping[str, Optional[str]] = os.environ + else: + env_vars = {k.lower(): v for k, v in os.environ.items()} + + dotenv_vars = self._read_env_files(settings.__config__.case_sensitive) + if dotenv_vars: + env_vars = {**dotenv_vars, **env_vars} + + for field in settings.__fields__.values(): + env_val: Optional[str] = None + for env_name in field.field_info.extra['env_names']: + env_val = env_vars.get(env_name) + if env_val is not None: + break + + is_complex, allow_parse_failure = self.field_is_complex(field) + if is_complex: + if env_val is None: + # field is complex but no value found so far, try explode_env_vars + env_val_built = self.explode_env_vars(field, env_vars) + if env_val_built: + d[field.alias] = env_val_built + else: + # field is complex and there's a value, decode that as JSON, then add explode_env_vars + try: + env_val = settings.__config__.parse_env_var(field.name, env_val) + except ValueError as e: + if not allow_parse_failure: + raise SettingsError(f'error parsing env var "{env_name}"') from e + + if isinstance(env_val, dict): + d[field.alias] = deep_update(env_val, self.explode_env_vars(field, env_vars)) + else: + d[field.alias] = env_val + elif env_val is not None: + # simplest case, field is not complex, we only need to add the value if it was found + d[field.alias] = env_val + + return d + + def _read_env_files(self, case_sensitive: bool) -> Dict[str, Optional[str]]: + env_files = self.env_file + if env_files is None: + return {} + + if isinstance(env_files, (str, os.PathLike)): + env_files = [env_files] + + dotenv_vars = {} + for env_file in env_files: + env_path = Path(env_file).expanduser() + if env_path.is_file(): + dotenv_vars.update( + read_env_file(env_path, encoding=self.env_file_encoding, case_sensitive=case_sensitive) + ) + + return dotenv_vars + + def field_is_complex(self, field: ModelField) -> Tuple[bool, bool]: + """ + Find out if a field is complex, and if so whether JSON errors should be ignored + """ + if lenient_issubclass(field.annotation, JsonWrapper): + return False, False + + if field.is_complex(): + allow_parse_failure = False + elif is_union(get_origin(field.type_)) and field.sub_fields and any(f.is_complex() for f in field.sub_fields): + allow_parse_failure = True + else: + return False, False + + return True, allow_parse_failure + + def explode_env_vars(self, field: ModelField, env_vars: Mapping[str, Optional[str]]) -> Dict[str, Any]: + """ + Process env_vars and extract the values of keys containing env_nested_delimiter into nested dictionaries. + + This is applied to a single field, hence filtering by env_var prefix. + """ + prefixes = [f'{env_name}{self.env_nested_delimiter}' for env_name in field.field_info.extra['env_names']] + result: Dict[str, Any] = {} + for env_name, env_val in env_vars.items(): + if not any(env_name.startswith(prefix) for prefix in prefixes): + continue + # we remove the prefix before splitting in case the prefix has characters in common with the delimiter + env_name_without_prefix = env_name[self.env_prefix_len :] + _, *keys, last_key = env_name_without_prefix.split(self.env_nested_delimiter) + env_var = result + for key in keys: + env_var = env_var.setdefault(key, {}) + env_var[last_key] = env_val + + return result + + def __repr__(self) -> str: + return ( + f'EnvSettingsSource(env_file={self.env_file!r}, env_file_encoding={self.env_file_encoding!r}, ' + f'env_nested_delimiter={self.env_nested_delimiter!r})' + ) + + +class SecretsSettingsSource: + __slots__ = ('secrets_dir',) + + def __init__(self, secrets_dir: Optional[StrPath]): + self.secrets_dir: Optional[StrPath] = secrets_dir + + def __call__(self, settings: BaseSettings) -> Dict[str, Any]: + """ + Build fields from "secrets" files. + """ + secrets: Dict[str, Optional[str]] = {} + + if self.secrets_dir is None: + return secrets + + secrets_path = Path(self.secrets_dir).expanduser() + + if not secrets_path.exists(): + warnings.warn(f'directory "{secrets_path}" does not exist') + return secrets + + if not secrets_path.is_dir(): + raise SettingsError(f'secrets_dir must reference a directory, not a {path_type(secrets_path)}') + + for field in settings.__fields__.values(): + for env_name in field.field_info.extra['env_names']: + path = find_case_path(secrets_path, env_name, settings.__config__.case_sensitive) + if not path: + # path does not exist, we currently don't return a warning for this + continue + + if path.is_file(): + secret_value = path.read_text().strip() + if field.is_complex(): + try: + secret_value = settings.__config__.parse_env_var(field.name, secret_value) + except ValueError as e: + raise SettingsError(f'error parsing env var "{env_name}"') from e + + secrets[field.alias] = secret_value + else: + warnings.warn( + f'attempted to load secret file "{path}" but found a {path_type(path)} instead.', + stacklevel=4, + ) + return secrets + + def __repr__(self) -> str: + return f'SecretsSettingsSource(secrets_dir={self.secrets_dir!r})' + + +def read_env_file( + file_path: StrPath, *, encoding: str = None, case_sensitive: bool = False +) -> Dict[str, Optional[str]]: + try: + from dotenv import dotenv_values + except ImportError as e: + raise ImportError('python-dotenv is not installed, run `pip install pydantic[dotenv]`') from e + + file_vars: Dict[str, Optional[str]] = dotenv_values(file_path, encoding=encoding or 'utf8') + if not case_sensitive: + return {k.lower(): v for k, v in file_vars.items()} + else: + return file_vars + + +def find_case_path(dir_path: Path, file_name: str, case_sensitive: bool) -> Optional[Path]: + """ + Find a file within path's directory matching filename, optionally ignoring case. + """ + for f in dir_path.iterdir(): + if f.name == file_name: + return f + elif not case_sensitive and f.name.lower() == file_name.lower(): + return f + return None diff --git a/env/Lib/site-packages/pydantic/v1/error_wrappers.py b/env/Lib/site-packages/pydantic/v1/error_wrappers.py new file mode 100644 index 0000000..bc7f263 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/error_wrappers.py @@ -0,0 +1,161 @@ +import json +from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union + +from pydantic.v1.json import pydantic_encoder +from pydantic.v1.utils import Representation + +if TYPE_CHECKING: + from typing_extensions import TypedDict + + from pydantic.v1.config import BaseConfig + from pydantic.v1.types import ModelOrDc + from pydantic.v1.typing import ReprArgs + + Loc = Tuple[Union[int, str], ...] + + class _ErrorDictRequired(TypedDict): + loc: Loc + msg: str + type: str + + class ErrorDict(_ErrorDictRequired, total=False): + ctx: Dict[str, Any] + + +__all__ = 'ErrorWrapper', 'ValidationError' + + +class ErrorWrapper(Representation): + __slots__ = 'exc', '_loc' + + def __init__(self, exc: Exception, loc: Union[str, 'Loc']) -> None: + self.exc = exc + self._loc = loc + + def loc_tuple(self) -> 'Loc': + if isinstance(self._loc, tuple): + return self._loc + else: + return (self._loc,) + + def __repr_args__(self) -> 'ReprArgs': + return [('exc', self.exc), ('loc', self.loc_tuple())] + + +# ErrorList is something like Union[List[Union[List[ErrorWrapper], ErrorWrapper]], ErrorWrapper] +# but recursive, therefore just use: +ErrorList = Union[Sequence[Any], ErrorWrapper] + + +class ValidationError(Representation, ValueError): + __slots__ = 'raw_errors', 'model', '_error_cache' + + def __init__(self, errors: Sequence[ErrorList], model: 'ModelOrDc') -> None: + self.raw_errors = errors + self.model = model + self._error_cache: Optional[List['ErrorDict']] = None + + def errors(self) -> List['ErrorDict']: + if self._error_cache is None: + try: + config = self.model.__config__ # type: ignore + except AttributeError: + config = self.model.__pydantic_model__.__config__ # type: ignore + self._error_cache = list(flatten_errors(self.raw_errors, config)) + return self._error_cache + + def json(self, *, indent: Union[None, int, str] = 2) -> str: + return json.dumps(self.errors(), indent=indent, default=pydantic_encoder) + + def __str__(self) -> str: + errors = self.errors() + no_errors = len(errors) + return ( + f'{no_errors} validation error{"" if no_errors == 1 else "s"} for {self.model.__name__}\n' + f'{display_errors(errors)}' + ) + + def __repr_args__(self) -> 'ReprArgs': + return [('model', self.model.__name__), ('errors', self.errors())] + + +def display_errors(errors: List['ErrorDict']) -> str: + return '\n'.join(f'{_display_error_loc(e)}\n {e["msg"]} ({_display_error_type_and_ctx(e)})' for e in errors) + + +def _display_error_loc(error: 'ErrorDict') -> str: + return ' -> '.join(str(e) for e in error['loc']) + + +def _display_error_type_and_ctx(error: 'ErrorDict') -> str: + t = 'type=' + error['type'] + ctx = error.get('ctx') + if ctx: + return t + ''.join(f'; {k}={v}' for k, v in ctx.items()) + else: + return t + + +def flatten_errors( + errors: Sequence[Any], config: Type['BaseConfig'], loc: Optional['Loc'] = None +) -> Generator['ErrorDict', None, None]: + for error in errors: + if isinstance(error, ErrorWrapper): + if loc: + error_loc = loc + error.loc_tuple() + else: + error_loc = error.loc_tuple() + + if isinstance(error.exc, ValidationError): + yield from flatten_errors(error.exc.raw_errors, config, error_loc) + else: + yield error_dict(error.exc, config, error_loc) + elif isinstance(error, list): + yield from flatten_errors(error, config, loc=loc) + else: + raise RuntimeError(f'Unknown error object: {error}') + + +def error_dict(exc: Exception, config: Type['BaseConfig'], loc: 'Loc') -> 'ErrorDict': + type_ = get_exc_type(exc.__class__) + msg_template = config.error_msg_templates.get(type_) or getattr(exc, 'msg_template', None) + ctx = exc.__dict__ + if msg_template: + msg = msg_template.format(**ctx) + else: + msg = str(exc) + + d: 'ErrorDict' = {'loc': loc, 'msg': msg, 'type': type_} + + if ctx: + d['ctx'] = ctx + + return d + + +_EXC_TYPE_CACHE: Dict[Type[Exception], str] = {} + + +def get_exc_type(cls: Type[Exception]) -> str: + # slightly more efficient than using lru_cache since we don't need to worry about the cache filling up + try: + return _EXC_TYPE_CACHE[cls] + except KeyError: + r = _get_exc_type(cls) + _EXC_TYPE_CACHE[cls] = r + return r + + +def _get_exc_type(cls: Type[Exception]) -> str: + if issubclass(cls, AssertionError): + return 'assertion_error' + + base_name = 'type_error' if issubclass(cls, TypeError) else 'value_error' + if cls in (TypeError, ValueError): + # just TypeError or ValueError, no extra code + return base_name + + # if it's not a TypeError or ValueError, we just take the lowercase of the exception name + # no chaining or snake case logic, use "code" for more complex error types. + code = getattr(cls, 'code', None) or cls.__name__.replace('Error', '').lower() + return base_name + '.' + code diff --git a/env/Lib/site-packages/pydantic/v1/errors.py b/env/Lib/site-packages/pydantic/v1/errors.py new file mode 100644 index 0000000..6e86442 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/errors.py @@ -0,0 +1,646 @@ +from decimal import Decimal +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Sequence, Set, Tuple, Type, Union + +from pydantic.v1.typing import display_as_type + +if TYPE_CHECKING: + from pydantic.v1.typing import DictStrAny + +# explicitly state exports to avoid "from pydantic.v1.errors import *" also importing Decimal, Path etc. +__all__ = ( + 'PydanticTypeError', + 'PydanticValueError', + 'ConfigError', + 'MissingError', + 'ExtraError', + 'NoneIsNotAllowedError', + 'NoneIsAllowedError', + 'WrongConstantError', + 'NotNoneError', + 'BoolError', + 'BytesError', + 'DictError', + 'EmailError', + 'UrlError', + 'UrlSchemeError', + 'UrlSchemePermittedError', + 'UrlUserInfoError', + 'UrlHostError', + 'UrlHostTldError', + 'UrlPortError', + 'UrlExtraError', + 'EnumError', + 'IntEnumError', + 'EnumMemberError', + 'IntegerError', + 'FloatError', + 'PathError', + 'PathNotExistsError', + 'PathNotAFileError', + 'PathNotADirectoryError', + 'PyObjectError', + 'SequenceError', + 'ListError', + 'SetError', + 'FrozenSetError', + 'TupleError', + 'TupleLengthError', + 'ListMinLengthError', + 'ListMaxLengthError', + 'ListUniqueItemsError', + 'SetMinLengthError', + 'SetMaxLengthError', + 'FrozenSetMinLengthError', + 'FrozenSetMaxLengthError', + 'AnyStrMinLengthError', + 'AnyStrMaxLengthError', + 'StrError', + 'StrRegexError', + 'NumberNotGtError', + 'NumberNotGeError', + 'NumberNotLtError', + 'NumberNotLeError', + 'NumberNotMultipleError', + 'DecimalError', + 'DecimalIsNotFiniteError', + 'DecimalMaxDigitsError', + 'DecimalMaxPlacesError', + 'DecimalWholeDigitsError', + 'DateTimeError', + 'DateError', + 'DateNotInThePastError', + 'DateNotInTheFutureError', + 'TimeError', + 'DurationError', + 'HashableError', + 'UUIDError', + 'UUIDVersionError', + 'ArbitraryTypeError', + 'ClassError', + 'SubclassError', + 'JsonError', + 'JsonTypeError', + 'PatternError', + 'DataclassTypeError', + 'CallableError', + 'IPvAnyAddressError', + 'IPvAnyInterfaceError', + 'IPvAnyNetworkError', + 'IPv4AddressError', + 'IPv6AddressError', + 'IPv4NetworkError', + 'IPv6NetworkError', + 'IPv4InterfaceError', + 'IPv6InterfaceError', + 'ColorError', + 'StrictBoolError', + 'NotDigitError', + 'LuhnValidationError', + 'InvalidLengthForBrand', + 'InvalidByteSize', + 'InvalidByteSizeUnit', + 'MissingDiscriminator', + 'InvalidDiscriminator', +) + + +def cls_kwargs(cls: Type['PydanticErrorMixin'], ctx: 'DictStrAny') -> 'PydanticErrorMixin': + """ + For built-in exceptions like ValueError or TypeError, we need to implement + __reduce__ to override the default behaviour (instead of __getstate__/__setstate__) + By default pickle protocol 2 calls `cls.__new__(cls, *args)`. + Since we only use kwargs, we need a little constructor to change that. + Note: the callable can't be a lambda as pickle looks in the namespace to find it + """ + return cls(**ctx) + + +class PydanticErrorMixin: + code: str + msg_template: str + + def __init__(self, **ctx: Any) -> None: + self.__dict__ = ctx + + def __str__(self) -> str: + return self.msg_template.format(**self.__dict__) + + def __reduce__(self) -> Tuple[Callable[..., 'PydanticErrorMixin'], Tuple[Type['PydanticErrorMixin'], 'DictStrAny']]: + return cls_kwargs, (self.__class__, self.__dict__) + + +class PydanticTypeError(PydanticErrorMixin, TypeError): + pass + + +class PydanticValueError(PydanticErrorMixin, ValueError): + pass + + +class ConfigError(RuntimeError): + pass + + +class MissingError(PydanticValueError): + msg_template = 'field required' + + +class ExtraError(PydanticValueError): + msg_template = 'extra fields not permitted' + + +class NoneIsNotAllowedError(PydanticTypeError): + code = 'none.not_allowed' + msg_template = 'none is not an allowed value' + + +class NoneIsAllowedError(PydanticTypeError): + code = 'none.allowed' + msg_template = 'value is not none' + + +class WrongConstantError(PydanticValueError): + code = 'const' + + def __str__(self) -> str: + permitted = ', '.join(repr(v) for v in self.permitted) # type: ignore + return f'unexpected value; permitted: {permitted}' + + +class NotNoneError(PydanticTypeError): + code = 'not_none' + msg_template = 'value is not None' + + +class BoolError(PydanticTypeError): + msg_template = 'value could not be parsed to a boolean' + + +class BytesError(PydanticTypeError): + msg_template = 'byte type expected' + + +class DictError(PydanticTypeError): + msg_template = 'value is not a valid dict' + + +class EmailError(PydanticValueError): + msg_template = 'value is not a valid email address' + + +class UrlError(PydanticValueError): + code = 'url' + + +class UrlSchemeError(UrlError): + code = 'url.scheme' + msg_template = 'invalid or missing URL scheme' + + +class UrlSchemePermittedError(UrlError): + code = 'url.scheme' + msg_template = 'URL scheme not permitted' + + def __init__(self, allowed_schemes: Set[str]): + super().__init__(allowed_schemes=allowed_schemes) + + +class UrlUserInfoError(UrlError): + code = 'url.userinfo' + msg_template = 'userinfo required in URL but missing' + + +class UrlHostError(UrlError): + code = 'url.host' + msg_template = 'URL host invalid' + + +class UrlHostTldError(UrlError): + code = 'url.host' + msg_template = 'URL host invalid, top level domain required' + + +class UrlPortError(UrlError): + code = 'url.port' + msg_template = 'URL port invalid, port cannot exceed 65535' + + +class UrlExtraError(UrlError): + code = 'url.extra' + msg_template = 'URL invalid, extra characters found after valid URL: {extra!r}' + + +class EnumMemberError(PydanticTypeError): + code = 'enum' + + def __str__(self) -> str: + permitted = ', '.join(repr(v.value) for v in self.enum_values) # type: ignore + return f'value is not a valid enumeration member; permitted: {permitted}' + + +class IntegerError(PydanticTypeError): + msg_template = 'value is not a valid integer' + + +class FloatError(PydanticTypeError): + msg_template = 'value is not a valid float' + + +class PathError(PydanticTypeError): + msg_template = 'value is not a valid path' + + +class _PathValueError(PydanticValueError): + def __init__(self, *, path: Path) -> None: + super().__init__(path=str(path)) + + +class PathNotExistsError(_PathValueError): + code = 'path.not_exists' + msg_template = 'file or directory at path "{path}" does not exist' + + +class PathNotAFileError(_PathValueError): + code = 'path.not_a_file' + msg_template = 'path "{path}" does not point to a file' + + +class PathNotADirectoryError(_PathValueError): + code = 'path.not_a_directory' + msg_template = 'path "{path}" does not point to a directory' + + +class PyObjectError(PydanticTypeError): + msg_template = 'ensure this value contains valid import path or valid callable: {error_message}' + + +class SequenceError(PydanticTypeError): + msg_template = 'value is not a valid sequence' + + +class IterableError(PydanticTypeError): + msg_template = 'value is not a valid iterable' + + +class ListError(PydanticTypeError): + msg_template = 'value is not a valid list' + + +class SetError(PydanticTypeError): + msg_template = 'value is not a valid set' + + +class FrozenSetError(PydanticTypeError): + msg_template = 'value is not a valid frozenset' + + +class DequeError(PydanticTypeError): + msg_template = 'value is not a valid deque' + + +class TupleError(PydanticTypeError): + msg_template = 'value is not a valid tuple' + + +class TupleLengthError(PydanticValueError): + code = 'tuple.length' + msg_template = 'wrong tuple length {actual_length}, expected {expected_length}' + + def __init__(self, *, actual_length: int, expected_length: int) -> None: + super().__init__(actual_length=actual_length, expected_length=expected_length) + + +class ListMinLengthError(PydanticValueError): + code = 'list.min_items' + msg_template = 'ensure this value has at least {limit_value} items' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class ListMaxLengthError(PydanticValueError): + code = 'list.max_items' + msg_template = 'ensure this value has at most {limit_value} items' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class ListUniqueItemsError(PydanticValueError): + code = 'list.unique_items' + msg_template = 'the list has duplicated items' + + +class SetMinLengthError(PydanticValueError): + code = 'set.min_items' + msg_template = 'ensure this value has at least {limit_value} items' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class SetMaxLengthError(PydanticValueError): + code = 'set.max_items' + msg_template = 'ensure this value has at most {limit_value} items' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class FrozenSetMinLengthError(PydanticValueError): + code = 'frozenset.min_items' + msg_template = 'ensure this value has at least {limit_value} items' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class FrozenSetMaxLengthError(PydanticValueError): + code = 'frozenset.max_items' + msg_template = 'ensure this value has at most {limit_value} items' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class AnyStrMinLengthError(PydanticValueError): + code = 'any_str.min_length' + msg_template = 'ensure this value has at least {limit_value} characters' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class AnyStrMaxLengthError(PydanticValueError): + code = 'any_str.max_length' + msg_template = 'ensure this value has at most {limit_value} characters' + + def __init__(self, *, limit_value: int) -> None: + super().__init__(limit_value=limit_value) + + +class StrError(PydanticTypeError): + msg_template = 'str type expected' + + +class StrRegexError(PydanticValueError): + code = 'str.regex' + msg_template = 'string does not match regex "{pattern}"' + + def __init__(self, *, pattern: str) -> None: + super().__init__(pattern=pattern) + + +class _NumberBoundError(PydanticValueError): + def __init__(self, *, limit_value: Union[int, float, Decimal]) -> None: + super().__init__(limit_value=limit_value) + + +class NumberNotGtError(_NumberBoundError): + code = 'number.not_gt' + msg_template = 'ensure this value is greater than {limit_value}' + + +class NumberNotGeError(_NumberBoundError): + code = 'number.not_ge' + msg_template = 'ensure this value is greater than or equal to {limit_value}' + + +class NumberNotLtError(_NumberBoundError): + code = 'number.not_lt' + msg_template = 'ensure this value is less than {limit_value}' + + +class NumberNotLeError(_NumberBoundError): + code = 'number.not_le' + msg_template = 'ensure this value is less than or equal to {limit_value}' + + +class NumberNotFiniteError(PydanticValueError): + code = 'number.not_finite_number' + msg_template = 'ensure this value is a finite number' + + +class NumberNotMultipleError(PydanticValueError): + code = 'number.not_multiple' + msg_template = 'ensure this value is a multiple of {multiple_of}' + + def __init__(self, *, multiple_of: Union[int, float, Decimal]) -> None: + super().__init__(multiple_of=multiple_of) + + +class DecimalError(PydanticTypeError): + msg_template = 'value is not a valid decimal' + + +class DecimalIsNotFiniteError(PydanticValueError): + code = 'decimal.not_finite' + msg_template = 'value is not a valid decimal' + + +class DecimalMaxDigitsError(PydanticValueError): + code = 'decimal.max_digits' + msg_template = 'ensure that there are no more than {max_digits} digits in total' + + def __init__(self, *, max_digits: int) -> None: + super().__init__(max_digits=max_digits) + + +class DecimalMaxPlacesError(PydanticValueError): + code = 'decimal.max_places' + msg_template = 'ensure that there are no more than {decimal_places} decimal places' + + def __init__(self, *, decimal_places: int) -> None: + super().__init__(decimal_places=decimal_places) + + +class DecimalWholeDigitsError(PydanticValueError): + code = 'decimal.whole_digits' + msg_template = 'ensure that there are no more than {whole_digits} digits before the decimal point' + + def __init__(self, *, whole_digits: int) -> None: + super().__init__(whole_digits=whole_digits) + + +class DateTimeError(PydanticValueError): + msg_template = 'invalid datetime format' + + +class DateError(PydanticValueError): + msg_template = 'invalid date format' + + +class DateNotInThePastError(PydanticValueError): + code = 'date.not_in_the_past' + msg_template = 'date is not in the past' + + +class DateNotInTheFutureError(PydanticValueError): + code = 'date.not_in_the_future' + msg_template = 'date is not in the future' + + +class TimeError(PydanticValueError): + msg_template = 'invalid time format' + + +class DurationError(PydanticValueError): + msg_template = 'invalid duration format' + + +class HashableError(PydanticTypeError): + msg_template = 'value is not a valid hashable' + + +class UUIDError(PydanticTypeError): + msg_template = 'value is not a valid uuid' + + +class UUIDVersionError(PydanticValueError): + code = 'uuid.version' + msg_template = 'uuid version {required_version} expected' + + def __init__(self, *, required_version: int) -> None: + super().__init__(required_version=required_version) + + +class ArbitraryTypeError(PydanticTypeError): + code = 'arbitrary_type' + msg_template = 'instance of {expected_arbitrary_type} expected' + + def __init__(self, *, expected_arbitrary_type: Type[Any]) -> None: + super().__init__(expected_arbitrary_type=display_as_type(expected_arbitrary_type)) + + +class ClassError(PydanticTypeError): + code = 'class' + msg_template = 'a class is expected' + + +class SubclassError(PydanticTypeError): + code = 'subclass' + msg_template = 'subclass of {expected_class} expected' + + def __init__(self, *, expected_class: Type[Any]) -> None: + super().__init__(expected_class=display_as_type(expected_class)) + + +class JsonError(PydanticValueError): + msg_template = 'Invalid JSON' + + +class JsonTypeError(PydanticTypeError): + code = 'json' + msg_template = 'JSON object must be str, bytes or bytearray' + + +class PatternError(PydanticValueError): + code = 'regex_pattern' + msg_template = 'Invalid regular expression' + + +class DataclassTypeError(PydanticTypeError): + code = 'dataclass' + msg_template = 'instance of {class_name}, tuple or dict expected' + + +class CallableError(PydanticTypeError): + msg_template = '{value} is not callable' + + +class EnumError(PydanticTypeError): + code = 'enum_instance' + msg_template = '{value} is not a valid Enum instance' + + +class IntEnumError(PydanticTypeError): + code = 'int_enum_instance' + msg_template = '{value} is not a valid IntEnum instance' + + +class IPvAnyAddressError(PydanticValueError): + msg_template = 'value is not a valid IPv4 or IPv6 address' + + +class IPvAnyInterfaceError(PydanticValueError): + msg_template = 'value is not a valid IPv4 or IPv6 interface' + + +class IPvAnyNetworkError(PydanticValueError): + msg_template = 'value is not a valid IPv4 or IPv6 network' + + +class IPv4AddressError(PydanticValueError): + msg_template = 'value is not a valid IPv4 address' + + +class IPv6AddressError(PydanticValueError): + msg_template = 'value is not a valid IPv6 address' + + +class IPv4NetworkError(PydanticValueError): + msg_template = 'value is not a valid IPv4 network' + + +class IPv6NetworkError(PydanticValueError): + msg_template = 'value is not a valid IPv6 network' + + +class IPv4InterfaceError(PydanticValueError): + msg_template = 'value is not a valid IPv4 interface' + + +class IPv6InterfaceError(PydanticValueError): + msg_template = 'value is not a valid IPv6 interface' + + +class ColorError(PydanticValueError): + msg_template = 'value is not a valid color: {reason}' + + +class StrictBoolError(PydanticValueError): + msg_template = 'value is not a valid boolean' + + +class NotDigitError(PydanticValueError): + code = 'payment_card_number.digits' + msg_template = 'card number is not all digits' + + +class LuhnValidationError(PydanticValueError): + code = 'payment_card_number.luhn_check' + msg_template = 'card number is not luhn valid' + + +class InvalidLengthForBrand(PydanticValueError): + code = 'payment_card_number.invalid_length_for_brand' + msg_template = 'Length for a {brand} card must be {required_length}' + + +class InvalidByteSize(PydanticValueError): + msg_template = 'could not parse value and unit from byte string' + + +class InvalidByteSizeUnit(PydanticValueError): + msg_template = 'could not interpret byte unit: {unit}' + + +class MissingDiscriminator(PydanticValueError): + code = 'discriminated_union.missing_discriminator' + msg_template = 'Discriminator {discriminator_key!r} is missing in value' + + +class InvalidDiscriminator(PydanticValueError): + code = 'discriminated_union.invalid_discriminator' + msg_template = ( + 'No match for discriminator {discriminator_key!r} and value {discriminator_value!r} ' + '(allowed values: {allowed_values})' + ) + + def __init__(self, *, discriminator_key: str, discriminator_value: Any, allowed_values: Sequence[Any]) -> None: + super().__init__( + discriminator_key=discriminator_key, + discriminator_value=discriminator_value, + allowed_values=', '.join(map(repr, allowed_values)), + ) diff --git a/env/Lib/site-packages/pydantic/v1/fields.py b/env/Lib/site-packages/pydantic/v1/fields.py new file mode 100644 index 0000000..002b60c --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/fields.py @@ -0,0 +1,1253 @@ +import copy +import re +from collections import Counter as CollectionCounter, defaultdict, deque +from collections.abc import Callable, Hashable as CollectionsHashable, Iterable as CollectionsIterable +from typing import ( + TYPE_CHECKING, + Any, + Counter, + DefaultDict, + Deque, + Dict, + ForwardRef, + FrozenSet, + Generator, + Iterable, + Iterator, + List, + Mapping, + Optional, + Pattern, + Sequence, + Set, + Tuple, + Type, + TypeVar, + Union, +) + +from typing_extensions import Annotated, Final + +from pydantic.v1 import errors as errors_ +from pydantic.v1.class_validators import Validator, make_generic_validator, prep_validators +from pydantic.v1.error_wrappers import ErrorWrapper +from pydantic.v1.errors import ConfigError, InvalidDiscriminator, MissingDiscriminator, NoneIsNotAllowedError +from pydantic.v1.types import Json, JsonWrapper +from pydantic.v1.typing import ( + NoArgAnyCallable, + convert_generics, + display_as_type, + get_args, + get_origin, + is_finalvar, + is_literal_type, + is_new_type, + is_none_type, + is_typeddict, + is_typeddict_special, + is_union, + new_type_supertype, +) +from pydantic.v1.utils import ( + PyObjectStr, + Representation, + ValueItems, + get_discriminator_alias_and_values, + get_unique_discriminator_alias, + lenient_isinstance, + lenient_issubclass, + sequence_like, + smart_deepcopy, +) +from pydantic.v1.validators import constant_validator, dict_validator, find_validators, validate_json + +Required: Any = Ellipsis + +T = TypeVar('T') + + +class UndefinedType: + def __repr__(self) -> str: + return 'PydanticUndefined' + + def __copy__(self: T) -> T: + return self + + def __reduce__(self) -> str: + return 'Undefined' + + def __deepcopy__(self: T, _: Any) -> T: + return self + + +Undefined = UndefinedType() + +if TYPE_CHECKING: + from pydantic.v1.class_validators import ValidatorsList + from pydantic.v1.config import BaseConfig + from pydantic.v1.error_wrappers import ErrorList + from pydantic.v1.types import ModelOrDc + from pydantic.v1.typing import AbstractSetIntStr, MappingIntStrAny, ReprArgs + + ValidateReturn = Tuple[Optional[Any], Optional[ErrorList]] + LocStr = Union[Tuple[Union[int, str], ...], str] + BoolUndefined = Union[bool, UndefinedType] + + +class FieldInfo(Representation): + """ + Captures extra information about a field. + """ + + __slots__ = ( + 'default', + 'default_factory', + 'alias', + 'alias_priority', + 'title', + 'description', + 'exclude', + 'include', + 'const', + 'gt', + 'ge', + 'lt', + 'le', + 'multiple_of', + 'allow_inf_nan', + 'max_digits', + 'decimal_places', + 'min_items', + 'max_items', + 'unique_items', + 'min_length', + 'max_length', + 'allow_mutation', + 'repr', + 'regex', + 'discriminator', + 'extra', + ) + + # field constraints with the default value, it's also used in update_from_config below + __field_constraints__ = { + 'min_length': None, + 'max_length': None, + 'regex': None, + 'gt': None, + 'lt': None, + 'ge': None, + 'le': None, + 'multiple_of': None, + 'allow_inf_nan': None, + 'max_digits': None, + 'decimal_places': None, + 'min_items': None, + 'max_items': None, + 'unique_items': None, + 'allow_mutation': True, + } + + def __init__(self, default: Any = Undefined, **kwargs: Any) -> None: + self.default = default + self.default_factory = kwargs.pop('default_factory', None) + self.alias = kwargs.pop('alias', None) + self.alias_priority = kwargs.pop('alias_priority', 2 if self.alias is not None else None) + self.title = kwargs.pop('title', None) + self.description = kwargs.pop('description', None) + self.exclude = kwargs.pop('exclude', None) + self.include = kwargs.pop('include', None) + self.const = kwargs.pop('const', None) + self.gt = kwargs.pop('gt', None) + self.ge = kwargs.pop('ge', None) + self.lt = kwargs.pop('lt', None) + self.le = kwargs.pop('le', None) + self.multiple_of = kwargs.pop('multiple_of', None) + self.allow_inf_nan = kwargs.pop('allow_inf_nan', None) + self.max_digits = kwargs.pop('max_digits', None) + self.decimal_places = kwargs.pop('decimal_places', None) + self.min_items = kwargs.pop('min_items', None) + self.max_items = kwargs.pop('max_items', None) + self.unique_items = kwargs.pop('unique_items', None) + self.min_length = kwargs.pop('min_length', None) + self.max_length = kwargs.pop('max_length', None) + self.allow_mutation = kwargs.pop('allow_mutation', True) + self.regex = kwargs.pop('regex', None) + self.discriminator = kwargs.pop('discriminator', None) + self.repr = kwargs.pop('repr', True) + self.extra = kwargs + + def __repr_args__(self) -> 'ReprArgs': + field_defaults_to_hide: Dict[str, Any] = { + 'repr': True, + **self.__field_constraints__, + } + + attrs = ((s, getattr(self, s)) for s in self.__slots__) + return [(a, v) for a, v in attrs if v != field_defaults_to_hide.get(a, None)] + + def get_constraints(self) -> Set[str]: + """ + Gets the constraints set on the field by comparing the constraint value with its default value + + :return: the constraints set on field_info + """ + return {attr for attr, default in self.__field_constraints__.items() if getattr(self, attr) != default} + + def update_from_config(self, from_config: Dict[str, Any]) -> None: + """ + Update this FieldInfo based on a dict from get_field_info, only fields which have not been set are dated. + """ + for attr_name, value in from_config.items(): + try: + current_value = getattr(self, attr_name) + except AttributeError: + # attr_name is not an attribute of FieldInfo, it should therefore be added to extra + # (except if extra already has this value!) + self.extra.setdefault(attr_name, value) + else: + if current_value is self.__field_constraints__.get(attr_name, None): + setattr(self, attr_name, value) + elif attr_name == 'exclude': + self.exclude = ValueItems.merge(value, current_value) + elif attr_name == 'include': + self.include = ValueItems.merge(value, current_value, intersect=True) + + def _validate(self) -> None: + if self.default is not Undefined and self.default_factory is not None: + raise ValueError('cannot specify both default and default_factory') + + +def Field( + default: Any = Undefined, + *, + default_factory: Optional[NoArgAnyCallable] = None, + alias: Optional[str] = None, + title: Optional[str] = None, + description: Optional[str] = None, + exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny', Any]] = None, + include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny', Any]] = None, + const: Optional[bool] = None, + gt: Optional[float] = None, + ge: Optional[float] = None, + lt: Optional[float] = None, + le: Optional[float] = None, + multiple_of: Optional[float] = None, + allow_inf_nan: Optional[bool] = None, + max_digits: Optional[int] = None, + decimal_places: Optional[int] = None, + min_items: Optional[int] = None, + max_items: Optional[int] = None, + unique_items: Optional[bool] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + allow_mutation: bool = True, + regex: Optional[str] = None, + discriminator: Optional[str] = None, + repr: bool = True, + **extra: Any, +) -> Any: + """ + Used to provide extra information about a field, either for the model schema or complex validation. Some arguments + apply only to number fields (``int``, ``float``, ``Decimal``) and some apply only to ``str``. + + :param default: since this is replacing the field’s default, its first argument is used + to set the default, use ellipsis (``...``) to indicate the field is required + :param default_factory: callable that will be called when a default value is needed for this field + If both `default` and `default_factory` are set, an error is raised. + :param alias: the public name of the field + :param title: can be any string, used in the schema + :param description: can be any string, used in the schema + :param exclude: exclude this field while dumping. + Takes same values as the ``include`` and ``exclude`` arguments on the ``.dict`` method. + :param include: include this field while dumping. + Takes same values as the ``include`` and ``exclude`` arguments on the ``.dict`` method. + :param const: this field is required and *must* take it's default value + :param gt: only applies to numbers, requires the field to be "greater than". The schema + will have an ``exclusiveMinimum`` validation keyword + :param ge: only applies to numbers, requires the field to be "greater than or equal to". The + schema will have a ``minimum`` validation keyword + :param lt: only applies to numbers, requires the field to be "less than". The schema + will have an ``exclusiveMaximum`` validation keyword + :param le: only applies to numbers, requires the field to be "less than or equal to". The + schema will have a ``maximum`` validation keyword + :param multiple_of: only applies to numbers, requires the field to be "a multiple of". The + schema will have a ``multipleOf`` validation keyword + :param allow_inf_nan: only applies to numbers, allows the field to be NaN or infinity (+inf or -inf), + which is a valid Python float. Default True, set to False for compatibility with JSON. + :param max_digits: only applies to Decimals, requires the field to have a maximum number + of digits within the decimal. It does not include a zero before the decimal point or trailing decimal zeroes. + :param decimal_places: only applies to Decimals, requires the field to have at most a number of decimal places + allowed. It does not include trailing decimal zeroes. + :param min_items: only applies to lists, requires the field to have a minimum number of + elements. The schema will have a ``minItems`` validation keyword + :param max_items: only applies to lists, requires the field to have a maximum number of + elements. The schema will have a ``maxItems`` validation keyword + :param unique_items: only applies to lists, requires the field not to have duplicated + elements. The schema will have a ``uniqueItems`` validation keyword + :param min_length: only applies to strings, requires the field to have a minimum length. The + schema will have a ``minLength`` validation keyword + :param max_length: only applies to strings, requires the field to have a maximum length. The + schema will have a ``maxLength`` validation keyword + :param allow_mutation: a boolean which defaults to True. When False, the field raises a TypeError if the field is + assigned on an instance. The BaseModel Config must set validate_assignment to True + :param regex: only applies to strings, requires the field match against a regular expression + pattern string. The schema will have a ``pattern`` validation keyword + :param discriminator: only useful with a (discriminated a.k.a. tagged) `Union` of sub models with a common field. + The `discriminator` is the name of this common field to shorten validation and improve generated schema + :param repr: show this field in the representation + :param **extra: any additional keyword arguments will be added as is to the schema + """ + field_info = FieldInfo( + default, + default_factory=default_factory, + alias=alias, + title=title, + description=description, + exclude=exclude, + include=include, + const=const, + gt=gt, + ge=ge, + lt=lt, + le=le, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + max_digits=max_digits, + decimal_places=decimal_places, + min_items=min_items, + max_items=max_items, + unique_items=unique_items, + min_length=min_length, + max_length=max_length, + allow_mutation=allow_mutation, + regex=regex, + discriminator=discriminator, + repr=repr, + **extra, + ) + field_info._validate() + return field_info + + +# used to be an enum but changed to int's for small performance improvement as less access overhead +SHAPE_SINGLETON = 1 +SHAPE_LIST = 2 +SHAPE_SET = 3 +SHAPE_MAPPING = 4 +SHAPE_TUPLE = 5 +SHAPE_TUPLE_ELLIPSIS = 6 +SHAPE_SEQUENCE = 7 +SHAPE_FROZENSET = 8 +SHAPE_ITERABLE = 9 +SHAPE_GENERIC = 10 +SHAPE_DEQUE = 11 +SHAPE_DICT = 12 +SHAPE_DEFAULTDICT = 13 +SHAPE_COUNTER = 14 +SHAPE_NAME_LOOKUP = { + SHAPE_LIST: 'List[{}]', + SHAPE_SET: 'Set[{}]', + SHAPE_TUPLE_ELLIPSIS: 'Tuple[{}, ...]', + SHAPE_SEQUENCE: 'Sequence[{}]', + SHAPE_FROZENSET: 'FrozenSet[{}]', + SHAPE_ITERABLE: 'Iterable[{}]', + SHAPE_DEQUE: 'Deque[{}]', + SHAPE_DICT: 'Dict[{}]', + SHAPE_DEFAULTDICT: 'DefaultDict[{}]', + SHAPE_COUNTER: 'Counter[{}]', +} + +MAPPING_LIKE_SHAPES: Set[int] = {SHAPE_DEFAULTDICT, SHAPE_DICT, SHAPE_MAPPING, SHAPE_COUNTER} + + +class ModelField(Representation): + __slots__ = ( + 'type_', + 'outer_type_', + 'annotation', + 'sub_fields', + 'sub_fields_mapping', + 'key_field', + 'validators', + 'pre_validators', + 'post_validators', + 'default', + 'default_factory', + 'required', + 'final', + 'model_config', + 'name', + 'alias', + 'has_alias', + 'field_info', + 'discriminator_key', + 'discriminator_alias', + 'validate_always', + 'allow_none', + 'shape', + 'class_validators', + 'parse_json', + ) + + def __init__( + self, + *, + name: str, + type_: Type[Any], + class_validators: Optional[Dict[str, Validator]], + model_config: Type['BaseConfig'], + default: Any = None, + default_factory: Optional[NoArgAnyCallable] = None, + required: 'BoolUndefined' = Undefined, + final: bool = False, + alias: Optional[str] = None, + field_info: Optional[FieldInfo] = None, + ) -> None: + self.name: str = name + self.has_alias: bool = alias is not None + self.alias: str = alias if alias is not None else name + self.annotation = type_ + self.type_: Any = convert_generics(type_) + self.outer_type_: Any = type_ + self.class_validators = class_validators or {} + self.default: Any = default + self.default_factory: Optional[NoArgAnyCallable] = default_factory + self.required: 'BoolUndefined' = required + self.final: bool = final + self.model_config = model_config + self.field_info: FieldInfo = field_info or FieldInfo(default) + self.discriminator_key: Optional[str] = self.field_info.discriminator + self.discriminator_alias: Optional[str] = self.discriminator_key + + self.allow_none: bool = False + self.validate_always: bool = False + self.sub_fields: Optional[List[ModelField]] = None + self.sub_fields_mapping: Optional[Dict[str, 'ModelField']] = None # used for discriminated union + self.key_field: Optional[ModelField] = None + self.validators: 'ValidatorsList' = [] + self.pre_validators: Optional['ValidatorsList'] = None + self.post_validators: Optional['ValidatorsList'] = None + self.parse_json: bool = False + self.shape: int = SHAPE_SINGLETON + self.model_config.prepare_field(self) + self.prepare() + + def get_default(self) -> Any: + return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() + + @staticmethod + def _get_field_info( + field_name: str, annotation: Any, value: Any, config: Type['BaseConfig'] + ) -> Tuple[FieldInfo, Any]: + """ + Get a FieldInfo from a root typing.Annotated annotation, value, or config default. + + The FieldInfo may be set in typing.Annotated or the value, but not both. If neither contain + a FieldInfo, a new one will be created using the config. + + :param field_name: name of the field for use in error messages + :param annotation: a type hint such as `str` or `Annotated[str, Field(..., min_length=5)]` + :param value: the field's assigned value + :param config: the model's config object + :return: the FieldInfo contained in the `annotation`, the value, or a new one from the config. + """ + field_info_from_config = config.get_field_info(field_name) + + field_info = None + if get_origin(annotation) is Annotated: + field_infos = [arg for arg in get_args(annotation)[1:] if isinstance(arg, FieldInfo)] + if len(field_infos) > 1: + raise ValueError(f'cannot specify multiple `Annotated` `Field`s for {field_name!r}') + field_info = next(iter(field_infos), None) + if field_info is not None: + field_info = copy.copy(field_info) + field_info.update_from_config(field_info_from_config) + if field_info.default not in (Undefined, Required): + raise ValueError(f'`Field` default cannot be set in `Annotated` for {field_name!r}') + if value is not Undefined and value is not Required: + # check also `Required` because of `validate_arguments` that sets `...` as default value + field_info.default = value + + if isinstance(value, FieldInfo): + if field_info is not None: + raise ValueError(f'cannot specify `Annotated` and value `Field`s together for {field_name!r}') + field_info = value + field_info.update_from_config(field_info_from_config) + elif field_info is None: + field_info = FieldInfo(value, **field_info_from_config) + value = None if field_info.default_factory is not None else field_info.default + field_info._validate() + return field_info, value + + @classmethod + def infer( + cls, + *, + name: str, + value: Any, + annotation: Any, + class_validators: Optional[Dict[str, Validator]], + config: Type['BaseConfig'], + ) -> 'ModelField': + from pydantic.v1.schema import get_annotation_from_field_info + + field_info, value = cls._get_field_info(name, annotation, value, config) + required: 'BoolUndefined' = Undefined + if value is Required: + required = True + value = None + elif value is not Undefined: + required = False + annotation = get_annotation_from_field_info(annotation, field_info, name, config.validate_assignment) + + return cls( + name=name, + type_=annotation, + alias=field_info.alias, + class_validators=class_validators, + default=value, + default_factory=field_info.default_factory, + required=required, + model_config=config, + field_info=field_info, + ) + + def set_config(self, config: Type['BaseConfig']) -> None: + self.model_config = config + info_from_config = config.get_field_info(self.name) + config.prepare_field(self) + new_alias = info_from_config.get('alias') + new_alias_priority = info_from_config.get('alias_priority') or 0 + if new_alias and new_alias_priority >= (self.field_info.alias_priority or 0): + self.field_info.alias = new_alias + self.field_info.alias_priority = new_alias_priority + self.alias = new_alias + new_exclude = info_from_config.get('exclude') + if new_exclude is not None: + self.field_info.exclude = ValueItems.merge(self.field_info.exclude, new_exclude) + new_include = info_from_config.get('include') + if new_include is not None: + self.field_info.include = ValueItems.merge(self.field_info.include, new_include, intersect=True) + + @property + def alt_alias(self) -> bool: + return self.name != self.alias + + def prepare(self) -> None: + """ + Prepare the field but inspecting self.default, self.type_ etc. + + Note: this method is **not** idempotent (because _type_analysis is not idempotent), + e.g. calling it it multiple times may modify the field and configure it incorrectly. + """ + self._set_default_and_type() + if self.type_.__class__ is ForwardRef or self.type_.__class__ is DeferredType: + # self.type_ is currently a ForwardRef and there's nothing we can do now, + # user will need to call model.update_forward_refs() + return + + self._type_analysis() + if self.required is Undefined: + self.required = True + if self.default is Undefined and self.default_factory is None: + self.default = None + self.populate_validators() + + def _set_default_and_type(self) -> None: + """ + Set the default value, infer the type if needed and check if `None` value is valid. + """ + if self.default_factory is not None: + if self.type_ is Undefined: + raise errors_.ConfigError( + f'you need to set the type of field {self.name!r} when using `default_factory`' + ) + return + + default_value = self.get_default() + + if default_value is not None and self.type_ is Undefined: + self.type_ = default_value.__class__ + self.outer_type_ = self.type_ + self.annotation = self.type_ + + if self.type_ is Undefined: + raise errors_.ConfigError(f'unable to infer type for attribute "{self.name}"') + + if self.required is False and default_value is None: + self.allow_none = True + + def _type_analysis(self) -> None: # noqa: C901 (ignore complexity) + # typing interface is horrible, we have to do some ugly checks + if lenient_issubclass(self.type_, JsonWrapper): + self.type_ = self.type_.inner_type + self.parse_json = True + elif lenient_issubclass(self.type_, Json): + self.type_ = Any + self.parse_json = True + elif isinstance(self.type_, TypeVar): + if self.type_.__bound__: + self.type_ = self.type_.__bound__ + elif self.type_.__constraints__: + self.type_ = Union[self.type_.__constraints__] + else: + self.type_ = Any + elif is_new_type(self.type_): + self.type_ = new_type_supertype(self.type_) + + if self.type_ is Any or self.type_ is object: + if self.required is Undefined: + self.required = False + self.allow_none = True + return + elif self.type_ is Pattern or self.type_ is re.Pattern: + # python 3.7 only, Pattern is a typing object but without sub fields + return + elif is_literal_type(self.type_): + return + elif is_typeddict(self.type_): + return + + if is_finalvar(self.type_): + self.final = True + + if self.type_ is Final: + self.type_ = Any + else: + self.type_ = get_args(self.type_)[0] + + self._type_analysis() + return + + origin = get_origin(self.type_) + + if origin is Annotated or is_typeddict_special(origin): + self.type_ = get_args(self.type_)[0] + self._type_analysis() + return + + if self.discriminator_key is not None and not is_union(origin): + raise TypeError('`discriminator` can only be used with `Union` type with more than one variant') + + # add extra check for `collections.abc.Hashable` for python 3.10+ where origin is not `None` + if origin is None or origin is CollectionsHashable: + # field is not "typing" object eg. Union, Dict, List etc. + # allow None for virtual superclasses of NoneType, e.g. Hashable + if isinstance(self.type_, type) and isinstance(None, self.type_): + self.allow_none = True + return + elif origin is Callable: + return + elif is_union(origin): + types_ = [] + for type_ in get_args(self.type_): + if is_none_type(type_) or type_ is Any or type_ is object: + if self.required is Undefined: + self.required = False + self.allow_none = True + if is_none_type(type_): + continue + types_.append(type_) + + if len(types_) == 1: + # Optional[] + self.type_ = types_[0] + # this is the one case where the "outer type" isn't just the original type + self.outer_type_ = self.type_ + # re-run to correctly interpret the new self.type_ + self._type_analysis() + else: + self.sub_fields = [self._create_sub_type(t, f'{self.name}_{display_as_type(t)}') for t in types_] + + if self.discriminator_key is not None: + self.prepare_discriminated_union_sub_fields() + return + elif issubclass(origin, Tuple): # type: ignore + # origin == Tuple without item type + args = get_args(self.type_) + if not args: # plain tuple + self.type_ = Any + self.shape = SHAPE_TUPLE_ELLIPSIS + elif len(args) == 2 and args[1] is Ellipsis: # e.g. Tuple[int, ...] + self.type_ = args[0] + self.shape = SHAPE_TUPLE_ELLIPSIS + self.sub_fields = [self._create_sub_type(args[0], f'{self.name}_0')] + elif args == ((),): # Tuple[()] means empty tuple + self.shape = SHAPE_TUPLE + self.type_ = Any + self.sub_fields = [] + else: + self.shape = SHAPE_TUPLE + self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(args)] + return + elif issubclass(origin, List): + # Create self validators + get_validators = getattr(self.type_, '__get_validators__', None) + if get_validators: + self.class_validators.update( + {f'list_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())} + ) + + self.type_ = get_args(self.type_)[0] + self.shape = SHAPE_LIST + elif issubclass(origin, Set): + # Create self validators + get_validators = getattr(self.type_, '__get_validators__', None) + if get_validators: + self.class_validators.update( + {f'set_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())} + ) + + self.type_ = get_args(self.type_)[0] + self.shape = SHAPE_SET + elif issubclass(origin, FrozenSet): + # Create self validators + get_validators = getattr(self.type_, '__get_validators__', None) + if get_validators: + self.class_validators.update( + {f'frozenset_{i}': Validator(validator, pre=True) for i, validator in enumerate(get_validators())} + ) + + self.type_ = get_args(self.type_)[0] + self.shape = SHAPE_FROZENSET + elif issubclass(origin, Deque): + self.type_ = get_args(self.type_)[0] + self.shape = SHAPE_DEQUE + elif issubclass(origin, Sequence): + self.type_ = get_args(self.type_)[0] + self.shape = SHAPE_SEQUENCE + # priority to most common mapping: dict + elif origin is dict or origin is Dict: + self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) + self.type_ = get_args(self.type_)[1] + self.shape = SHAPE_DICT + elif issubclass(origin, DefaultDict): + self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) + self.type_ = get_args(self.type_)[1] + self.shape = SHAPE_DEFAULTDICT + elif issubclass(origin, Counter): + self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) + self.type_ = int + self.shape = SHAPE_COUNTER + elif issubclass(origin, Mapping): + self.key_field = self._create_sub_type(get_args(self.type_)[0], 'key_' + self.name, for_keys=True) + self.type_ = get_args(self.type_)[1] + self.shape = SHAPE_MAPPING + # Equality check as almost everything inherits form Iterable, including str + # check for Iterable and CollectionsIterable, as it could receive one even when declared with the other + elif origin in {Iterable, CollectionsIterable}: + self.type_ = get_args(self.type_)[0] + self.shape = SHAPE_ITERABLE + self.sub_fields = [self._create_sub_type(self.type_, f'{self.name}_type')] + elif issubclass(origin, Type): # type: ignore + return + elif hasattr(origin, '__get_validators__') or self.model_config.arbitrary_types_allowed: + # Is a Pydantic-compatible generic that handles itself + # or we have arbitrary_types_allowed = True + self.shape = SHAPE_GENERIC + self.sub_fields = [self._create_sub_type(t, f'{self.name}_{i}') for i, t in enumerate(get_args(self.type_))] + self.type_ = origin + return + else: + raise TypeError(f'Fields of type "{origin}" are not supported.') + + # type_ has been refined eg. as the type of a List and sub_fields needs to be populated + self.sub_fields = [self._create_sub_type(self.type_, '_' + self.name)] + + def prepare_discriminated_union_sub_fields(self) -> None: + """ + Prepare the mapping -> and update `sub_fields` + Note that this process can be aborted if a `ForwardRef` is encountered + """ + assert self.discriminator_key is not None + + if self.type_.__class__ is DeferredType: + return + + assert self.sub_fields is not None + sub_fields_mapping: Dict[str, 'ModelField'] = {} + all_aliases: Set[str] = set() + + for sub_field in self.sub_fields: + t = sub_field.type_ + if t.__class__ is ForwardRef: + # Stopping everything...will need to call `update_forward_refs` + return + + alias, discriminator_values = get_discriminator_alias_and_values(t, self.discriminator_key) + all_aliases.add(alias) + for discriminator_value in discriminator_values: + sub_fields_mapping[discriminator_value] = sub_field + + self.sub_fields_mapping = sub_fields_mapping + self.discriminator_alias = get_unique_discriminator_alias(all_aliases, self.discriminator_key) + + def _create_sub_type(self, type_: Type[Any], name: str, *, for_keys: bool = False) -> 'ModelField': + if for_keys: + class_validators = None + else: + # validators for sub items should not have `each_item` as we want to check only the first sublevel + class_validators = { + k: Validator( + func=v.func, + pre=v.pre, + each_item=False, + always=v.always, + check_fields=v.check_fields, + skip_on_failure=v.skip_on_failure, + ) + for k, v in self.class_validators.items() + if v.each_item + } + + field_info, _ = self._get_field_info(name, type_, None, self.model_config) + + return self.__class__( + type_=type_, + name=name, + class_validators=class_validators, + model_config=self.model_config, + field_info=field_info, + ) + + def populate_validators(self) -> None: + """ + Prepare self.pre_validators, self.validators, and self.post_validators based on self.type_'s __get_validators__ + and class validators. This method should be idempotent, e.g. it should be safe to call multiple times + without mis-configuring the field. + """ + self.validate_always = getattr(self.type_, 'validate_always', False) or any( + v.always for v in self.class_validators.values() + ) + + class_validators_ = self.class_validators.values() + if not self.sub_fields or self.shape == SHAPE_GENERIC: + get_validators = getattr(self.type_, '__get_validators__', None) + v_funcs = ( + *[v.func for v in class_validators_ if v.each_item and v.pre], + *(get_validators() if get_validators else list(find_validators(self.type_, self.model_config))), + *[v.func for v in class_validators_ if v.each_item and not v.pre], + ) + self.validators = prep_validators(v_funcs) + + self.pre_validators = [] + self.post_validators = [] + + if self.field_info and self.field_info.const: + self.post_validators.append(make_generic_validator(constant_validator)) + + if class_validators_: + self.pre_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and v.pre) + self.post_validators += prep_validators(v.func for v in class_validators_ if not v.each_item and not v.pre) + + if self.parse_json: + self.pre_validators.append(make_generic_validator(validate_json)) + + self.pre_validators = self.pre_validators or None + self.post_validators = self.post_validators or None + + def validate( + self, v: Any, values: Dict[str, Any], *, loc: 'LocStr', cls: Optional['ModelOrDc'] = None + ) -> 'ValidateReturn': + assert self.type_.__class__ is not DeferredType + + if self.type_.__class__ is ForwardRef: + assert cls is not None + raise ConfigError( + f'field "{self.name}" not yet prepared so type is still a ForwardRef, ' + f'you might need to call {cls.__name__}.update_forward_refs().' + ) + + errors: Optional['ErrorList'] + if self.pre_validators: + v, errors = self._apply_validators(v, values, loc, cls, self.pre_validators) + if errors: + return v, errors + + if v is None: + if is_none_type(self.type_): + # keep validating + pass + elif self.allow_none: + if self.post_validators: + return self._apply_validators(v, values, loc, cls, self.post_validators) + else: + return None, None + else: + return v, ErrorWrapper(NoneIsNotAllowedError(), loc) + + if self.shape == SHAPE_SINGLETON: + v, errors = self._validate_singleton(v, values, loc, cls) + elif self.shape in MAPPING_LIKE_SHAPES: + v, errors = self._validate_mapping_like(v, values, loc, cls) + elif self.shape == SHAPE_TUPLE: + v, errors = self._validate_tuple(v, values, loc, cls) + elif self.shape == SHAPE_ITERABLE: + v, errors = self._validate_iterable(v, values, loc, cls) + elif self.shape == SHAPE_GENERIC: + v, errors = self._apply_validators(v, values, loc, cls, self.validators) + else: + # sequence, list, set, generator, tuple with ellipsis, frozen set + v, errors = self._validate_sequence_like(v, values, loc, cls) + + if not errors and self.post_validators: + v, errors = self._apply_validators(v, values, loc, cls, self.post_validators) + return v, errors + + def _validate_sequence_like( # noqa: C901 (ignore complexity) + self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] + ) -> 'ValidateReturn': + """ + Validate sequence-like containers: lists, tuples, sets and generators + Note that large if-else blocks are necessary to enable Cython + optimization, which is why we disable the complexity check above. + """ + if not sequence_like(v): + e: errors_.PydanticTypeError + if self.shape == SHAPE_LIST: + e = errors_.ListError() + elif self.shape in (SHAPE_TUPLE, SHAPE_TUPLE_ELLIPSIS): + e = errors_.TupleError() + elif self.shape == SHAPE_SET: + e = errors_.SetError() + elif self.shape == SHAPE_FROZENSET: + e = errors_.FrozenSetError() + else: + e = errors_.SequenceError() + return v, ErrorWrapper(e, loc) + + loc = loc if isinstance(loc, tuple) else (loc,) + result = [] + errors: List[ErrorList] = [] + for i, v_ in enumerate(v): + v_loc = *loc, i + r, ee = self._validate_singleton(v_, values, v_loc, cls) + if ee: + errors.append(ee) + else: + result.append(r) + + if errors: + return v, errors + + converted: Union[List[Any], Set[Any], FrozenSet[Any], Tuple[Any, ...], Iterator[Any], Deque[Any]] = result + + if self.shape == SHAPE_SET: + converted = set(result) + elif self.shape == SHAPE_FROZENSET: + converted = frozenset(result) + elif self.shape == SHAPE_TUPLE_ELLIPSIS: + converted = tuple(result) + elif self.shape == SHAPE_DEQUE: + converted = deque(result, maxlen=getattr(v, 'maxlen', None)) + elif self.shape == SHAPE_SEQUENCE: + if isinstance(v, tuple): + converted = tuple(result) + elif isinstance(v, set): + converted = set(result) + elif isinstance(v, Generator): + converted = iter(result) + elif isinstance(v, deque): + converted = deque(result, maxlen=getattr(v, 'maxlen', None)) + return converted, None + + def _validate_iterable( + self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] + ) -> 'ValidateReturn': + """ + Validate Iterables. + + This intentionally doesn't validate values to allow infinite generators. + """ + + try: + iterable = iter(v) + except TypeError: + return v, ErrorWrapper(errors_.IterableError(), loc) + return iterable, None + + def _validate_tuple( + self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] + ) -> 'ValidateReturn': + e: Optional[Exception] = None + if not sequence_like(v): + e = errors_.TupleError() + else: + actual_length, expected_length = len(v), len(self.sub_fields) # type: ignore + if actual_length != expected_length: + e = errors_.TupleLengthError(actual_length=actual_length, expected_length=expected_length) + + if e: + return v, ErrorWrapper(e, loc) + + loc = loc if isinstance(loc, tuple) else (loc,) + result = [] + errors: List[ErrorList] = [] + for i, (v_, field) in enumerate(zip(v, self.sub_fields)): # type: ignore + v_loc = *loc, i + r, ee = field.validate(v_, values, loc=v_loc, cls=cls) + if ee: + errors.append(ee) + else: + result.append(r) + + if errors: + return v, errors + else: + return tuple(result), None + + def _validate_mapping_like( + self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] + ) -> 'ValidateReturn': + try: + v_iter = dict_validator(v) + except TypeError as exc: + return v, ErrorWrapper(exc, loc) + + loc = loc if isinstance(loc, tuple) else (loc,) + result, errors = {}, [] + for k, v_ in v_iter.items(): + v_loc = *loc, '__key__' + key_result, key_errors = self.key_field.validate(k, values, loc=v_loc, cls=cls) # type: ignore + if key_errors: + errors.append(key_errors) + continue + + v_loc = *loc, k + value_result, value_errors = self._validate_singleton(v_, values, v_loc, cls) + if value_errors: + errors.append(value_errors) + continue + + result[key_result] = value_result + if errors: + return v, errors + elif self.shape == SHAPE_DICT: + return result, None + elif self.shape == SHAPE_DEFAULTDICT: + return defaultdict(self.type_, result), None + elif self.shape == SHAPE_COUNTER: + return CollectionCounter(result), None + else: + return self._get_mapping_value(v, result), None + + def _get_mapping_value(self, original: T, converted: Dict[Any, Any]) -> Union[T, Dict[Any, Any]]: + """ + When type is `Mapping[KT, KV]` (or another unsupported mapping), we try to avoid + coercing to `dict` unwillingly. + """ + original_cls = original.__class__ + + if original_cls == dict or original_cls == Dict: + return converted + elif original_cls in {defaultdict, DefaultDict}: + return defaultdict(self.type_, converted) + else: + try: + # Counter, OrderedDict, UserDict, ... + return original_cls(converted) # type: ignore + except TypeError: + raise RuntimeError(f'Could not convert dictionary to {original_cls.__name__!r}') from None + + def _validate_singleton( + self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] + ) -> 'ValidateReturn': + if self.sub_fields: + if self.discriminator_key is not None: + return self._validate_discriminated_union(v, values, loc, cls) + + errors = [] + + if self.model_config.smart_union and is_union(get_origin(self.type_)): + # 1st pass: check if the value is an exact instance of one of the Union types + # (e.g. to avoid coercing a bool into an int) + for field in self.sub_fields: + if v.__class__ is field.outer_type_: + return v, None + + # 2nd pass: check if the value is an instance of any subclass of the Union types + for field in self.sub_fields: + # This whole logic will be improved later on to support more complex `isinstance` checks + # It will probably be done once a strict mode is added and be something like: + # ``` + # value, error = field.validate(v, values, strict=True) + # if error is None: + # return value, None + # ``` + try: + if isinstance(v, field.outer_type_): + return v, None + except TypeError: + # compound type + if lenient_isinstance(v, get_origin(field.outer_type_)): + value, error = field.validate(v, values, loc=loc, cls=cls) + if not error: + return value, None + + # 1st pass by default or 3rd pass with `smart_union` enabled: + # check if the value can be coerced into one of the Union types + for field in self.sub_fields: + value, error = field.validate(v, values, loc=loc, cls=cls) + if error: + errors.append(error) + else: + return value, None + return v, errors + else: + return self._apply_validators(v, values, loc, cls, self.validators) + + def _validate_discriminated_union( + self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'] + ) -> 'ValidateReturn': + assert self.discriminator_key is not None + assert self.discriminator_alias is not None + + try: + try: + discriminator_value = v[self.discriminator_alias] + except KeyError: + if self.model_config.allow_population_by_field_name: + discriminator_value = v[self.discriminator_key] + else: + raise + except KeyError: + return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc) + except TypeError: + try: + # BaseModel or dataclass + discriminator_value = getattr(v, self.discriminator_key) + except (AttributeError, TypeError): + return v, ErrorWrapper(MissingDiscriminator(discriminator_key=self.discriminator_key), loc) + + if self.sub_fields_mapping is None: + assert cls is not None + raise ConfigError( + f'field "{self.name}" not yet prepared so type is still a ForwardRef, ' + f'you might need to call {cls.__name__}.update_forward_refs().' + ) + + try: + sub_field = self.sub_fields_mapping[discriminator_value] + except (KeyError, TypeError): + # KeyError: `discriminator_value` is not in the dictionary. + # TypeError: `discriminator_value` is unhashable. + assert self.sub_fields_mapping is not None + return v, ErrorWrapper( + InvalidDiscriminator( + discriminator_key=self.discriminator_key, + discriminator_value=discriminator_value, + allowed_values=list(self.sub_fields_mapping), + ), + loc, + ) + else: + if not isinstance(loc, tuple): + loc = (loc,) + return sub_field.validate(v, values, loc=(*loc, display_as_type(sub_field.type_)), cls=cls) + + def _apply_validators( + self, v: Any, values: Dict[str, Any], loc: 'LocStr', cls: Optional['ModelOrDc'], validators: 'ValidatorsList' + ) -> 'ValidateReturn': + for validator in validators: + try: + v = validator(cls, v, values, self, self.model_config) + except (ValueError, TypeError, AssertionError) as exc: + return v, ErrorWrapper(exc, loc) + return v, None + + def is_complex(self) -> bool: + """ + Whether the field is "complex" eg. env variables should be parsed as JSON. + """ + from pydantic.v1.main import BaseModel + + return ( + self.shape != SHAPE_SINGLETON + or hasattr(self.type_, '__pydantic_model__') + or lenient_issubclass(self.type_, (BaseModel, list, set, frozenset, dict)) + ) + + def _type_display(self) -> PyObjectStr: + t = display_as_type(self.type_) + + if self.shape in MAPPING_LIKE_SHAPES: + t = f'Mapping[{display_as_type(self.key_field.type_)}, {t}]' # type: ignore + elif self.shape == SHAPE_TUPLE: + t = 'Tuple[{}]'.format(', '.join(display_as_type(f.type_) for f in self.sub_fields)) # type: ignore + elif self.shape == SHAPE_GENERIC: + assert self.sub_fields + t = '{}[{}]'.format( + display_as_type(self.type_), ', '.join(display_as_type(f.type_) for f in self.sub_fields) + ) + elif self.shape != SHAPE_SINGLETON: + t = SHAPE_NAME_LOOKUP[self.shape].format(t) + + if self.allow_none and (self.shape != SHAPE_SINGLETON or not self.sub_fields): + t = f'Optional[{t}]' + return PyObjectStr(t) + + def __repr_args__(self) -> 'ReprArgs': + args = [('name', self.name), ('type', self._type_display()), ('required', self.required)] + + if not self.required: + if self.default_factory is not None: + args.append(('default_factory', f'')) + else: + args.append(('default', self.default)) + + if self.alt_alias: + args.append(('alias', self.alias)) + return args + + +class ModelPrivateAttr(Representation): + __slots__ = ('default', 'default_factory') + + def __init__(self, default: Any = Undefined, *, default_factory: Optional[NoArgAnyCallable] = None) -> None: + self.default = default + self.default_factory = default_factory + + def get_default(self) -> Any: + return smart_deepcopy(self.default) if self.default_factory is None else self.default_factory() + + def __eq__(self, other: Any) -> bool: + return isinstance(other, self.__class__) and (self.default, self.default_factory) == ( + other.default, + other.default_factory, + ) + + +def PrivateAttr( + default: Any = Undefined, + *, + default_factory: Optional[NoArgAnyCallable] = None, +) -> Any: + """ + Indicates that attribute is only used internally and never mixed with regular fields. + + Types or values of private attrs are not checked by pydantic and it's up to you to keep them relevant. + + Private attrs are stored in model __slots__. + + :param default: the attribute’s default value + :param default_factory: callable that will be called when a default value is needed for this attribute + If both `default` and `default_factory` are set, an error is raised. + """ + if default is not Undefined and default_factory is not None: + raise ValueError('cannot specify both default and default_factory') + + return ModelPrivateAttr( + default, + default_factory=default_factory, + ) + + +class DeferredType: + """ + Used to postpone field preparation, while creating recursive generic models. + """ + + +def is_finalvar_with_default_val(type_: Type[Any], val: Any) -> bool: + return is_finalvar(type_) and val is not Undefined and not isinstance(val, FieldInfo) diff --git a/env/Lib/site-packages/pydantic/v1/generics.py b/env/Lib/site-packages/pydantic/v1/generics.py new file mode 100644 index 0000000..9a69f2b --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/generics.py @@ -0,0 +1,400 @@ +import sys +import types +import typing +from typing import ( + TYPE_CHECKING, + Any, + ClassVar, + Dict, + ForwardRef, + Generic, + Iterator, + List, + Mapping, + Optional, + Tuple, + Type, + TypeVar, + Union, + cast, +) +from weakref import WeakKeyDictionary, WeakValueDictionary + +from typing_extensions import Annotated, Literal as ExtLiteral + +from pydantic.v1.class_validators import gather_all_validators +from pydantic.v1.fields import DeferredType +from pydantic.v1.main import BaseModel, create_model +from pydantic.v1.types import JsonWrapper +from pydantic.v1.typing import display_as_type, get_all_type_hints, get_args, get_origin, typing_base +from pydantic.v1.utils import all_identical, lenient_issubclass + +if sys.version_info >= (3, 10): + from typing import _UnionGenericAlias +if sys.version_info >= (3, 8): + from typing import Literal + +GenericModelT = TypeVar('GenericModelT', bound='GenericModel') +TypeVarType = Any # since mypy doesn't allow the use of TypeVar as a type + +CacheKey = Tuple[Type[Any], Any, Tuple[Any, ...]] +Parametrization = Mapping[TypeVarType, Type[Any]] + +# weak dictionaries allow the dynamically created parametrized versions of generic models to get collected +# once they are no longer referenced by the caller. +if sys.version_info >= (3, 9): # Typing for weak dictionaries available at 3.9 + GenericTypesCache = WeakValueDictionary[CacheKey, Type[BaseModel]] + AssignedParameters = WeakKeyDictionary[Type[BaseModel], Parametrization] +else: + GenericTypesCache = WeakValueDictionary + AssignedParameters = WeakKeyDictionary + +# _generic_types_cache is a Mapping from __class_getitem__ arguments to the parametrized version of generic models. +# This ensures multiple calls of e.g. A[B] return always the same class. +_generic_types_cache = GenericTypesCache() + +# _assigned_parameters is a Mapping from parametrized version of generic models to assigned types of parametrizations +# as captured during construction of the class (not instances). +# E.g., for generic model `Model[A, B]`, when parametrized model `Model[int, str]` is created, +# `Model[int, str]`: {A: int, B: str}` will be stored in `_assigned_parameters`. +# (This information is only otherwise available after creation from the class name string). +_assigned_parameters = AssignedParameters() + + +class GenericModel(BaseModel): + __slots__ = () + __concrete__: ClassVar[bool] = False + + if TYPE_CHECKING: + # Putting this in a TYPE_CHECKING block allows us to replace `if Generic not in cls.__bases__` with + # `not hasattr(cls, "__parameters__")`. This means we don't need to force non-concrete subclasses of + # `GenericModel` to also inherit from `Generic`, which would require changes to the use of `create_model` below. + __parameters__: ClassVar[Tuple[TypeVarType, ...]] + + # Setting the return type as Type[Any] instead of Type[BaseModel] prevents PyCharm warnings + def __class_getitem__(cls: Type[GenericModelT], params: Union[Type[Any], Tuple[Type[Any], ...]]) -> Type[Any]: + """Instantiates a new class from a generic class `cls` and type variables `params`. + + :param params: Tuple of types the class . Given a generic class + `Model` with 2 type variables and a concrete model `Model[str, int]`, + the value `(str, int)` would be passed to `params`. + :return: New model class inheriting from `cls` with instantiated + types described by `params`. If no parameters are given, `cls` is + returned as is. + + """ + + def _cache_key(_params: Any) -> CacheKey: + args = get_args(_params) + # python returns a list for Callables, which is not hashable + if len(args) == 2 and isinstance(args[0], list): + args = (tuple(args[0]), args[1]) + return cls, _params, args + + cached = _generic_types_cache.get(_cache_key(params)) + if cached is not None: + return cached + if cls.__concrete__ and Generic not in cls.__bases__: + raise TypeError('Cannot parameterize a concrete instantiation of a generic model') + if not isinstance(params, tuple): + params = (params,) + if cls is GenericModel and any(isinstance(param, TypeVar) for param in params): + raise TypeError('Type parameters should be placed on typing.Generic, not GenericModel') + if not hasattr(cls, '__parameters__'): + raise TypeError(f'Type {cls.__name__} must inherit from typing.Generic before being parameterized') + + check_parameters_count(cls, params) + # Build map from generic typevars to passed params + typevars_map: Dict[TypeVarType, Type[Any]] = dict(zip(cls.__parameters__, params)) + if all_identical(typevars_map.keys(), typevars_map.values()) and typevars_map: + return cls # if arguments are equal to parameters it's the same object + + # Create new model with original model as parent inserting fields with DeferredType. + model_name = cls.__concrete_name__(params) + validators = gather_all_validators(cls) + + type_hints = get_all_type_hints(cls).items() + instance_type_hints = {k: v for k, v in type_hints if get_origin(v) is not ClassVar} + + fields = {k: (DeferredType(), cls.__fields__[k].field_info) for k in instance_type_hints if k in cls.__fields__} + + model_module, called_globally = get_caller_frame_info() + created_model = cast( + Type[GenericModel], # casting ensures mypy is aware of the __concrete__ and __parameters__ attributes + create_model( + model_name, + __module__=model_module or cls.__module__, + __base__=(cls,) + tuple(cls.__parameterized_bases__(typevars_map)), + __config__=None, + __validators__=validators, + __cls_kwargs__=None, + **fields, + ), + ) + + _assigned_parameters[created_model] = typevars_map + + if called_globally: # create global reference and therefore allow pickling + object_by_reference = None + reference_name = model_name + reference_module_globals = sys.modules[created_model.__module__].__dict__ + while object_by_reference is not created_model: + object_by_reference = reference_module_globals.setdefault(reference_name, created_model) + reference_name += '_' + + created_model.Config = cls.Config + + # Find any typevars that are still present in the model. + # If none are left, the model is fully "concrete", otherwise the new + # class is a generic class as well taking the found typevars as + # parameters. + new_params = tuple( + {param: None for param in iter_contained_typevars(typevars_map.values())} + ) # use dict as ordered set + created_model.__concrete__ = not new_params + if new_params: + created_model.__parameters__ = new_params + + # Save created model in cache so we don't end up creating duplicate + # models that should be identical. + _generic_types_cache[_cache_key(params)] = created_model + if len(params) == 1: + _generic_types_cache[_cache_key(params[0])] = created_model + + # Recursively walk class type hints and replace generic typevars + # with concrete types that were passed. + _prepare_model_fields(created_model, fields, instance_type_hints, typevars_map) + + return created_model + + @classmethod + def __concrete_name__(cls: Type[Any], params: Tuple[Type[Any], ...]) -> str: + """Compute class name for child classes. + + :param params: Tuple of types the class . Given a generic class + `Model` with 2 type variables and a concrete model `Model[str, int]`, + the value `(str, int)` would be passed to `params`. + :return: String representing a the new class where `params` are + passed to `cls` as type variables. + + This method can be overridden to achieve a custom naming scheme for GenericModels. + """ + param_names = [display_as_type(param) for param in params] + params_component = ', '.join(param_names) + return f'{cls.__name__}[{params_component}]' + + @classmethod + def __parameterized_bases__(cls, typevars_map: Parametrization) -> Iterator[Type[Any]]: + """ + Returns unbound bases of cls parameterised to given type variables + + :param typevars_map: Dictionary of type applications for binding subclasses. + Given a generic class `Model` with 2 type variables [S, T] + and a concrete model `Model[str, int]`, + the value `{S: str, T: int}` would be passed to `typevars_map`. + :return: an iterator of generic sub classes, parameterised by `typevars_map` + and other assigned parameters of `cls` + + e.g.: + ``` + class A(GenericModel, Generic[T]): + ... + + class B(A[V], Generic[V]): + ... + + assert A[int] in B.__parameterized_bases__({V: int}) + ``` + """ + + def build_base_model( + base_model: Type[GenericModel], mapped_types: Parametrization + ) -> Iterator[Type[GenericModel]]: + base_parameters = tuple(mapped_types[param] for param in base_model.__parameters__) + parameterized_base = base_model.__class_getitem__(base_parameters) + if parameterized_base is base_model or parameterized_base is cls: + # Avoid duplication in MRO + return + yield parameterized_base + + for base_model in cls.__bases__: + if not issubclass(base_model, GenericModel): + # not a class that can be meaningfully parameterized + continue + elif not getattr(base_model, '__parameters__', None): + # base_model is "GenericModel" (and has no __parameters__) + # or + # base_model is already concrete, and will be included transitively via cls. + continue + elif cls in _assigned_parameters: + if base_model in _assigned_parameters: + # cls is partially parameterised but not from base_model + # e.g. cls = B[S], base_model = A[S] + # B[S][int] should subclass A[int], (and will be transitively via B[int]) + # but it's not viable to consistently subclass types with arbitrary construction + # So don't attempt to include A[S][int] + continue + else: # base_model not in _assigned_parameters: + # cls is partially parameterized, base_model is original generic + # e.g. cls = B[str, T], base_model = B[S, T] + # Need to determine the mapping for the base_model parameters + mapped_types: Parametrization = { + key: typevars_map.get(value, value) for key, value in _assigned_parameters[cls].items() + } + yield from build_base_model(base_model, mapped_types) + else: + # cls is base generic, so base_class has a distinct base + # can construct the Parameterised base model using typevars_map directly + yield from build_base_model(base_model, typevars_map) + + +def replace_types(type_: Any, type_map: Mapping[Any, Any]) -> Any: + """Return type with all occurrences of `type_map` keys recursively replaced with their values. + + :param type_: Any type, class or generic alias + :param type_map: Mapping from `TypeVar` instance to concrete types. + :return: New type representing the basic structure of `type_` with all + `typevar_map` keys recursively replaced. + + >>> replace_types(Tuple[str, Union[List[str], float]], {str: int}) + Tuple[int, Union[List[int], float]] + + """ + if not type_map: + return type_ + + type_args = get_args(type_) + origin_type = get_origin(type_) + + if origin_type is Annotated: + annotated_type, *annotations = type_args + return Annotated[replace_types(annotated_type, type_map), tuple(annotations)] + + if (origin_type is ExtLiteral) or (sys.version_info >= (3, 8) and origin_type is Literal): + return type_map.get(type_, type_) + # Having type args is a good indicator that this is a typing module + # class instantiation or a generic alias of some sort. + if type_args: + resolved_type_args = tuple(replace_types(arg, type_map) for arg in type_args) + if all_identical(type_args, resolved_type_args): + # If all arguments are the same, there is no need to modify the + # type or create a new object at all + return type_ + if ( + origin_type is not None + and isinstance(type_, typing_base) + and not isinstance(origin_type, typing_base) + and getattr(type_, '_name', None) is not None + ): + # In python < 3.9 generic aliases don't exist so any of these like `list`, + # `type` or `collections.abc.Callable` need to be translated. + # See: https://www.python.org/dev/peps/pep-0585 + origin_type = getattr(typing, type_._name) + assert origin_type is not None + # PEP-604 syntax (Ex.: list | str) is represented with a types.UnionType object that does not have __getitem__. + # We also cannot use isinstance() since we have to compare types. + if sys.version_info >= (3, 10) and origin_type is types.UnionType: # noqa: E721 + return _UnionGenericAlias(origin_type, resolved_type_args) + return origin_type[resolved_type_args] + + # We handle pydantic generic models separately as they don't have the same + # semantics as "typing" classes or generic aliases + if not origin_type and lenient_issubclass(type_, GenericModel) and not type_.__concrete__: + type_args = type_.__parameters__ + resolved_type_args = tuple(replace_types(t, type_map) for t in type_args) + if all_identical(type_args, resolved_type_args): + return type_ + return type_[resolved_type_args] + + # Handle special case for typehints that can have lists as arguments. + # `typing.Callable[[int, str], int]` is an example for this. + if isinstance(type_, (List, list)): + resolved_list = list(replace_types(element, type_map) for element in type_) + if all_identical(type_, resolved_list): + return type_ + return resolved_list + + # For JsonWrapperValue, need to handle its inner type to allow correct parsing + # of generic Json arguments like Json[T] + if not origin_type and lenient_issubclass(type_, JsonWrapper): + type_.inner_type = replace_types(type_.inner_type, type_map) + return type_ + + # If all else fails, we try to resolve the type directly and otherwise just + # return the input with no modifications. + new_type = type_map.get(type_, type_) + # Convert string to ForwardRef + if isinstance(new_type, str): + return ForwardRef(new_type) + else: + return new_type + + +def check_parameters_count(cls: Type[GenericModel], parameters: Tuple[Any, ...]) -> None: + actual = len(parameters) + expected = len(cls.__parameters__) + if actual != expected: + description = 'many' if actual > expected else 'few' + raise TypeError(f'Too {description} parameters for {cls.__name__}; actual {actual}, expected {expected}') + + +DictValues: Type[Any] = {}.values().__class__ + + +def iter_contained_typevars(v: Any) -> Iterator[TypeVarType]: + """Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found.""" + if isinstance(v, TypeVar): + yield v + elif hasattr(v, '__parameters__') and not get_origin(v) and lenient_issubclass(v, GenericModel): + yield from v.__parameters__ + elif isinstance(v, (DictValues, list)): + for var in v: + yield from iter_contained_typevars(var) + else: + args = get_args(v) + for arg in args: + yield from iter_contained_typevars(arg) + + +def get_caller_frame_info() -> Tuple[Optional[str], bool]: + """ + Used inside a function to check whether it was called globally + + Will only work against non-compiled code, therefore used only in pydantic.generics + + :returns Tuple[module_name, called_globally] + """ + try: + previous_caller_frame = sys._getframe(2) + except ValueError as e: + raise RuntimeError('This function must be used inside another function') from e + except AttributeError: # sys module does not have _getframe function, so there's nothing we can do about it + return None, False + frame_globals = previous_caller_frame.f_globals + return frame_globals.get('__name__'), previous_caller_frame.f_locals is frame_globals + + +def _prepare_model_fields( + created_model: Type[GenericModel], + fields: Mapping[str, Any], + instance_type_hints: Mapping[str, type], + typevars_map: Mapping[Any, type], +) -> None: + """ + Replace DeferredType fields with concrete type hints and prepare them. + """ + + for key, field in created_model.__fields__.items(): + if key not in fields: + assert field.type_.__class__ is not DeferredType + # https://github.com/nedbat/coveragepy/issues/198 + continue # pragma: no cover + + assert field.type_.__class__ is DeferredType, field.type_.__class__ + + field_type_hint = instance_type_hints[key] + concrete_type = replace_types(field_type_hint, typevars_map) + field.type_ = concrete_type + field.outer_type_ = concrete_type + field.prepare() + created_model.__annotations__[key] = concrete_type diff --git a/env/Lib/site-packages/pydantic/v1/json.py b/env/Lib/site-packages/pydantic/v1/json.py new file mode 100644 index 0000000..41d0d5f --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/json.py @@ -0,0 +1,112 @@ +import datetime +from collections import deque +from decimal import Decimal +from enum import Enum +from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network +from pathlib import Path +from re import Pattern +from types import GeneratorType +from typing import Any, Callable, Dict, Type, Union +from uuid import UUID + +from pydantic.v1.color import Color +from pydantic.v1.networks import NameEmail +from pydantic.v1.types import SecretBytes, SecretStr + +__all__ = 'pydantic_encoder', 'custom_pydantic_encoder', 'timedelta_isoformat' + + +def isoformat(o: Union[datetime.date, datetime.time]) -> str: + return o.isoformat() + + +def decimal_encoder(dec_value: Decimal) -> Union[int, float]: + """ + Encodes a Decimal as int of there's no exponent, otherwise float + + This is useful when we use ConstrainedDecimal to represent Numeric(x,0) + where a integer (but not int typed) is used. Encoding this as a float + results in failed round-tripping between encode and parse. + Our Id type is a prime example of this. + + >>> decimal_encoder(Decimal("1.0")) + 1.0 + + >>> decimal_encoder(Decimal("1")) + 1 + """ + if dec_value.as_tuple().exponent >= 0: + return int(dec_value) + else: + return float(dec_value) + + +ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = { + bytes: lambda o: o.decode(), + Color: str, + datetime.date: isoformat, + datetime.datetime: isoformat, + datetime.time: isoformat, + datetime.timedelta: lambda td: td.total_seconds(), + Decimal: decimal_encoder, + Enum: lambda o: o.value, + frozenset: list, + deque: list, + GeneratorType: list, + IPv4Address: str, + IPv4Interface: str, + IPv4Network: str, + IPv6Address: str, + IPv6Interface: str, + IPv6Network: str, + NameEmail: str, + Path: str, + Pattern: lambda o: o.pattern, + SecretBytes: str, + SecretStr: str, + set: list, + UUID: str, +} + + +def pydantic_encoder(obj: Any) -> Any: + from dataclasses import asdict, is_dataclass + + from pydantic.v1.main import BaseModel + + if isinstance(obj, BaseModel): + return obj.dict() + elif is_dataclass(obj): + return asdict(obj) + + # Check the class type and its superclasses for a matching encoder + for base in obj.__class__.__mro__[:-1]: + try: + encoder = ENCODERS_BY_TYPE[base] + except KeyError: + continue + return encoder(obj) + else: # We have exited the for loop without finding a suitable encoder + raise TypeError(f"Object of type '{obj.__class__.__name__}' is not JSON serializable") + + +def custom_pydantic_encoder(type_encoders: Dict[Any, Callable[[Type[Any]], Any]], obj: Any) -> Any: + # Check the class type and its superclasses for a matching encoder + for base in obj.__class__.__mro__[:-1]: + try: + encoder = type_encoders[base] + except KeyError: + continue + + return encoder(obj) + else: # We have exited the for loop without finding a suitable encoder + return pydantic_encoder(obj) + + +def timedelta_isoformat(td: datetime.timedelta) -> str: + """ + ISO 8601 encoding for Python timedelta object. + """ + minutes, seconds = divmod(td.seconds, 60) + hours, minutes = divmod(minutes, 60) + return f'{"-" if td.days < 0 else ""}P{abs(td.days)}DT{hours:d}H{minutes:d}M{seconds:d}.{td.microseconds:06d}S' diff --git a/env/Lib/site-packages/pydantic/v1/main.py b/env/Lib/site-packages/pydantic/v1/main.py new file mode 100644 index 0000000..cd37603 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/main.py @@ -0,0 +1,1107 @@ +import warnings +from abc import ABCMeta +from copy import deepcopy +from enum import Enum +from functools import partial +from pathlib import Path +from types import FunctionType, prepare_class, resolve_bases +from typing import ( + TYPE_CHECKING, + AbstractSet, + Any, + Callable, + ClassVar, + Dict, + List, + Mapping, + Optional, + Tuple, + Type, + TypeVar, + Union, + cast, + no_type_check, + overload, +) + +from typing_extensions import dataclass_transform + +from pydantic.v1.class_validators import ValidatorGroup, extract_root_validators, extract_validators, inherit_validators +from pydantic.v1.config import BaseConfig, Extra, inherit_config, prepare_config +from pydantic.v1.error_wrappers import ErrorWrapper, ValidationError +from pydantic.v1.errors import ConfigError, DictError, ExtraError, MissingError +from pydantic.v1.fields import ( + MAPPING_LIKE_SHAPES, + Field, + ModelField, + ModelPrivateAttr, + PrivateAttr, + Undefined, + is_finalvar_with_default_val, +) +from pydantic.v1.json import custom_pydantic_encoder, pydantic_encoder +from pydantic.v1.parse import Protocol, load_file, load_str_bytes +from pydantic.v1.schema import default_ref_template, model_schema +from pydantic.v1.types import PyObject, StrBytes +from pydantic.v1.typing import ( + AnyCallable, + get_args, + get_origin, + is_classvar, + is_namedtuple, + is_union, + resolve_annotations, + update_model_forward_refs, +) +from pydantic.v1.utils import ( + DUNDER_ATTRIBUTES, + ROOT_KEY, + ClassAttribute, + GetterDict, + Representation, + ValueItems, + generate_model_signature, + is_valid_field, + is_valid_private_name, + lenient_issubclass, + sequence_like, + smart_deepcopy, + unique_list, + validate_field_name, +) + +if TYPE_CHECKING: + from inspect import Signature + + from pydantic.v1.class_validators import ValidatorListDict + from pydantic.v1.types import ModelOrDc + from pydantic.v1.typing import ( + AbstractSetIntStr, + AnyClassMethod, + CallableGenerator, + DictAny, + DictStrAny, + MappingIntStrAny, + ReprArgs, + SetStr, + TupleGenerator, + ) + + Model = TypeVar('Model', bound='BaseModel') + +__all__ = 'BaseModel', 'create_model', 'validate_model' + +_T = TypeVar('_T') + + +def validate_custom_root_type(fields: Dict[str, ModelField]) -> None: + if len(fields) > 1: + raise ValueError(f'{ROOT_KEY} cannot be mixed with other fields') + + +def generate_hash_function(frozen: bool) -> Optional[Callable[[Any], int]]: + def hash_function(self_: Any) -> int: + return hash(self_.__class__) + hash(tuple(self_.__dict__.values())) + + return hash_function if frozen else None + + +# If a field is of type `Callable`, its default value should be a function and cannot to ignored. +ANNOTATED_FIELD_UNTOUCHED_TYPES: Tuple[Any, ...] = (property, type, classmethod, staticmethod) +# When creating a `BaseModel` instance, we bypass all the methods, properties... added to the model +UNTOUCHED_TYPES: Tuple[Any, ...] = (FunctionType,) + ANNOTATED_FIELD_UNTOUCHED_TYPES +# Note `ModelMetaclass` refers to `BaseModel`, but is also used to *create* `BaseModel`, so we need to add this extra +# (somewhat hacky) boolean to keep track of whether we've created the `BaseModel` class yet, and therefore whether it's +# safe to refer to it. If it *hasn't* been created, we assume that the `__new__` call we're in the middle of is for +# the `BaseModel` class, since that's defined immediately after the metaclass. +_is_base_model_class_defined = False + + +@dataclass_transform(kw_only_default=True, field_specifiers=(Field,)) +class ModelMetaclass(ABCMeta): + @no_type_check # noqa C901 + def __new__(mcs, name, bases, namespace, **kwargs): # noqa C901 + fields: Dict[str, ModelField] = {} + config = BaseConfig + validators: 'ValidatorListDict' = {} + + pre_root_validators, post_root_validators = [], [] + private_attributes: Dict[str, ModelPrivateAttr] = {} + base_private_attributes: Dict[str, ModelPrivateAttr] = {} + slots: SetStr = namespace.get('__slots__', ()) + slots = {slots} if isinstance(slots, str) else set(slots) + class_vars: SetStr = set() + hash_func: Optional[Callable[[Any], int]] = None + + for base in reversed(bases): + if _is_base_model_class_defined and issubclass(base, BaseModel) and base != BaseModel: + fields.update(smart_deepcopy(base.__fields__)) + config = inherit_config(base.__config__, config) + validators = inherit_validators(base.__validators__, validators) + pre_root_validators += base.__pre_root_validators__ + post_root_validators += base.__post_root_validators__ + base_private_attributes.update(base.__private_attributes__) + class_vars.update(base.__class_vars__) + hash_func = base.__hash__ + + resolve_forward_refs = kwargs.pop('__resolve_forward_refs__', True) + allowed_config_kwargs: SetStr = { + key + for key in dir(config) + if not (key.startswith('__') and key.endswith('__')) # skip dunder methods and attributes + } + config_kwargs = {key: kwargs.pop(key) for key in kwargs.keys() & allowed_config_kwargs} + config_from_namespace = namespace.get('Config') + if config_kwargs and config_from_namespace: + raise TypeError('Specifying config in two places is ambiguous, use either Config attribute or class kwargs') + config = inherit_config(config_from_namespace, config, **config_kwargs) + + validators = inherit_validators(extract_validators(namespace), validators) + vg = ValidatorGroup(validators) + + for f in fields.values(): + f.set_config(config) + extra_validators = vg.get_validators(f.name) + if extra_validators: + f.class_validators.update(extra_validators) + # re-run prepare to add extra validators + f.populate_validators() + + prepare_config(config, name) + + untouched_types = ANNOTATED_FIELD_UNTOUCHED_TYPES + + def is_untouched(v: Any) -> bool: + return isinstance(v, untouched_types) or v.__class__.__name__ == 'cython_function_or_method' + + if (namespace.get('__module__'), namespace.get('__qualname__')) != ('pydantic.main', 'BaseModel'): + annotations = resolve_annotations(namespace.get('__annotations__', {}), namespace.get('__module__', None)) + # annotation only fields need to come first in fields + for ann_name, ann_type in annotations.items(): + if is_classvar(ann_type): + class_vars.add(ann_name) + elif is_finalvar_with_default_val(ann_type, namespace.get(ann_name, Undefined)): + class_vars.add(ann_name) + elif is_valid_field(ann_name): + validate_field_name(bases, ann_name) + value = namespace.get(ann_name, Undefined) + allowed_types = get_args(ann_type) if is_union(get_origin(ann_type)) else (ann_type,) + if ( + is_untouched(value) + and ann_type != PyObject + and not any( + lenient_issubclass(get_origin(allowed_type), Type) for allowed_type in allowed_types + ) + ): + continue + fields[ann_name] = ModelField.infer( + name=ann_name, + value=value, + annotation=ann_type, + class_validators=vg.get_validators(ann_name), + config=config, + ) + elif ann_name not in namespace and config.underscore_attrs_are_private: + private_attributes[ann_name] = PrivateAttr() + + untouched_types = UNTOUCHED_TYPES + config.keep_untouched + for var_name, value in namespace.items(): + can_be_changed = var_name not in class_vars and not is_untouched(value) + if isinstance(value, ModelPrivateAttr): + if not is_valid_private_name(var_name): + raise NameError( + f'Private attributes "{var_name}" must not be a valid field name; ' + f'Use sunder or dunder names, e. g. "_{var_name}" or "__{var_name}__"' + ) + private_attributes[var_name] = value + elif config.underscore_attrs_are_private and is_valid_private_name(var_name) and can_be_changed: + private_attributes[var_name] = PrivateAttr(default=value) + elif is_valid_field(var_name) and var_name not in annotations and can_be_changed: + validate_field_name(bases, var_name) + inferred = ModelField.infer( + name=var_name, + value=value, + annotation=annotations.get(var_name, Undefined), + class_validators=vg.get_validators(var_name), + config=config, + ) + if var_name in fields: + if lenient_issubclass(inferred.type_, fields[var_name].type_): + inferred.type_ = fields[var_name].type_ + else: + raise TypeError( + f'The type of {name}.{var_name} differs from the new default value; ' + f'if you wish to change the type of this field, please use a type annotation' + ) + fields[var_name] = inferred + + _custom_root_type = ROOT_KEY in fields + if _custom_root_type: + validate_custom_root_type(fields) + vg.check_for_unused() + if config.json_encoders: + json_encoder = partial(custom_pydantic_encoder, config.json_encoders) + else: + json_encoder = pydantic_encoder + pre_rv_new, post_rv_new = extract_root_validators(namespace) + + if hash_func is None: + hash_func = generate_hash_function(config.frozen) + + exclude_from_namespace = fields | private_attributes.keys() | {'__slots__'} + new_namespace = { + '__config__': config, + '__fields__': fields, + '__exclude_fields__': { + name: field.field_info.exclude for name, field in fields.items() if field.field_info.exclude is not None + } + or None, + '__include_fields__': { + name: field.field_info.include for name, field in fields.items() if field.field_info.include is not None + } + or None, + '__validators__': vg.validators, + '__pre_root_validators__': unique_list( + pre_root_validators + pre_rv_new, + name_factory=lambda v: v.__name__, + ), + '__post_root_validators__': unique_list( + post_root_validators + post_rv_new, + name_factory=lambda skip_on_failure_and_v: skip_on_failure_and_v[1].__name__, + ), + '__schema_cache__': {}, + '__json_encoder__': staticmethod(json_encoder), + '__custom_root_type__': _custom_root_type, + '__private_attributes__': {**base_private_attributes, **private_attributes}, + '__slots__': slots | private_attributes.keys(), + '__hash__': hash_func, + '__class_vars__': class_vars, + **{n: v for n, v in namespace.items() if n not in exclude_from_namespace}, + } + + cls = super().__new__(mcs, name, bases, new_namespace, **kwargs) + # set __signature__ attr only for model class, but not for its instances + cls.__signature__ = ClassAttribute('__signature__', generate_model_signature(cls.__init__, fields, config)) + if resolve_forward_refs: + cls.__try_update_forward_refs__() + + # preserve `__set_name__` protocol defined in https://peps.python.org/pep-0487 + # for attributes not in `new_namespace` (e.g. private attributes) + for name, obj in namespace.items(): + if name not in new_namespace: + set_name = getattr(obj, '__set_name__', None) + if callable(set_name): + set_name(cls, name) + + return cls + + def __instancecheck__(self, instance: Any) -> bool: + """ + Avoid calling ABC _abc_subclasscheck unless we're pretty sure. + + See #3829 and python/cpython#92810 + """ + return hasattr(instance, '__fields__') and super().__instancecheck__(instance) + + +object_setattr = object.__setattr__ + + +class BaseModel(Representation, metaclass=ModelMetaclass): + if TYPE_CHECKING: + # populated by the metaclass, defined here to help IDEs only + __fields__: ClassVar[Dict[str, ModelField]] = {} + __include_fields__: ClassVar[Optional[Mapping[str, Any]]] = None + __exclude_fields__: ClassVar[Optional[Mapping[str, Any]]] = None + __validators__: ClassVar[Dict[str, AnyCallable]] = {} + __pre_root_validators__: ClassVar[List[AnyCallable]] + __post_root_validators__: ClassVar[List[Tuple[bool, AnyCallable]]] + __config__: ClassVar[Type[BaseConfig]] = BaseConfig + __json_encoder__: ClassVar[Callable[[Any], Any]] = lambda x: x + __schema_cache__: ClassVar['DictAny'] = {} + __custom_root_type__: ClassVar[bool] = False + __signature__: ClassVar['Signature'] + __private_attributes__: ClassVar[Dict[str, ModelPrivateAttr]] + __class_vars__: ClassVar[SetStr] + __fields_set__: ClassVar[SetStr] = set() + + Config = BaseConfig + __slots__ = ('__dict__', '__fields_set__') + __doc__ = '' # Null out the Representation docstring + + def __init__(__pydantic_self__, **data: Any) -> None: + """ + Create a new model by parsing and validating input data from keyword arguments. + + Raises ValidationError if the input data cannot be parsed to form a valid model. + """ + # Uses something other than `self` the first arg to allow "self" as a settable attribute + values, fields_set, validation_error = validate_model(__pydantic_self__.__class__, data) + if validation_error: + raise validation_error + try: + object_setattr(__pydantic_self__, '__dict__', values) + except TypeError as e: + raise TypeError( + 'Model values must be a dict; you may not have returned a dictionary from a root validator' + ) from e + object_setattr(__pydantic_self__, '__fields_set__', fields_set) + __pydantic_self__._init_private_attributes() + + @no_type_check + def __setattr__(self, name, value): # noqa: C901 (ignore complexity) + if name in self.__private_attributes__ or name in DUNDER_ATTRIBUTES: + return object_setattr(self, name, value) + + if self.__config__.extra is not Extra.allow and name not in self.__fields__: + raise ValueError(f'"{self.__class__.__name__}" object has no field "{name}"') + elif not self.__config__.allow_mutation or self.__config__.frozen: + raise TypeError(f'"{self.__class__.__name__}" is immutable and does not support item assignment') + elif name in self.__fields__ and self.__fields__[name].final: + raise TypeError( + f'"{self.__class__.__name__}" object "{name}" field is final and does not support reassignment' + ) + elif self.__config__.validate_assignment: + new_values = {**self.__dict__, name: value} + + for validator in self.__pre_root_validators__: + try: + new_values = validator(self.__class__, new_values) + except (ValueError, TypeError, AssertionError) as exc: + raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], self.__class__) + + known_field = self.__fields__.get(name, None) + if known_field: + # We want to + # - make sure validators are called without the current value for this field inside `values` + # - keep other values (e.g. submodels) untouched (using `BaseModel.dict()` will change them into dicts) + # - keep the order of the fields + if not known_field.field_info.allow_mutation: + raise TypeError(f'"{known_field.name}" has allow_mutation set to False and cannot be assigned') + dict_without_original_value = {k: v for k, v in self.__dict__.items() if k != name} + value, error_ = known_field.validate(value, dict_without_original_value, loc=name, cls=self.__class__) + if error_: + raise ValidationError([error_], self.__class__) + else: + new_values[name] = value + + errors = [] + for skip_on_failure, validator in self.__post_root_validators__: + if skip_on_failure and errors: + continue + try: + new_values = validator(self.__class__, new_values) + except (ValueError, TypeError, AssertionError) as exc: + errors.append(ErrorWrapper(exc, loc=ROOT_KEY)) + if errors: + raise ValidationError(errors, self.__class__) + + # update the whole __dict__ as other values than just `value` + # may be changed (e.g. with `root_validator`) + object_setattr(self, '__dict__', new_values) + else: + self.__dict__[name] = value + + self.__fields_set__.add(name) + + def __getstate__(self) -> 'DictAny': + private_attrs = ((k, getattr(self, k, Undefined)) for k in self.__private_attributes__) + return { + '__dict__': self.__dict__, + '__fields_set__': self.__fields_set__, + '__private_attribute_values__': {k: v for k, v in private_attrs if v is not Undefined}, + } + + def __setstate__(self, state: 'DictAny') -> None: + object_setattr(self, '__dict__', state['__dict__']) + object_setattr(self, '__fields_set__', state['__fields_set__']) + for name, value in state.get('__private_attribute_values__', {}).items(): + object_setattr(self, name, value) + + def _init_private_attributes(self) -> None: + for name, private_attr in self.__private_attributes__.items(): + default = private_attr.get_default() + if default is not Undefined: + object_setattr(self, name, default) + + def dict( + self, + *, + include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, + exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, + by_alias: bool = False, + skip_defaults: Optional[bool] = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> 'DictStrAny': + """ + Generate a dictionary representation of the model, optionally specifying which fields to include or exclude. + + """ + if skip_defaults is not None: + warnings.warn( + f'{self.__class__.__name__}.dict(): "skip_defaults" is deprecated and replaced by "exclude_unset"', + DeprecationWarning, + ) + exclude_unset = skip_defaults + + return dict( + self._iter( + to_dict=True, + by_alias=by_alias, + include=include, + exclude=exclude, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + ) + + def json( + self, + *, + include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, + exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, + by_alias: bool = False, + skip_defaults: Optional[bool] = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + encoder: Optional[Callable[[Any], Any]] = None, + models_as_dict: bool = True, + **dumps_kwargs: Any, + ) -> str: + """ + Generate a JSON representation of the model, `include` and `exclude` arguments as per `dict()`. + + `encoder` is an optional function to supply as `default` to json.dumps(), other arguments as per `json.dumps()`. + """ + if skip_defaults is not None: + warnings.warn( + f'{self.__class__.__name__}.json(): "skip_defaults" is deprecated and replaced by "exclude_unset"', + DeprecationWarning, + ) + exclude_unset = skip_defaults + encoder = cast(Callable[[Any], Any], encoder or self.__json_encoder__) + + # We don't directly call `self.dict()`, which does exactly this with `to_dict=True` + # because we want to be able to keep raw `BaseModel` instances and not as `dict`. + # This allows users to write custom JSON encoders for given `BaseModel` classes. + data = dict( + self._iter( + to_dict=models_as_dict, + by_alias=by_alias, + include=include, + exclude=exclude, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + ) + if self.__custom_root_type__: + data = data[ROOT_KEY] + return self.__config__.json_dumps(data, default=encoder, **dumps_kwargs) + + @classmethod + def _enforce_dict_if_root(cls, obj: Any) -> Any: + if cls.__custom_root_type__ and ( + not (isinstance(obj, dict) and obj.keys() == {ROOT_KEY}) + and not (isinstance(obj, BaseModel) and obj.__fields__.keys() == {ROOT_KEY}) + or cls.__fields__[ROOT_KEY].shape in MAPPING_LIKE_SHAPES + ): + return {ROOT_KEY: obj} + else: + return obj + + @classmethod + def parse_obj(cls: Type['Model'], obj: Any) -> 'Model': + obj = cls._enforce_dict_if_root(obj) + if not isinstance(obj, dict): + try: + obj = dict(obj) + except (TypeError, ValueError) as e: + exc = TypeError(f'{cls.__name__} expected dict not {obj.__class__.__name__}') + raise ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls) from e + return cls(**obj) + + @classmethod + def parse_raw( + cls: Type['Model'], + b: StrBytes, + *, + content_type: str = None, + encoding: str = 'utf8', + proto: Protocol = None, + allow_pickle: bool = False, + ) -> 'Model': + try: + obj = load_str_bytes( + b, + proto=proto, + content_type=content_type, + encoding=encoding, + allow_pickle=allow_pickle, + json_loads=cls.__config__.json_loads, + ) + except (ValueError, TypeError, UnicodeDecodeError) as e: + raise ValidationError([ErrorWrapper(e, loc=ROOT_KEY)], cls) + return cls.parse_obj(obj) + + @classmethod + def parse_file( + cls: Type['Model'], + path: Union[str, Path], + *, + content_type: str = None, + encoding: str = 'utf8', + proto: Protocol = None, + allow_pickle: bool = False, + ) -> 'Model': + obj = load_file( + path, + proto=proto, + content_type=content_type, + encoding=encoding, + allow_pickle=allow_pickle, + json_loads=cls.__config__.json_loads, + ) + return cls.parse_obj(obj) + + @classmethod + def from_orm(cls: Type['Model'], obj: Any) -> 'Model': + if not cls.__config__.orm_mode: + raise ConfigError('You must have the config attribute orm_mode=True to use from_orm') + obj = {ROOT_KEY: obj} if cls.__custom_root_type__ else cls._decompose_class(obj) + m = cls.__new__(cls) + values, fields_set, validation_error = validate_model(cls, obj) + if validation_error: + raise validation_error + object_setattr(m, '__dict__', values) + object_setattr(m, '__fields_set__', fields_set) + m._init_private_attributes() + return m + + @classmethod + def construct(cls: Type['Model'], _fields_set: Optional['SetStr'] = None, **values: Any) -> 'Model': + """ + Creates a new model setting __dict__ and __fields_set__ from trusted or pre-validated data. + Default values are respected, but no other validation is performed. + Behaves as if `Config.extra = 'allow'` was set since it adds all passed values + """ + m = cls.__new__(cls) + fields_values: Dict[str, Any] = {} + for name, field in cls.__fields__.items(): + if field.alt_alias and field.alias in values: + fields_values[name] = values[field.alias] + elif name in values: + fields_values[name] = values[name] + elif not field.required: + fields_values[name] = field.get_default() + fields_values.update(values) + object_setattr(m, '__dict__', fields_values) + if _fields_set is None: + _fields_set = set(values.keys()) + object_setattr(m, '__fields_set__', _fields_set) + m._init_private_attributes() + return m + + def _copy_and_set_values(self: 'Model', values: 'DictStrAny', fields_set: 'SetStr', *, deep: bool) -> 'Model': + if deep: + # chances of having empty dict here are quite low for using smart_deepcopy + values = deepcopy(values) + + cls = self.__class__ + m = cls.__new__(cls) + object_setattr(m, '__dict__', values) + object_setattr(m, '__fields_set__', fields_set) + for name in self.__private_attributes__: + value = getattr(self, name, Undefined) + if value is not Undefined: + if deep: + value = deepcopy(value) + object_setattr(m, name, value) + + return m + + def copy( + self: 'Model', + *, + include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, + exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, + update: Optional['DictStrAny'] = None, + deep: bool = False, + ) -> 'Model': + """ + Duplicate a model, optionally choose which fields to include, exclude and change. + + :param include: fields to include in new model + :param exclude: fields to exclude from new model, as with values this takes precedence over include + :param update: values to change/add in the new model. Note: the data is not validated before creating + the new model: you should trust this data + :param deep: set to `True` to make a deep copy of the model + :return: new model instance + """ + + values = dict( + self._iter(to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False), + **(update or {}), + ) + + # new `__fields_set__` can have unset optional fields with a set value in `update` kwarg + if update: + fields_set = self.__fields_set__ | update.keys() + else: + fields_set = set(self.__fields_set__) + + return self._copy_and_set_values(values, fields_set, deep=deep) + + @classmethod + def schema(cls, by_alias: bool = True, ref_template: str = default_ref_template) -> 'DictStrAny': + cached = cls.__schema_cache__.get((by_alias, ref_template)) + if cached is not None: + return cached + s = model_schema(cls, by_alias=by_alias, ref_template=ref_template) + cls.__schema_cache__[(by_alias, ref_template)] = s + return s + + @classmethod + def schema_json( + cls, *, by_alias: bool = True, ref_template: str = default_ref_template, **dumps_kwargs: Any + ) -> str: + from pydantic.v1.json import pydantic_encoder + + return cls.__config__.json_dumps( + cls.schema(by_alias=by_alias, ref_template=ref_template), default=pydantic_encoder, **dumps_kwargs + ) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + + @classmethod + def validate(cls: Type['Model'], value: Any) -> 'Model': + if isinstance(value, cls): + copy_on_model_validation = cls.__config__.copy_on_model_validation + # whether to deep or shallow copy the model on validation, None means do not copy + deep_copy: Optional[bool] = None + if copy_on_model_validation not in {'deep', 'shallow', 'none'}: + # Warn about deprecated behavior + warnings.warn( + "`copy_on_model_validation` should be a string: 'deep', 'shallow' or 'none'", DeprecationWarning + ) + if copy_on_model_validation: + deep_copy = False + + if copy_on_model_validation == 'shallow': + # shallow copy + deep_copy = False + elif copy_on_model_validation == 'deep': + # deep copy + deep_copy = True + + if deep_copy is None: + return value + else: + return value._copy_and_set_values(value.__dict__, value.__fields_set__, deep=deep_copy) + + value = cls._enforce_dict_if_root(value) + + if isinstance(value, dict): + return cls(**value) + elif cls.__config__.orm_mode: + return cls.from_orm(value) + else: + try: + value_as_dict = dict(value) + except (TypeError, ValueError) as e: + raise DictError() from e + return cls(**value_as_dict) + + @classmethod + def _decompose_class(cls: Type['Model'], obj: Any) -> GetterDict: + if isinstance(obj, GetterDict): + return obj + return cls.__config__.getter_dict(obj) + + @classmethod + @no_type_check + def _get_value( + cls, + v: Any, + to_dict: bool, + by_alias: bool, + include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']], + exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']], + exclude_unset: bool, + exclude_defaults: bool, + exclude_none: bool, + ) -> Any: + if isinstance(v, BaseModel): + if to_dict: + v_dict = v.dict( + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + include=include, + exclude=exclude, + exclude_none=exclude_none, + ) + if ROOT_KEY in v_dict: + return v_dict[ROOT_KEY] + return v_dict + else: + return v.copy(include=include, exclude=exclude) + + value_exclude = ValueItems(v, exclude) if exclude else None + value_include = ValueItems(v, include) if include else None + + if isinstance(v, dict): + return { + k_: cls._get_value( + v_, + to_dict=to_dict, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + include=value_include and value_include.for_element(k_), + exclude=value_exclude and value_exclude.for_element(k_), + exclude_none=exclude_none, + ) + for k_, v_ in v.items() + if (not value_exclude or not value_exclude.is_excluded(k_)) + and (not value_include or value_include.is_included(k_)) + } + + elif sequence_like(v): + seq_args = ( + cls._get_value( + v_, + to_dict=to_dict, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + include=value_include and value_include.for_element(i), + exclude=value_exclude and value_exclude.for_element(i), + exclude_none=exclude_none, + ) + for i, v_ in enumerate(v) + if (not value_exclude or not value_exclude.is_excluded(i)) + and (not value_include or value_include.is_included(i)) + ) + + return v.__class__(*seq_args) if is_namedtuple(v.__class__) else v.__class__(seq_args) + + elif isinstance(v, Enum) and getattr(cls.Config, 'use_enum_values', False): + return v.value + + else: + return v + + @classmethod + def __try_update_forward_refs__(cls, **localns: Any) -> None: + """ + Same as update_forward_refs but will not raise exception + when forward references are not defined. + """ + update_model_forward_refs(cls, cls.__fields__.values(), cls.__config__.json_encoders, localns, (NameError,)) + + @classmethod + def update_forward_refs(cls, **localns: Any) -> None: + """ + Try to update ForwardRefs on fields based on this Model, globalns and localns. + """ + update_model_forward_refs(cls, cls.__fields__.values(), cls.__config__.json_encoders, localns) + + def __iter__(self) -> 'TupleGenerator': + """ + so `dict(model)` works + """ + yield from self.__dict__.items() + + def _iter( + self, + to_dict: bool = False, + by_alias: bool = False, + include: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, + exclude: Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']] = None, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + ) -> 'TupleGenerator': + # Merge field set excludes with explicit exclude parameter with explicit overriding field set options. + # The extra "is not None" guards are not logically necessary but optimizes performance for the simple case. + if exclude is not None or self.__exclude_fields__ is not None: + exclude = ValueItems.merge(self.__exclude_fields__, exclude) + + if include is not None or self.__include_fields__ is not None: + include = ValueItems.merge(self.__include_fields__, include, intersect=True) + + allowed_keys = self._calculate_keys( + include=include, exclude=exclude, exclude_unset=exclude_unset # type: ignore + ) + if allowed_keys is None and not (to_dict or by_alias or exclude_unset or exclude_defaults or exclude_none): + # huge boost for plain _iter() + yield from self.__dict__.items() + return + + value_exclude = ValueItems(self, exclude) if exclude is not None else None + value_include = ValueItems(self, include) if include is not None else None + + for field_key, v in self.__dict__.items(): + if (allowed_keys is not None and field_key not in allowed_keys) or (exclude_none and v is None): + continue + + if exclude_defaults: + model_field = self.__fields__.get(field_key) + if not getattr(model_field, 'required', True) and getattr(model_field, 'default', _missing) == v: + continue + + if by_alias and field_key in self.__fields__: + dict_key = self.__fields__[field_key].alias + else: + dict_key = field_key + + if to_dict or value_include or value_exclude: + v = self._get_value( + v, + to_dict=to_dict, + by_alias=by_alias, + include=value_include and value_include.for_element(field_key), + exclude=value_exclude and value_exclude.for_element(field_key), + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + ) + yield dict_key, v + + def _calculate_keys( + self, + include: Optional['MappingIntStrAny'], + exclude: Optional['MappingIntStrAny'], + exclude_unset: bool, + update: Optional['DictStrAny'] = None, + ) -> Optional[AbstractSet[str]]: + if include is None and exclude is None and exclude_unset is False: + return None + + keys: AbstractSet[str] + if exclude_unset: + keys = self.__fields_set__.copy() + else: + keys = self.__dict__.keys() + + if include is not None: + keys &= include.keys() + + if update: + keys -= update.keys() + + if exclude: + keys -= {k for k, v in exclude.items() if ValueItems.is_true(v)} + + return keys + + def __eq__(self, other: Any) -> bool: + if isinstance(other, BaseModel): + return self.dict() == other.dict() + else: + return self.dict() == other + + def __repr_args__(self) -> 'ReprArgs': + return [ + (k, v) + for k, v in self.__dict__.items() + if k not in DUNDER_ATTRIBUTES and (k not in self.__fields__ or self.__fields__[k].field_info.repr) + ] + + +_is_base_model_class_defined = True + + +@overload +def create_model( + __model_name: str, + *, + __config__: Optional[Type[BaseConfig]] = None, + __base__: None = None, + __module__: str = __name__, + __validators__: Dict[str, 'AnyClassMethod'] = None, + __cls_kwargs__: Dict[str, Any] = None, + **field_definitions: Any, +) -> Type['BaseModel']: + ... + + +@overload +def create_model( + __model_name: str, + *, + __config__: Optional[Type[BaseConfig]] = None, + __base__: Union[Type['Model'], Tuple[Type['Model'], ...]], + __module__: str = __name__, + __validators__: Dict[str, 'AnyClassMethod'] = None, + __cls_kwargs__: Dict[str, Any] = None, + **field_definitions: Any, +) -> Type['Model']: + ... + + +def create_model( + __model_name: str, + *, + __config__: Optional[Type[BaseConfig]] = None, + __base__: Union[None, Type['Model'], Tuple[Type['Model'], ...]] = None, + __module__: str = __name__, + __validators__: Dict[str, 'AnyClassMethod'] = None, + __cls_kwargs__: Dict[str, Any] = None, + __slots__: Optional[Tuple[str, ...]] = None, + **field_definitions: Any, +) -> Type['Model']: + """ + Dynamically create a model. + :param __model_name: name of the created model + :param __config__: config class to use for the new model + :param __base__: base class for the new model to inherit from + :param __module__: module of the created model + :param __validators__: a dict of method names and @validator class methods + :param __cls_kwargs__: a dict for class creation + :param __slots__: Deprecated, `__slots__` should not be passed to `create_model` + :param field_definitions: fields of the model (or extra fields if a base is supplied) + in the format `=(, )` or `=, e.g. + `foobar=(str, ...)` or `foobar=123`, or, for complex use-cases, in the format + `=` or `=(, )`, e.g. + `foo=Field(datetime, default_factory=datetime.utcnow, alias='bar')` or + `foo=(str, FieldInfo(title='Foo'))` + """ + if __slots__ is not None: + # __slots__ will be ignored from here on + warnings.warn('__slots__ should not be passed to create_model', RuntimeWarning) + + if __base__ is not None: + if __config__ is not None: + raise ConfigError('to avoid confusion __config__ and __base__ cannot be used together') + if not isinstance(__base__, tuple): + __base__ = (__base__,) + else: + __base__ = (cast(Type['Model'], BaseModel),) + + __cls_kwargs__ = __cls_kwargs__ or {} + + fields = {} + annotations = {} + + for f_name, f_def in field_definitions.items(): + if not is_valid_field(f_name): + warnings.warn(f'fields may not start with an underscore, ignoring "{f_name}"', RuntimeWarning) + if isinstance(f_def, tuple): + try: + f_annotation, f_value = f_def + except ValueError as e: + raise ConfigError( + 'field definitions should either be a tuple of (, ) or just a ' + 'default value, unfortunately this means tuples as ' + 'default values are not allowed' + ) from e + else: + f_annotation, f_value = None, f_def + + if f_annotation: + annotations[f_name] = f_annotation + fields[f_name] = f_value + + namespace: 'DictStrAny' = {'__annotations__': annotations, '__module__': __module__} + if __validators__: + namespace.update(__validators__) + namespace.update(fields) + if __config__: + namespace['Config'] = inherit_config(__config__, BaseConfig) + resolved_bases = resolve_bases(__base__) + meta, ns, kwds = prepare_class(__model_name, resolved_bases, kwds=__cls_kwargs__) + if resolved_bases is not __base__: + ns['__orig_bases__'] = __base__ + namespace.update(ns) + return meta(__model_name, resolved_bases, namespace, **kwds) + + +_missing = object() + + +def validate_model( # noqa: C901 (ignore complexity) + model: Type[BaseModel], input_data: 'DictStrAny', cls: 'ModelOrDc' = None +) -> Tuple['DictStrAny', 'SetStr', Optional[ValidationError]]: + """ + validate data against a model. + """ + values = {} + errors = [] + # input_data names, possibly alias + names_used = set() + # field names, never aliases + fields_set = set() + config = model.__config__ + check_extra = config.extra is not Extra.ignore + cls_ = cls or model + + for validator in model.__pre_root_validators__: + try: + input_data = validator(cls_, input_data) + except (ValueError, TypeError, AssertionError) as exc: + return {}, set(), ValidationError([ErrorWrapper(exc, loc=ROOT_KEY)], cls_) + + for name, field in model.__fields__.items(): + value = input_data.get(field.alias, _missing) + using_name = False + if value is _missing and config.allow_population_by_field_name and field.alt_alias: + value = input_data.get(field.name, _missing) + using_name = True + + if value is _missing: + if field.required: + errors.append(ErrorWrapper(MissingError(), loc=field.alias)) + continue + + value = field.get_default() + + if not config.validate_all and not field.validate_always: + values[name] = value + continue + else: + fields_set.add(name) + if check_extra: + names_used.add(field.name if using_name else field.alias) + + v_, errors_ = field.validate(value, values, loc=field.alias, cls=cls_) + if isinstance(errors_, ErrorWrapper): + errors.append(errors_) + elif isinstance(errors_, list): + errors.extend(errors_) + else: + values[name] = v_ + + if check_extra: + if isinstance(input_data, GetterDict): + extra = input_data.extra_keys() - names_used + else: + extra = input_data.keys() - names_used + if extra: + fields_set |= extra + if config.extra is Extra.allow: + for f in extra: + values[f] = input_data[f] + else: + for f in sorted(extra): + errors.append(ErrorWrapper(ExtraError(), loc=f)) + + for skip_on_failure, validator in model.__post_root_validators__: + if skip_on_failure and errors: + continue + try: + values = validator(cls_, values) + except (ValueError, TypeError, AssertionError) as exc: + errors.append(ErrorWrapper(exc, loc=ROOT_KEY)) + + if errors: + return values, fields_set, ValidationError(errors, cls_) + else: + return values, fields_set, None diff --git a/env/Lib/site-packages/pydantic/v1/mypy.py b/env/Lib/site-packages/pydantic/v1/mypy.py new file mode 100644 index 0000000..20fc039 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/mypy.py @@ -0,0 +1,945 @@ +import sys +from configparser import ConfigParser +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type as TypingType, Union + +from mypy.errorcodes import ErrorCode +from mypy.nodes import ( + ARG_NAMED, + ARG_NAMED_OPT, + ARG_OPT, + ARG_POS, + ARG_STAR2, + MDEF, + Argument, + AssignmentStmt, + Block, + CallExpr, + ClassDef, + Context, + Decorator, + EllipsisExpr, + FuncBase, + FuncDef, + JsonDict, + MemberExpr, + NameExpr, + PassStmt, + PlaceholderNode, + RefExpr, + StrExpr, + SymbolNode, + SymbolTableNode, + TempNode, + TypeInfo, + TypeVarExpr, + Var, +) +from mypy.options import Options +from mypy.plugin import ( + CheckerPluginInterface, + ClassDefContext, + FunctionContext, + MethodContext, + Plugin, + ReportConfigContext, + SemanticAnalyzerPluginInterface, +) +from mypy.plugins import dataclasses +from mypy.semanal import set_callable_name # type: ignore +from mypy.server.trigger import make_wildcard_trigger +from mypy.types import ( + AnyType, + CallableType, + Instance, + NoneType, + Overloaded, + ProperType, + Type, + TypeOfAny, + TypeType, + TypeVarId, + TypeVarType, + UnionType, + get_proper_type, +) +from mypy.typevars import fill_typevars +from mypy.util import get_unique_redefinition_name +from mypy.version import __version__ as mypy_version + +from pydantic.v1.utils import is_valid_field + +try: + from mypy.types import TypeVarDef # type: ignore[attr-defined] +except ImportError: # pragma: no cover + # Backward-compatible with TypeVarDef from Mypy 0.910. + from mypy.types import TypeVarType as TypeVarDef + +CONFIGFILE_KEY = 'pydantic-mypy' +METADATA_KEY = 'pydantic-mypy-metadata' +_NAMESPACE = __name__[:-5] # 'pydantic' in 1.10.X, 'pydantic.v1' in v2.X +BASEMODEL_FULLNAME = f'{_NAMESPACE}.main.BaseModel' +BASESETTINGS_FULLNAME = f'{_NAMESPACE}.env_settings.BaseSettings' +MODEL_METACLASS_FULLNAME = f'{_NAMESPACE}.main.ModelMetaclass' +FIELD_FULLNAME = f'{_NAMESPACE}.fields.Field' +DATACLASS_FULLNAME = f'{_NAMESPACE}.dataclasses.dataclass' + + +def parse_mypy_version(version: str) -> Tuple[int, ...]: + return tuple(map(int, version.partition('+')[0].split('.'))) + + +MYPY_VERSION_TUPLE = parse_mypy_version(mypy_version) +BUILTINS_NAME = 'builtins' if MYPY_VERSION_TUPLE >= (0, 930) else '__builtins__' + +# Increment version if plugin changes and mypy caches should be invalidated +__version__ = 2 + + +def plugin(version: str) -> 'TypingType[Plugin]': + """ + `version` is the mypy version string + + We might want to use this to print a warning if the mypy version being used is + newer, or especially older, than we expect (or need). + """ + return PydanticPlugin + + +class PydanticPlugin(Plugin): + def __init__(self, options: Options) -> None: + self.plugin_config = PydanticPluginConfig(options) + self._plugin_data = self.plugin_config.to_data() + super().__init__(options) + + def get_base_class_hook(self, fullname: str) -> 'Optional[Callable[[ClassDefContext], None]]': + sym = self.lookup_fully_qualified(fullname) + if sym and isinstance(sym.node, TypeInfo): # pragma: no branch + # No branching may occur if the mypy cache has not been cleared + if any(get_fullname(base) == BASEMODEL_FULLNAME for base in sym.node.mro): + return self._pydantic_model_class_maker_callback + return None + + def get_metaclass_hook(self, fullname: str) -> Optional[Callable[[ClassDefContext], None]]: + if fullname == MODEL_METACLASS_FULLNAME: + return self._pydantic_model_metaclass_marker_callback + return None + + def get_function_hook(self, fullname: str) -> 'Optional[Callable[[FunctionContext], Type]]': + sym = self.lookup_fully_qualified(fullname) + if sym and sym.fullname == FIELD_FULLNAME: + return self._pydantic_field_callback + return None + + def get_method_hook(self, fullname: str) -> Optional[Callable[[MethodContext], Type]]: + if fullname.endswith('.from_orm'): + return from_orm_callback + return None + + def get_class_decorator_hook(self, fullname: str) -> Optional[Callable[[ClassDefContext], None]]: + """Mark pydantic.dataclasses as dataclass. + + Mypy version 1.1.1 added support for `@dataclass_transform` decorator. + """ + if fullname == DATACLASS_FULLNAME and MYPY_VERSION_TUPLE < (1, 1): + return dataclasses.dataclass_class_maker_callback # type: ignore[return-value] + return None + + def report_config_data(self, ctx: ReportConfigContext) -> Dict[str, Any]: + """Return all plugin config data. + + Used by mypy to determine if cache needs to be discarded. + """ + return self._plugin_data + + def _pydantic_model_class_maker_callback(self, ctx: ClassDefContext) -> None: + transformer = PydanticModelTransformer(ctx, self.plugin_config) + transformer.transform() + + def _pydantic_model_metaclass_marker_callback(self, ctx: ClassDefContext) -> None: + """Reset dataclass_transform_spec attribute of ModelMetaclass. + + Let the plugin handle it. This behavior can be disabled + if 'debug_dataclass_transform' is set to True', for testing purposes. + """ + if self.plugin_config.debug_dataclass_transform: + return + info_metaclass = ctx.cls.info.declared_metaclass + assert info_metaclass, "callback not passed from 'get_metaclass_hook'" + if getattr(info_metaclass.type, 'dataclass_transform_spec', None): + info_metaclass.type.dataclass_transform_spec = None # type: ignore[attr-defined] + + def _pydantic_field_callback(self, ctx: FunctionContext) -> 'Type': + """ + Extract the type of the `default` argument from the Field function, and use it as the return type. + + In particular: + * Check whether the default and default_factory argument is specified. + * Output an error if both are specified. + * Retrieve the type of the argument which is specified, and use it as return type for the function. + """ + default_any_type = ctx.default_return_type + + assert ctx.callee_arg_names[0] == 'default', '"default" is no longer first argument in Field()' + assert ctx.callee_arg_names[1] == 'default_factory', '"default_factory" is no longer second argument in Field()' + default_args = ctx.args[0] + default_factory_args = ctx.args[1] + + if default_args and default_factory_args: + error_default_and_default_factory_specified(ctx.api, ctx.context) + return default_any_type + + if default_args: + default_type = ctx.arg_types[0][0] + default_arg = default_args[0] + + # Fallback to default Any type if the field is required + if not isinstance(default_arg, EllipsisExpr): + return default_type + + elif default_factory_args: + default_factory_type = ctx.arg_types[1][0] + + # Functions which use `ParamSpec` can be overloaded, exposing the callable's types as a parameter + # Pydantic calls the default factory without any argument, so we retrieve the first item + if isinstance(default_factory_type, Overloaded): + if MYPY_VERSION_TUPLE > (0, 910): + default_factory_type = default_factory_type.items[0] + else: + # Mypy0.910 exposes the items of overloaded types in a function + default_factory_type = default_factory_type.items()[0] # type: ignore[operator] + + if isinstance(default_factory_type, CallableType): + ret_type = default_factory_type.ret_type + # mypy doesn't think `ret_type` has `args`, you'd think mypy should know, + # add this check in case it varies by version + args = getattr(ret_type, 'args', None) + if args: + if all(isinstance(arg, TypeVarType) for arg in args): + # Looks like the default factory is a type like `list` or `dict`, replace all args with `Any` + ret_type.args = tuple(default_any_type for _ in args) # type: ignore[attr-defined] + return ret_type + + return default_any_type + + +class PydanticPluginConfig: + __slots__ = ( + 'init_forbid_extra', + 'init_typed', + 'warn_required_dynamic_aliases', + 'warn_untyped_fields', + 'debug_dataclass_transform', + ) + init_forbid_extra: bool + init_typed: bool + warn_required_dynamic_aliases: bool + warn_untyped_fields: bool + debug_dataclass_transform: bool # undocumented + + def __init__(self, options: Options) -> None: + if options.config_file is None: # pragma: no cover + return + + toml_config = parse_toml(options.config_file) + if toml_config is not None: + config = toml_config.get('tool', {}).get('pydantic-mypy', {}) + for key in self.__slots__: + setting = config.get(key, False) + if not isinstance(setting, bool): + raise ValueError(f'Configuration value must be a boolean for key: {key}') + setattr(self, key, setting) + else: + plugin_config = ConfigParser() + plugin_config.read(options.config_file) + for key in self.__slots__: + setting = plugin_config.getboolean(CONFIGFILE_KEY, key, fallback=False) + setattr(self, key, setting) + + def to_data(self) -> Dict[str, Any]: + return {key: getattr(self, key) for key in self.__slots__} + + +def from_orm_callback(ctx: MethodContext) -> Type: + """ + Raise an error if orm_mode is not enabled + """ + model_type: Instance + ctx_type = ctx.type + if isinstance(ctx_type, TypeType): + ctx_type = ctx_type.item + if isinstance(ctx_type, CallableType) and isinstance(ctx_type.ret_type, Instance): + model_type = ctx_type.ret_type # called on the class + elif isinstance(ctx_type, Instance): + model_type = ctx_type # called on an instance (unusual, but still valid) + else: # pragma: no cover + detail = f'ctx.type: {ctx_type} (of type {ctx_type.__class__.__name__})' + error_unexpected_behavior(detail, ctx.api, ctx.context) + return ctx.default_return_type + pydantic_metadata = model_type.type.metadata.get(METADATA_KEY) + if pydantic_metadata is None: + return ctx.default_return_type + orm_mode = pydantic_metadata.get('config', {}).get('orm_mode') + if orm_mode is not True: + error_from_orm(get_name(model_type.type), ctx.api, ctx.context) + return ctx.default_return_type + + +class PydanticModelTransformer: + tracked_config_fields: Set[str] = { + 'extra', + 'allow_mutation', + 'frozen', + 'orm_mode', + 'allow_population_by_field_name', + 'alias_generator', + } + + def __init__(self, ctx: ClassDefContext, plugin_config: PydanticPluginConfig) -> None: + self._ctx = ctx + self.plugin_config = plugin_config + + def transform(self) -> None: + """ + Configures the BaseModel subclass according to the plugin settings. + + In particular: + * determines the model config and fields, + * adds a fields-aware signature for the initializer and construct methods + * freezes the class if allow_mutation = False or frozen = True + * stores the fields, config, and if the class is settings in the mypy metadata for access by subclasses + """ + ctx = self._ctx + info = ctx.cls.info + + self.adjust_validator_signatures() + config = self.collect_config() + fields = self.collect_fields(config) + is_settings = any(get_fullname(base) == BASESETTINGS_FULLNAME for base in info.mro[:-1]) + self.add_initializer(fields, config, is_settings) + self.add_construct_method(fields) + self.set_frozen(fields, frozen=config.allow_mutation is False or config.frozen is True) + info.metadata[METADATA_KEY] = { + 'fields': {field.name: field.serialize() for field in fields}, + 'config': config.set_values_dict(), + } + + def adjust_validator_signatures(self) -> None: + """When we decorate a function `f` with `pydantic.validator(...), mypy sees + `f` as a regular method taking a `self` instance, even though pydantic + internally wraps `f` with `classmethod` if necessary. + + Teach mypy this by marking any function whose outermost decorator is a + `validator()` call as a classmethod. + """ + for name, sym in self._ctx.cls.info.names.items(): + if isinstance(sym.node, Decorator): + first_dec = sym.node.original_decorators[0] + if ( + isinstance(first_dec, CallExpr) + and isinstance(first_dec.callee, NameExpr) + and first_dec.callee.fullname == f'{_NAMESPACE}.class_validators.validator' + ): + sym.node.func.is_class = True + + def collect_config(self) -> 'ModelConfigData': + """ + Collects the values of the config attributes that are used by the plugin, accounting for parent classes. + """ + ctx = self._ctx + cls = ctx.cls + config = ModelConfigData() + for stmt in cls.defs.body: + if not isinstance(stmt, ClassDef): + continue + if stmt.name == 'Config': + for substmt in stmt.defs.body: + if not isinstance(substmt, AssignmentStmt): + continue + config.update(self.get_config_update(substmt)) + if ( + config.has_alias_generator + and not config.allow_population_by_field_name + and self.plugin_config.warn_required_dynamic_aliases + ): + error_required_dynamic_aliases(ctx.api, stmt) + for info in cls.info.mro[1:]: # 0 is the current class + if METADATA_KEY not in info.metadata: + continue + + # Each class depends on the set of fields in its ancestors + ctx.api.add_plugin_dependency(make_wildcard_trigger(get_fullname(info))) + for name, value in info.metadata[METADATA_KEY]['config'].items(): + config.setdefault(name, value) + return config + + def collect_fields(self, model_config: 'ModelConfigData') -> List['PydanticModelField']: + """ + Collects the fields for the model, accounting for parent classes + """ + # First, collect fields belonging to the current class. + ctx = self._ctx + cls = self._ctx.cls + fields = [] # type: List[PydanticModelField] + known_fields = set() # type: Set[str] + for stmt in cls.defs.body: + if not isinstance(stmt, AssignmentStmt): # `and stmt.new_syntax` to require annotation + continue + + lhs = stmt.lvalues[0] + if not isinstance(lhs, NameExpr) or not is_valid_field(lhs.name): + continue + + if not stmt.new_syntax and self.plugin_config.warn_untyped_fields: + error_untyped_fields(ctx.api, stmt) + + # if lhs.name == '__config__': # BaseConfig not well handled; I'm not sure why yet + # continue + + sym = cls.info.names.get(lhs.name) + if sym is None: # pragma: no cover + # This is likely due to a star import (see the dataclasses plugin for a more detailed explanation) + # This is the same logic used in the dataclasses plugin + continue + + node = sym.node + if isinstance(node, PlaceholderNode): # pragma: no cover + # See the PlaceholderNode docstring for more detail about how this can occur + # Basically, it is an edge case when dealing with complex import logic + # This is the same logic used in the dataclasses plugin + continue + if not isinstance(node, Var): # pragma: no cover + # Don't know if this edge case still happens with the `is_valid_field` check above + # but better safe than sorry + continue + + # x: ClassVar[int] is ignored by dataclasses. + if node.is_classvar: + continue + + is_required = self.get_is_required(cls, stmt, lhs) + alias, has_dynamic_alias = self.get_alias_info(stmt) + if ( + has_dynamic_alias + and not model_config.allow_population_by_field_name + and self.plugin_config.warn_required_dynamic_aliases + ): + error_required_dynamic_aliases(ctx.api, stmt) + fields.append( + PydanticModelField( + name=lhs.name, + is_required=is_required, + alias=alias, + has_dynamic_alias=has_dynamic_alias, + line=stmt.line, + column=stmt.column, + ) + ) + known_fields.add(lhs.name) + all_fields = fields.copy() + for info in cls.info.mro[1:]: # 0 is the current class, -2 is BaseModel, -1 is object + if METADATA_KEY not in info.metadata: + continue + + superclass_fields = [] + # Each class depends on the set of fields in its ancestors + ctx.api.add_plugin_dependency(make_wildcard_trigger(get_fullname(info))) + + for name, data in info.metadata[METADATA_KEY]['fields'].items(): + if name not in known_fields: + field = PydanticModelField.deserialize(info, data) + known_fields.add(name) + superclass_fields.append(field) + else: + (field,) = (a for a in all_fields if a.name == name) + all_fields.remove(field) + superclass_fields.append(field) + all_fields = superclass_fields + all_fields + return all_fields + + def add_initializer(self, fields: List['PydanticModelField'], config: 'ModelConfigData', is_settings: bool) -> None: + """ + Adds a fields-aware `__init__` method to the class. + + The added `__init__` will be annotated with types vs. all `Any` depending on the plugin settings. + """ + ctx = self._ctx + typed = self.plugin_config.init_typed + use_alias = config.allow_population_by_field_name is not True + force_all_optional = is_settings or bool( + config.has_alias_generator and not config.allow_population_by_field_name + ) + init_arguments = self.get_field_arguments( + fields, typed=typed, force_all_optional=force_all_optional, use_alias=use_alias + ) + if not self.should_init_forbid_extra(fields, config): + var = Var('kwargs') + init_arguments.append(Argument(var, AnyType(TypeOfAny.explicit), None, ARG_STAR2)) + + if '__init__' not in ctx.cls.info.names: + add_method(ctx, '__init__', init_arguments, NoneType()) + + def add_construct_method(self, fields: List['PydanticModelField']) -> None: + """ + Adds a fully typed `construct` classmethod to the class. + + Similar to the fields-aware __init__ method, but always uses the field names (not aliases), + and does not treat settings fields as optional. + """ + ctx = self._ctx + set_str = ctx.api.named_type(f'{BUILTINS_NAME}.set', [ctx.api.named_type(f'{BUILTINS_NAME}.str')]) + optional_set_str = UnionType([set_str, NoneType()]) + fields_set_argument = Argument(Var('_fields_set', optional_set_str), optional_set_str, None, ARG_OPT) + construct_arguments = self.get_field_arguments(fields, typed=True, force_all_optional=False, use_alias=False) + construct_arguments = [fields_set_argument] + construct_arguments + + obj_type = ctx.api.named_type(f'{BUILTINS_NAME}.object') + self_tvar_name = '_PydanticBaseModel' # Make sure it does not conflict with other names in the class + tvar_fullname = ctx.cls.fullname + '.' + self_tvar_name + if MYPY_VERSION_TUPLE >= (1, 4): + tvd = TypeVarType( + self_tvar_name, + tvar_fullname, + TypeVarId(-1), + [], + obj_type, + AnyType(TypeOfAny.from_omitted_generics), # type: ignore[arg-type] + ) + self_tvar_expr = TypeVarExpr( + self_tvar_name, + tvar_fullname, + [], + obj_type, + AnyType(TypeOfAny.from_omitted_generics), # type: ignore[arg-type] + ) + else: + tvd = TypeVarDef(self_tvar_name, tvar_fullname, -1, [], obj_type) + self_tvar_expr = TypeVarExpr(self_tvar_name, tvar_fullname, [], obj_type) + ctx.cls.info.names[self_tvar_name] = SymbolTableNode(MDEF, self_tvar_expr) + + # Backward-compatible with TypeVarDef from Mypy 0.910. + if isinstance(tvd, TypeVarType): + self_type = tvd + else: + self_type = TypeVarType(tvd) + + add_method( + ctx, + 'construct', + construct_arguments, + return_type=self_type, + self_type=self_type, + tvar_def=tvd, + is_classmethod=True, + ) + + def set_frozen(self, fields: List['PydanticModelField'], frozen: bool) -> None: + """ + Marks all fields as properties so that attempts to set them trigger mypy errors. + + This is the same approach used by the attrs and dataclasses plugins. + """ + ctx = self._ctx + info = ctx.cls.info + for field in fields: + sym_node = info.names.get(field.name) + if sym_node is not None: + var = sym_node.node + if isinstance(var, Var): + var.is_property = frozen + elif isinstance(var, PlaceholderNode) and not ctx.api.final_iteration: + # See https://github.com/pydantic/pydantic/issues/5191 to hit this branch for test coverage + ctx.api.defer() + else: # pragma: no cover + # I don't know whether it's possible to hit this branch, but I've added it for safety + try: + var_str = str(var) + except TypeError: + # This happens for PlaceholderNode; perhaps it will happen for other types in the future.. + var_str = repr(var) + detail = f'sym_node.node: {var_str} (of type {var.__class__})' + error_unexpected_behavior(detail, ctx.api, ctx.cls) + else: + var = field.to_var(info, use_alias=False) + var.info = info + var.is_property = frozen + var._fullname = get_fullname(info) + '.' + get_name(var) + info.names[get_name(var)] = SymbolTableNode(MDEF, var) + + def get_config_update(self, substmt: AssignmentStmt) -> Optional['ModelConfigData']: + """ + Determines the config update due to a single statement in the Config class definition. + + Warns if a tracked config attribute is set to a value the plugin doesn't know how to interpret (e.g., an int) + """ + lhs = substmt.lvalues[0] + if not (isinstance(lhs, NameExpr) and lhs.name in self.tracked_config_fields): + return None + if lhs.name == 'extra': + if isinstance(substmt.rvalue, StrExpr): + forbid_extra = substmt.rvalue.value == 'forbid' + elif isinstance(substmt.rvalue, MemberExpr): + forbid_extra = substmt.rvalue.name == 'forbid' + else: + error_invalid_config_value(lhs.name, self._ctx.api, substmt) + return None + return ModelConfigData(forbid_extra=forbid_extra) + if lhs.name == 'alias_generator': + has_alias_generator = True + if isinstance(substmt.rvalue, NameExpr) and substmt.rvalue.fullname == 'builtins.None': + has_alias_generator = False + return ModelConfigData(has_alias_generator=has_alias_generator) + if isinstance(substmt.rvalue, NameExpr) and substmt.rvalue.fullname in ('builtins.True', 'builtins.False'): + return ModelConfigData(**{lhs.name: substmt.rvalue.fullname == 'builtins.True'}) + error_invalid_config_value(lhs.name, self._ctx.api, substmt) + return None + + @staticmethod + def get_is_required(cls: ClassDef, stmt: AssignmentStmt, lhs: NameExpr) -> bool: + """ + Returns a boolean indicating whether the field defined in `stmt` is a required field. + """ + expr = stmt.rvalue + if isinstance(expr, TempNode): + # TempNode means annotation-only, so only non-required if Optional + value_type = get_proper_type(cls.info[lhs.name].type) + return not PydanticModelTransformer.type_has_implicit_default(value_type) + if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME: + # The "default value" is a call to `Field`; at this point, the field is + # only required if default is Ellipsis (i.e., `field_name: Annotation = Field(...)`) or if default_factory + # is specified. + for arg, name in zip(expr.args, expr.arg_names): + # If name is None, then this arg is the default because it is the only positional argument. + if name is None or name == 'default': + return arg.__class__ is EllipsisExpr + if name == 'default_factory': + return False + # In this case, default and default_factory are not specified, so we need to look at the annotation + value_type = get_proper_type(cls.info[lhs.name].type) + return not PydanticModelTransformer.type_has_implicit_default(value_type) + # Only required if the "default value" is Ellipsis (i.e., `field_name: Annotation = ...`) + return isinstance(expr, EllipsisExpr) + + @staticmethod + def type_has_implicit_default(type_: Optional[ProperType]) -> bool: + """ + Returns True if the passed type will be given an implicit default value. + + In pydantic v1, this is the case for Optional types and Any (with default value None). + """ + if isinstance(type_, AnyType): + # Annotated as Any + return True + if isinstance(type_, UnionType) and any( + isinstance(item, NoneType) or isinstance(item, AnyType) for item in type_.items + ): + # Annotated as Optional, or otherwise having NoneType or AnyType in the union + return True + return False + + @staticmethod + def get_alias_info(stmt: AssignmentStmt) -> Tuple[Optional[str], bool]: + """ + Returns a pair (alias, has_dynamic_alias), extracted from the declaration of the field defined in `stmt`. + + `has_dynamic_alias` is True if and only if an alias is provided, but not as a string literal. + If `has_dynamic_alias` is True, `alias` will be None. + """ + expr = stmt.rvalue + if isinstance(expr, TempNode): + # TempNode means annotation-only + return None, False + + if not ( + isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr) and expr.callee.fullname == FIELD_FULLNAME + ): + # Assigned value is not a call to pydantic.fields.Field + return None, False + + for i, arg_name in enumerate(expr.arg_names): + if arg_name != 'alias': + continue + arg = expr.args[i] + if isinstance(arg, StrExpr): + return arg.value, False + else: + return None, True + return None, False + + def get_field_arguments( + self, fields: List['PydanticModelField'], typed: bool, force_all_optional: bool, use_alias: bool + ) -> List[Argument]: + """ + Helper function used during the construction of the `__init__` and `construct` method signatures. + + Returns a list of mypy Argument instances for use in the generated signatures. + """ + info = self._ctx.cls.info + arguments = [ + field.to_argument(info, typed=typed, force_optional=force_all_optional, use_alias=use_alias) + for field in fields + if not (use_alias and field.has_dynamic_alias) + ] + return arguments + + def should_init_forbid_extra(self, fields: List['PydanticModelField'], config: 'ModelConfigData') -> bool: + """ + Indicates whether the generated `__init__` should get a `**kwargs` at the end of its signature + + We disallow arbitrary kwargs if the extra config setting is "forbid", or if the plugin config says to, + *unless* a required dynamic alias is present (since then we can't determine a valid signature). + """ + if not config.allow_population_by_field_name: + if self.is_dynamic_alias_present(fields, bool(config.has_alias_generator)): + return False + if config.forbid_extra: + return True + return self.plugin_config.init_forbid_extra + + @staticmethod + def is_dynamic_alias_present(fields: List['PydanticModelField'], has_alias_generator: bool) -> bool: + """ + Returns whether any fields on the model have a "dynamic alias", i.e., an alias that cannot be + determined during static analysis. + """ + for field in fields: + if field.has_dynamic_alias: + return True + if has_alias_generator: + for field in fields: + if field.alias is None: + return True + return False + + +class PydanticModelField: + def __init__( + self, name: str, is_required: bool, alias: Optional[str], has_dynamic_alias: bool, line: int, column: int + ): + self.name = name + self.is_required = is_required + self.alias = alias + self.has_dynamic_alias = has_dynamic_alias + self.line = line + self.column = column + + def to_var(self, info: TypeInfo, use_alias: bool) -> Var: + name = self.name + if use_alias and self.alias is not None: + name = self.alias + return Var(name, info[self.name].type) + + def to_argument(self, info: TypeInfo, typed: bool, force_optional: bool, use_alias: bool) -> Argument: + if typed and info[self.name].type is not None: + type_annotation = info[self.name].type + else: + type_annotation = AnyType(TypeOfAny.explicit) + return Argument( + variable=self.to_var(info, use_alias), + type_annotation=type_annotation, + initializer=None, + kind=ARG_NAMED_OPT if force_optional or not self.is_required else ARG_NAMED, + ) + + def serialize(self) -> JsonDict: + return self.__dict__ + + @classmethod + def deserialize(cls, info: TypeInfo, data: JsonDict) -> 'PydanticModelField': + return cls(**data) + + +class ModelConfigData: + def __init__( + self, + forbid_extra: Optional[bool] = None, + allow_mutation: Optional[bool] = None, + frozen: Optional[bool] = None, + orm_mode: Optional[bool] = None, + allow_population_by_field_name: Optional[bool] = None, + has_alias_generator: Optional[bool] = None, + ): + self.forbid_extra = forbid_extra + self.allow_mutation = allow_mutation + self.frozen = frozen + self.orm_mode = orm_mode + self.allow_population_by_field_name = allow_population_by_field_name + self.has_alias_generator = has_alias_generator + + def set_values_dict(self) -> Dict[str, Any]: + return {k: v for k, v in self.__dict__.items() if v is not None} + + def update(self, config: Optional['ModelConfigData']) -> None: + if config is None: + return + for k, v in config.set_values_dict().items(): + setattr(self, k, v) + + def setdefault(self, key: str, value: Any) -> None: + if getattr(self, key) is None: + setattr(self, key, value) + + +ERROR_ORM = ErrorCode('pydantic-orm', 'Invalid from_orm call', 'Pydantic') +ERROR_CONFIG = ErrorCode('pydantic-config', 'Invalid config value', 'Pydantic') +ERROR_ALIAS = ErrorCode('pydantic-alias', 'Dynamic alias disallowed', 'Pydantic') +ERROR_UNEXPECTED = ErrorCode('pydantic-unexpected', 'Unexpected behavior', 'Pydantic') +ERROR_UNTYPED = ErrorCode('pydantic-field', 'Untyped field disallowed', 'Pydantic') +ERROR_FIELD_DEFAULTS = ErrorCode('pydantic-field', 'Invalid Field defaults', 'Pydantic') + + +def error_from_orm(model_name: str, api: CheckerPluginInterface, context: Context) -> None: + api.fail(f'"{model_name}" does not have orm_mode=True', context, code=ERROR_ORM) + + +def error_invalid_config_value(name: str, api: SemanticAnalyzerPluginInterface, context: Context) -> None: + api.fail(f'Invalid value for "Config.{name}"', context, code=ERROR_CONFIG) + + +def error_required_dynamic_aliases(api: SemanticAnalyzerPluginInterface, context: Context) -> None: + api.fail('Required dynamic aliases disallowed', context, code=ERROR_ALIAS) + + +def error_unexpected_behavior( + detail: str, api: Union[CheckerPluginInterface, SemanticAnalyzerPluginInterface], context: Context +) -> None: # pragma: no cover + # Can't think of a good way to test this, but I confirmed it renders as desired by adding to a non-error path + link = 'https://github.com/pydantic/pydantic/issues/new/choose' + full_message = f'The pydantic mypy plugin ran into unexpected behavior: {detail}\n' + full_message += f'Please consider reporting this bug at {link} so we can try to fix it!' + api.fail(full_message, context, code=ERROR_UNEXPECTED) + + +def error_untyped_fields(api: SemanticAnalyzerPluginInterface, context: Context) -> None: + api.fail('Untyped fields disallowed', context, code=ERROR_UNTYPED) + + +def error_default_and_default_factory_specified(api: CheckerPluginInterface, context: Context) -> None: + api.fail('Field default and default_factory cannot be specified together', context, code=ERROR_FIELD_DEFAULTS) + + +def add_method( + ctx: ClassDefContext, + name: str, + args: List[Argument], + return_type: Type, + self_type: Optional[Type] = None, + tvar_def: Optional[TypeVarDef] = None, + is_classmethod: bool = False, + is_new: bool = False, + # is_staticmethod: bool = False, +) -> None: + """ + Adds a new method to a class. + + This can be dropped if/when https://github.com/python/mypy/issues/7301 is merged + """ + info = ctx.cls.info + + # First remove any previously generated methods with the same name + # to avoid clashes and problems in the semantic analyzer. + if name in info.names: + sym = info.names[name] + if sym.plugin_generated and isinstance(sym.node, FuncDef): + ctx.cls.defs.body.remove(sym.node) # pragma: no cover + + self_type = self_type or fill_typevars(info) + if is_classmethod or is_new: + first = [Argument(Var('_cls'), TypeType.make_normalized(self_type), None, ARG_POS)] + # elif is_staticmethod: + # first = [] + else: + self_type = self_type or fill_typevars(info) + first = [Argument(Var('__pydantic_self__'), self_type, None, ARG_POS)] + args = first + args + arg_types, arg_names, arg_kinds = [], [], [] + for arg in args: + assert arg.type_annotation, 'All arguments must be fully typed.' + arg_types.append(arg.type_annotation) + arg_names.append(get_name(arg.variable)) + arg_kinds.append(arg.kind) + + function_type = ctx.api.named_type(f'{BUILTINS_NAME}.function') + signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type) + if tvar_def: + signature.variables = [tvar_def] + + func = FuncDef(name, args, Block([PassStmt()])) + func.info = info + func.type = set_callable_name(signature, func) + func.is_class = is_classmethod + # func.is_static = is_staticmethod + func._fullname = get_fullname(info) + '.' + name + func.line = info.line + + # NOTE: we would like the plugin generated node to dominate, but we still + # need to keep any existing definitions so they get semantically analyzed. + if name in info.names: + # Get a nice unique name instead. + r_name = get_unique_redefinition_name(name, info.names) + info.names[r_name] = info.names[name] + + if is_classmethod: # or is_staticmethod: + func.is_decorated = True + v = Var(name, func.type) + v.info = info + v._fullname = func._fullname + # if is_classmethod: + v.is_classmethod = True + dec = Decorator(func, [NameExpr('classmethod')], v) + # else: + # v.is_staticmethod = True + # dec = Decorator(func, [NameExpr('staticmethod')], v) + + dec.line = info.line + sym = SymbolTableNode(MDEF, dec) + else: + sym = SymbolTableNode(MDEF, func) + sym.plugin_generated = True + + info.names[name] = sym + info.defn.defs.body.append(func) + + +def get_fullname(x: Union[FuncBase, SymbolNode]) -> str: + """ + Used for compatibility with mypy 0.740; can be dropped once support for 0.740 is dropped. + """ + fn = x.fullname + if callable(fn): # pragma: no cover + return fn() + return fn + + +def get_name(x: Union[FuncBase, SymbolNode]) -> str: + """ + Used for compatibility with mypy 0.740; can be dropped once support for 0.740 is dropped. + """ + fn = x.name + if callable(fn): # pragma: no cover + return fn() + return fn + + +def parse_toml(config_file: str) -> Optional[Dict[str, Any]]: + if not config_file.endswith('.toml'): + return None + + read_mode = 'rb' + if sys.version_info >= (3, 11): + import tomllib as toml_ + else: + try: + import tomli as toml_ + except ImportError: + # older versions of mypy have toml as a dependency, not tomli + read_mode = 'r' + try: + import toml as toml_ # type: ignore[no-redef] + except ImportError: # pragma: no cover + import warnings + + warnings.warn('No TOML parser installed, cannot read configuration from `pyproject.toml`.') + return None + + with open(config_file, read_mode) as rf: + return toml_.load(rf) # type: ignore[arg-type] diff --git a/env/Lib/site-packages/pydantic/v1/networks.py b/env/Lib/site-packages/pydantic/v1/networks.py new file mode 100644 index 0000000..ba07b74 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/networks.py @@ -0,0 +1,747 @@ +import re +from ipaddress import ( + IPv4Address, + IPv4Interface, + IPv4Network, + IPv6Address, + IPv6Interface, + IPv6Network, + _BaseAddress, + _BaseNetwork, +) +from typing import ( + TYPE_CHECKING, + Any, + Collection, + Dict, + Generator, + List, + Match, + Optional, + Pattern, + Set, + Tuple, + Type, + Union, + cast, + no_type_check, +) + +from pydantic.v1 import errors +from pydantic.v1.utils import Representation, update_not_none +from pydantic.v1.validators import constr_length_validator, str_validator + +if TYPE_CHECKING: + import email_validator + from typing_extensions import TypedDict + + from pydantic.v1.config import BaseConfig + from pydantic.v1.fields import ModelField + from pydantic.v1.typing import AnyCallable + + CallableGenerator = Generator[AnyCallable, None, None] + + class Parts(TypedDict, total=False): + scheme: str + user: Optional[str] + password: Optional[str] + ipv4: Optional[str] + ipv6: Optional[str] + domain: Optional[str] + port: Optional[str] + path: Optional[str] + query: Optional[str] + fragment: Optional[str] + + class HostParts(TypedDict, total=False): + host: str + tld: Optional[str] + host_type: Optional[str] + port: Optional[str] + rebuild: bool + +else: + email_validator = None + + class Parts(dict): + pass + + +NetworkType = Union[str, bytes, int, Tuple[Union[str, bytes, int], Union[str, int]]] + +__all__ = [ + 'AnyUrl', + 'AnyHttpUrl', + 'FileUrl', + 'HttpUrl', + 'stricturl', + 'EmailStr', + 'NameEmail', + 'IPvAnyAddress', + 'IPvAnyInterface', + 'IPvAnyNetwork', + 'PostgresDsn', + 'CockroachDsn', + 'AmqpDsn', + 'RedisDsn', + 'MongoDsn', + 'KafkaDsn', + 'validate_email', +] + +_url_regex_cache = None +_multi_host_url_regex_cache = None +_ascii_domain_regex_cache = None +_int_domain_regex_cache = None +_host_regex_cache = None + +_host_regex = ( + r'(?:' + r'(?P(?:\d{1,3}\.){3}\d{1,3})(?=$|[/:#?])|' # ipv4 + r'(?P\[[A-F0-9]*:[A-F0-9:]+\])(?=$|[/:#?])|' # ipv6 + r'(?P[^\s/:?#]+)' # domain, validation occurs later + r')?' + r'(?::(?P\d+))?' # port +) +_scheme_regex = r'(?:(?P[a-z][a-z0-9+\-.]+)://)?' # scheme https://tools.ietf.org/html/rfc3986#appendix-A +_user_info_regex = r'(?:(?P[^\s:/]*)(?::(?P[^\s/]*))?@)?' +_path_regex = r'(?P/[^\s?#]*)?' +_query_regex = r'(?:\?(?P[^\s#]*))?' +_fragment_regex = r'(?:#(?P[^\s#]*))?' + + +def url_regex() -> Pattern[str]: + global _url_regex_cache + if _url_regex_cache is None: + _url_regex_cache = re.compile( + rf'{_scheme_regex}{_user_info_regex}{_host_regex}{_path_regex}{_query_regex}{_fragment_regex}', + re.IGNORECASE, + ) + return _url_regex_cache + + +def multi_host_url_regex() -> Pattern[str]: + """ + Compiled multi host url regex. + + Additionally to `url_regex` it allows to match multiple hosts. + E.g. host1.db.net,host2.db.net + """ + global _multi_host_url_regex_cache + if _multi_host_url_regex_cache is None: + _multi_host_url_regex_cache = re.compile( + rf'{_scheme_regex}{_user_info_regex}' + r'(?P([^/]*))' # validation occurs later + rf'{_path_regex}{_query_regex}{_fragment_regex}', + re.IGNORECASE, + ) + return _multi_host_url_regex_cache + + +def ascii_domain_regex() -> Pattern[str]: + global _ascii_domain_regex_cache + if _ascii_domain_regex_cache is None: + ascii_chunk = r'[_0-9a-z](?:[-_0-9a-z]{0,61}[_0-9a-z])?' + ascii_domain_ending = r'(?P\.[a-z]{2,63})?\.?' + _ascii_domain_regex_cache = re.compile( + fr'(?:{ascii_chunk}\.)*?{ascii_chunk}{ascii_domain_ending}', re.IGNORECASE + ) + return _ascii_domain_regex_cache + + +def int_domain_regex() -> Pattern[str]: + global _int_domain_regex_cache + if _int_domain_regex_cache is None: + int_chunk = r'[_0-9a-\U00040000](?:[-_0-9a-\U00040000]{0,61}[_0-9a-\U00040000])?' + int_domain_ending = r'(?P(\.[^\W\d_]{2,63})|(\.(?:xn--)[_0-9a-z-]{2,63}))?\.?' + _int_domain_regex_cache = re.compile(fr'(?:{int_chunk}\.)*?{int_chunk}{int_domain_ending}', re.IGNORECASE) + return _int_domain_regex_cache + + +def host_regex() -> Pattern[str]: + global _host_regex_cache + if _host_regex_cache is None: + _host_regex_cache = re.compile( + _host_regex, + re.IGNORECASE, + ) + return _host_regex_cache + + +class AnyUrl(str): + strip_whitespace = True + min_length = 1 + max_length = 2**16 + allowed_schemes: Optional[Collection[str]] = None + tld_required: bool = False + user_required: bool = False + host_required: bool = True + hidden_parts: Set[str] = set() + + __slots__ = ('scheme', 'user', 'password', 'host', 'tld', 'host_type', 'port', 'path', 'query', 'fragment') + + @no_type_check + def __new__(cls, url: Optional[str], **kwargs) -> object: + return str.__new__(cls, cls.build(**kwargs) if url is None else url) + + def __init__( + self, + url: str, + *, + scheme: str, + user: Optional[str] = None, + password: Optional[str] = None, + host: Optional[str] = None, + tld: Optional[str] = None, + host_type: str = 'domain', + port: Optional[str] = None, + path: Optional[str] = None, + query: Optional[str] = None, + fragment: Optional[str] = None, + ) -> None: + str.__init__(url) + self.scheme = scheme + self.user = user + self.password = password + self.host = host + self.tld = tld + self.host_type = host_type + self.port = port + self.path = path + self.query = query + self.fragment = fragment + + @classmethod + def build( + cls, + *, + scheme: str, + user: Optional[str] = None, + password: Optional[str] = None, + host: str, + port: Optional[str] = None, + path: Optional[str] = None, + query: Optional[str] = None, + fragment: Optional[str] = None, + **_kwargs: str, + ) -> str: + parts = Parts( + scheme=scheme, + user=user, + password=password, + host=host, + port=port, + path=path, + query=query, + fragment=fragment, + **_kwargs, # type: ignore[misc] + ) + + url = scheme + '://' + if user: + url += user + if password: + url += ':' + password + if user or password: + url += '@' + url += host + if port and ('port' not in cls.hidden_parts or cls.get_default_parts(parts).get('port') != port): + url += ':' + port + if path: + url += path + if query: + url += '?' + query + if fragment: + url += '#' + fragment + return url + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none(field_schema, minLength=cls.min_length, maxLength=cls.max_length, format='uri') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + + @classmethod + def validate(cls, value: Any, field: 'ModelField', config: 'BaseConfig') -> 'AnyUrl': + if value.__class__ == cls: + return value + value = str_validator(value) + if cls.strip_whitespace: + value = value.strip() + url: str = cast(str, constr_length_validator(value, field, config)) + + m = cls._match_url(url) + # the regex should always match, if it doesn't please report with details of the URL tried + assert m, 'URL regex failed unexpectedly' + + original_parts = cast('Parts', m.groupdict()) + parts = cls.apply_default_parts(original_parts) + parts = cls.validate_parts(parts) + + if m.end() != len(url): + raise errors.UrlExtraError(extra=url[m.end() :]) + + return cls._build_url(m, url, parts) + + @classmethod + def _build_url(cls, m: Match[str], url: str, parts: 'Parts') -> 'AnyUrl': + """ + Validate hosts and build the AnyUrl object. Split from `validate` so this method + can be altered in `MultiHostDsn`. + """ + host, tld, host_type, rebuild = cls.validate_host(parts) + + return cls( + None if rebuild else url, + scheme=parts['scheme'], + user=parts['user'], + password=parts['password'], + host=host, + tld=tld, + host_type=host_type, + port=parts['port'], + path=parts['path'], + query=parts['query'], + fragment=parts['fragment'], + ) + + @staticmethod + def _match_url(url: str) -> Optional[Match[str]]: + return url_regex().match(url) + + @staticmethod + def _validate_port(port: Optional[str]) -> None: + if port is not None and int(port) > 65_535: + raise errors.UrlPortError() + + @classmethod + def validate_parts(cls, parts: 'Parts', validate_port: bool = True) -> 'Parts': + """ + A method used to validate parts of a URL. + Could be overridden to set default values for parts if missing + """ + scheme = parts['scheme'] + if scheme is None: + raise errors.UrlSchemeError() + + if cls.allowed_schemes and scheme.lower() not in cls.allowed_schemes: + raise errors.UrlSchemePermittedError(set(cls.allowed_schemes)) + + if validate_port: + cls._validate_port(parts['port']) + + user = parts['user'] + if cls.user_required and user is None: + raise errors.UrlUserInfoError() + + return parts + + @classmethod + def validate_host(cls, parts: 'Parts') -> Tuple[str, Optional[str], str, bool]: + tld, host_type, rebuild = None, None, False + for f in ('domain', 'ipv4', 'ipv6'): + host = parts[f] # type: ignore[literal-required] + if host: + host_type = f + break + + if host is None: + if cls.host_required: + raise errors.UrlHostError() + elif host_type == 'domain': + is_international = False + d = ascii_domain_regex().fullmatch(host) + if d is None: + d = int_domain_regex().fullmatch(host) + if d is None: + raise errors.UrlHostError() + is_international = True + + tld = d.group('tld') + if tld is None and not is_international: + d = int_domain_regex().fullmatch(host) + assert d is not None + tld = d.group('tld') + is_international = True + + if tld is not None: + tld = tld[1:] + elif cls.tld_required: + raise errors.UrlHostTldError() + + if is_international: + host_type = 'int_domain' + rebuild = True + host = host.encode('idna').decode('ascii') + if tld is not None: + tld = tld.encode('idna').decode('ascii') + + return host, tld, host_type, rebuild # type: ignore + + @staticmethod + def get_default_parts(parts: 'Parts') -> 'Parts': + return {} + + @classmethod + def apply_default_parts(cls, parts: 'Parts') -> 'Parts': + for key, value in cls.get_default_parts(parts).items(): + if not parts[key]: # type: ignore[literal-required] + parts[key] = value # type: ignore[literal-required] + return parts + + def __repr__(self) -> str: + extra = ', '.join(f'{n}={getattr(self, n)!r}' for n in self.__slots__ if getattr(self, n) is not None) + return f'{self.__class__.__name__}({super().__repr__()}, {extra})' + + +class AnyHttpUrl(AnyUrl): + allowed_schemes = {'http', 'https'} + + __slots__ = () + + +class HttpUrl(AnyHttpUrl): + tld_required = True + # https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers + max_length = 2083 + hidden_parts = {'port'} + + @staticmethod + def get_default_parts(parts: 'Parts') -> 'Parts': + return {'port': '80' if parts['scheme'] == 'http' else '443'} + + +class FileUrl(AnyUrl): + allowed_schemes = {'file'} + host_required = False + + __slots__ = () + + +class MultiHostDsn(AnyUrl): + __slots__ = AnyUrl.__slots__ + ('hosts',) + + def __init__(self, *args: Any, hosts: Optional[List['HostParts']] = None, **kwargs: Any): + super().__init__(*args, **kwargs) + self.hosts = hosts + + @staticmethod + def _match_url(url: str) -> Optional[Match[str]]: + return multi_host_url_regex().match(url) + + @classmethod + def validate_parts(cls, parts: 'Parts', validate_port: bool = True) -> 'Parts': + return super().validate_parts(parts, validate_port=False) + + @classmethod + def _build_url(cls, m: Match[str], url: str, parts: 'Parts') -> 'MultiHostDsn': + hosts_parts: List['HostParts'] = [] + host_re = host_regex() + for host in m.groupdict()['hosts'].split(','): + d: Parts = host_re.match(host).groupdict() # type: ignore + host, tld, host_type, rebuild = cls.validate_host(d) + port = d.get('port') + cls._validate_port(port) + hosts_parts.append( + { + 'host': host, + 'host_type': host_type, + 'tld': tld, + 'rebuild': rebuild, + 'port': port, + } + ) + + if len(hosts_parts) > 1: + return cls( + None if any([hp['rebuild'] for hp in hosts_parts]) else url, + scheme=parts['scheme'], + user=parts['user'], + password=parts['password'], + path=parts['path'], + query=parts['query'], + fragment=parts['fragment'], + host_type=None, + hosts=hosts_parts, + ) + else: + # backwards compatibility with single host + host_part = hosts_parts[0] + return cls( + None if host_part['rebuild'] else url, + scheme=parts['scheme'], + user=parts['user'], + password=parts['password'], + host=host_part['host'], + tld=host_part['tld'], + host_type=host_part['host_type'], + port=host_part.get('port'), + path=parts['path'], + query=parts['query'], + fragment=parts['fragment'], + ) + + +class PostgresDsn(MultiHostDsn): + allowed_schemes = { + 'postgres', + 'postgresql', + 'postgresql+asyncpg', + 'postgresql+pg8000', + 'postgresql+psycopg', + 'postgresql+psycopg2', + 'postgresql+psycopg2cffi', + 'postgresql+py-postgresql', + 'postgresql+pygresql', + } + user_required = True + + __slots__ = () + + +class CockroachDsn(AnyUrl): + allowed_schemes = { + 'cockroachdb', + 'cockroachdb+psycopg2', + 'cockroachdb+asyncpg', + } + user_required = True + + +class AmqpDsn(AnyUrl): + allowed_schemes = {'amqp', 'amqps'} + host_required = False + + +class RedisDsn(AnyUrl): + __slots__ = () + allowed_schemes = {'redis', 'rediss'} + host_required = False + + @staticmethod + def get_default_parts(parts: 'Parts') -> 'Parts': + return { + 'domain': 'localhost' if not (parts['ipv4'] or parts['ipv6']) else '', + 'port': '6379', + 'path': '/0', + } + + +class MongoDsn(AnyUrl): + allowed_schemes = {'mongodb'} + + # TODO: Needed to generic "Parts" for "Replica Set", "Sharded Cluster", and other mongodb deployment modes + @staticmethod + def get_default_parts(parts: 'Parts') -> 'Parts': + return { + 'port': '27017', + } + + +class KafkaDsn(AnyUrl): + allowed_schemes = {'kafka'} + + @staticmethod + def get_default_parts(parts: 'Parts') -> 'Parts': + return { + 'domain': 'localhost', + 'port': '9092', + } + + +def stricturl( + *, + strip_whitespace: bool = True, + min_length: int = 1, + max_length: int = 2**16, + tld_required: bool = True, + host_required: bool = True, + allowed_schemes: Optional[Collection[str]] = None, +) -> Type[AnyUrl]: + # use kwargs then define conf in a dict to aid with IDE type hinting + namespace = dict( + strip_whitespace=strip_whitespace, + min_length=min_length, + max_length=max_length, + tld_required=tld_required, + host_required=host_required, + allowed_schemes=allowed_schemes, + ) + return type('UrlValue', (AnyUrl,), namespace) + + +def import_email_validator() -> None: + global email_validator + try: + import email_validator + except ImportError as e: + raise ImportError('email-validator is not installed, run `pip install pydantic[email]`') from e + + +class EmailStr(str): + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='string', format='email') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + # included here and below so the error happens straight away + import_email_validator() + + yield str_validator + yield cls.validate + + @classmethod + def validate(cls, value: Union[str]) -> str: + return validate_email(value)[1] + + +class NameEmail(Representation): + __slots__ = 'name', 'email' + + def __init__(self, name: str, email: str): + self.name = name + self.email = email + + def __eq__(self, other: Any) -> bool: + return isinstance(other, NameEmail) and (self.name, self.email) == (other.name, other.email) + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='string', format='name-email') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + import_email_validator() + + yield cls.validate + + @classmethod + def validate(cls, value: Any) -> 'NameEmail': + if value.__class__ == cls: + return value + value = str_validator(value) + return cls(*validate_email(value)) + + def __str__(self) -> str: + return f'{self.name} <{self.email}>' + + +class IPvAnyAddress(_BaseAddress): + __slots__ = () + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='string', format='ipvanyaddress') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + + @classmethod + def validate(cls, value: Union[str, bytes, int]) -> Union[IPv4Address, IPv6Address]: + try: + return IPv4Address(value) + except ValueError: + pass + + try: + return IPv6Address(value) + except ValueError: + raise errors.IPvAnyAddressError() + + +class IPvAnyInterface(_BaseAddress): + __slots__ = () + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='string', format='ipvanyinterface') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + + @classmethod + def validate(cls, value: NetworkType) -> Union[IPv4Interface, IPv6Interface]: + try: + return IPv4Interface(value) + except ValueError: + pass + + try: + return IPv6Interface(value) + except ValueError: + raise errors.IPvAnyInterfaceError() + + +class IPvAnyNetwork(_BaseNetwork): # type: ignore + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='string', format='ipvanynetwork') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + + @classmethod + def validate(cls, value: NetworkType) -> Union[IPv4Network, IPv6Network]: + # Assume IP Network is defined with a default value for ``strict`` argument. + # Define your own class if you want to specify network address check strictness. + try: + return IPv4Network(value) + except ValueError: + pass + + try: + return IPv6Network(value) + except ValueError: + raise errors.IPvAnyNetworkError() + + +pretty_email_regex = re.compile(r'([\w ]*?) *<(.*)> *') +MAX_EMAIL_LENGTH = 2048 +"""Maximum length for an email. +A somewhat arbitrary but very generous number compared to what is allowed by most implementations. +""" + + +def validate_email(value: Union[str]) -> Tuple[str, str]: + """ + Email address validation using https://pypi.org/project/email-validator/ + Notes: + * raw ip address (literal) domain parts are not allowed. + * "John Doe " style "pretty" email addresses are processed + * spaces are striped from the beginning and end of addresses but no error is raised + """ + if email_validator is None: + import_email_validator() + + if len(value) > MAX_EMAIL_LENGTH: + raise errors.EmailError() + + m = pretty_email_regex.fullmatch(value) + name: Union[str, None] = None + if m: + name, value = m.groups() + email = value.strip() + try: + parts = email_validator.validate_email(email, check_deliverability=False) + except email_validator.EmailNotValidError as e: + raise errors.EmailError from e + + if hasattr(parts, 'normalized'): + # email-validator >= 2 + email = parts.normalized + assert email is not None + name = name or parts.local_part + return name, email + else: + # email-validator >1, <2 + at_index = email.index('@') + local_part = email[:at_index] # RFC 5321, local part must be case-sensitive. + global_part = email[at_index:].lower() + + return name or local_part, local_part + global_part diff --git a/env/Lib/site-packages/pydantic/v1/parse.py b/env/Lib/site-packages/pydantic/v1/parse.py new file mode 100644 index 0000000..431d75a --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/parse.py @@ -0,0 +1,66 @@ +import json +import pickle +from enum import Enum +from pathlib import Path +from typing import Any, Callable, Union + +from pydantic.v1.types import StrBytes + + +class Protocol(str, Enum): + json = 'json' + pickle = 'pickle' + + +def load_str_bytes( + b: StrBytes, + *, + content_type: str = None, + encoding: str = 'utf8', + proto: Protocol = None, + allow_pickle: bool = False, + json_loads: Callable[[str], Any] = json.loads, +) -> Any: + if proto is None and content_type: + if content_type.endswith(('json', 'javascript')): + pass + elif allow_pickle and content_type.endswith('pickle'): + proto = Protocol.pickle + else: + raise TypeError(f'Unknown content-type: {content_type}') + + proto = proto or Protocol.json + + if proto == Protocol.json: + if isinstance(b, bytes): + b = b.decode(encoding) + return json_loads(b) + elif proto == Protocol.pickle: + if not allow_pickle: + raise RuntimeError('Trying to decode with pickle with allow_pickle=False') + bb = b if isinstance(b, bytes) else b.encode() + return pickle.loads(bb) + else: + raise TypeError(f'Unknown protocol: {proto}') + + +def load_file( + path: Union[str, Path], + *, + content_type: str = None, + encoding: str = 'utf8', + proto: Protocol = None, + allow_pickle: bool = False, + json_loads: Callable[[str], Any] = json.loads, +) -> Any: + path = Path(path) + b = path.read_bytes() + if content_type is None: + if path.suffix in ('.js', '.json'): + proto = Protocol.json + elif path.suffix == '.pkl': + proto = Protocol.pickle + + return load_str_bytes( + b, proto=proto, content_type=content_type, encoding=encoding, allow_pickle=allow_pickle, json_loads=json_loads + ) diff --git a/env/Lib/site-packages/pydantic/v1/py.typed b/env/Lib/site-packages/pydantic/v1/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/pydantic/v1/schema.py b/env/Lib/site-packages/pydantic/v1/schema.py new file mode 100644 index 0000000..bac4c0a --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/schema.py @@ -0,0 +1,1163 @@ +import re +import warnings +from collections import defaultdict +from dataclasses import is_dataclass +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from enum import Enum +from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + ForwardRef, + FrozenSet, + Generic, + Iterable, + List, + Optional, + Pattern, + Sequence, + Set, + Tuple, + Type, + TypeVar, + Union, + cast, +) +from uuid import UUID + +from typing_extensions import Annotated, Literal + +from pydantic.v1.fields import ( + MAPPING_LIKE_SHAPES, + SHAPE_DEQUE, + SHAPE_FROZENSET, + SHAPE_GENERIC, + SHAPE_ITERABLE, + SHAPE_LIST, + SHAPE_SEQUENCE, + SHAPE_SET, + SHAPE_SINGLETON, + SHAPE_TUPLE, + SHAPE_TUPLE_ELLIPSIS, + FieldInfo, + ModelField, +) +from pydantic.v1.json import pydantic_encoder +from pydantic.v1.networks import AnyUrl, EmailStr +from pydantic.v1.types import ( + ConstrainedDecimal, + ConstrainedFloat, + ConstrainedFrozenSet, + ConstrainedInt, + ConstrainedList, + ConstrainedSet, + ConstrainedStr, + SecretBytes, + SecretStr, + StrictBytes, + StrictStr, + conbytes, + condecimal, + confloat, + confrozenset, + conint, + conlist, + conset, + constr, +) +from pydantic.v1.typing import ( + all_literal_values, + get_args, + get_origin, + get_sub_types, + is_callable_type, + is_literal_type, + is_namedtuple, + is_none_type, + is_union, +) +from pydantic.v1.utils import ROOT_KEY, get_model, lenient_issubclass + +if TYPE_CHECKING: + from pydantic.v1.dataclasses import Dataclass + from pydantic.v1.main import BaseModel + +default_prefix = '#/definitions/' +default_ref_template = '#/definitions/{model}' + +TypeModelOrEnum = Union[Type['BaseModel'], Type[Enum]] +TypeModelSet = Set[TypeModelOrEnum] + + +def _apply_modify_schema( + modify_schema: Callable[..., None], field: Optional[ModelField], field_schema: Dict[str, Any] +) -> None: + from inspect import signature + + sig = signature(modify_schema) + args = set(sig.parameters.keys()) + if 'field' in args or 'kwargs' in args: + modify_schema(field_schema, field=field) + else: + modify_schema(field_schema) + + +def schema( + models: Sequence[Union[Type['BaseModel'], Type['Dataclass']]], + *, + by_alias: bool = True, + title: Optional[str] = None, + description: Optional[str] = None, + ref_prefix: Optional[str] = None, + ref_template: str = default_ref_template, +) -> Dict[str, Any]: + """ + Process a list of models and generate a single JSON Schema with all of them defined in the ``definitions`` + top-level JSON key, including their sub-models. + + :param models: a list of models to include in the generated JSON Schema + :param by_alias: generate the schemas using the aliases defined, if any + :param title: title for the generated schema that includes the definitions + :param description: description for the generated schema + :param ref_prefix: the JSON Pointer prefix for schema references with ``$ref``, if None, will be set to the + default of ``#/definitions/``. Update it if you want the schemas to reference the definitions somewhere + else, e.g. for OpenAPI use ``#/components/schemas/``. The resulting generated schemas will still be at the + top-level key ``definitions``, so you can extract them from there. But all the references will have the set + prefix. + :param ref_template: Use a ``string.format()`` template for ``$ref`` instead of a prefix. This can be useful + for references that cannot be represented by ``ref_prefix`` such as a definition stored in another file. For + a sibling json file in a ``/schemas`` directory use ``"/schemas/${model}.json#"``. + :return: dict with the JSON Schema with a ``definitions`` top-level key including the schema definitions for + the models and sub-models passed in ``models``. + """ + clean_models = [get_model(model) for model in models] + flat_models = get_flat_models_from_models(clean_models) + model_name_map = get_model_name_map(flat_models) + definitions = {} + output_schema: Dict[str, Any] = {} + if title: + output_schema['title'] = title + if description: + output_schema['description'] = description + for model in clean_models: + m_schema, m_definitions, m_nested_models = model_process_schema( + model, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + ) + definitions.update(m_definitions) + model_name = model_name_map[model] + definitions[model_name] = m_schema + if definitions: + output_schema['definitions'] = definitions + return output_schema + + +def model_schema( + model: Union[Type['BaseModel'], Type['Dataclass']], + by_alias: bool = True, + ref_prefix: Optional[str] = None, + ref_template: str = default_ref_template, +) -> Dict[str, Any]: + """ + Generate a JSON Schema for one model. With all the sub-models defined in the ``definitions`` top-level + JSON key. + + :param model: a Pydantic model (a class that inherits from BaseModel) + :param by_alias: generate the schemas using the aliases defined, if any + :param ref_prefix: the JSON Pointer prefix for schema references with ``$ref``, if None, will be set to the + default of ``#/definitions/``. Update it if you want the schemas to reference the definitions somewhere + else, e.g. for OpenAPI use ``#/components/schemas/``. The resulting generated schemas will still be at the + top-level key ``definitions``, so you can extract them from there. But all the references will have the set + prefix. + :param ref_template: Use a ``string.format()`` template for ``$ref`` instead of a prefix. This can be useful for + references that cannot be represented by ``ref_prefix`` such as a definition stored in another file. For a + sibling json file in a ``/schemas`` directory use ``"/schemas/${model}.json#"``. + :return: dict with the JSON Schema for the passed ``model`` + """ + model = get_model(model) + flat_models = get_flat_models_from_model(model) + model_name_map = get_model_name_map(flat_models) + model_name = model_name_map[model] + m_schema, m_definitions, nested_models = model_process_schema( + model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, ref_template=ref_template + ) + if model_name in nested_models: + # model_name is in Nested models, it has circular references + m_definitions[model_name] = m_schema + m_schema = get_schema_ref(model_name, ref_prefix, ref_template, False) + if m_definitions: + m_schema.update({'definitions': m_definitions}) + return m_schema + + +def get_field_info_schema(field: ModelField, schema_overrides: bool = False) -> Tuple[Dict[str, Any], bool]: + # If no title is explicitly set, we don't set title in the schema for enums. + # The behaviour is the same as `BaseModel` reference, where the default title + # is in the definitions part of the schema. + schema_: Dict[str, Any] = {} + if field.field_info.title or not lenient_issubclass(field.type_, Enum): + schema_['title'] = field.field_info.title or field.alias.title().replace('_', ' ') + + if field.field_info.title: + schema_overrides = True + + if field.field_info.description: + schema_['description'] = field.field_info.description + schema_overrides = True + + if not field.required and field.default is not None and not is_callable_type(field.outer_type_): + schema_['default'] = encode_default(field.default) + schema_overrides = True + + return schema_, schema_overrides + + +def field_schema( + field: ModelField, + *, + by_alias: bool = True, + model_name_map: Dict[TypeModelOrEnum, str], + ref_prefix: Optional[str] = None, + ref_template: str = default_ref_template, + known_models: Optional[TypeModelSet] = None, +) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: + """ + Process a Pydantic field and return a tuple with a JSON Schema for it as the first item. + Also return a dictionary of definitions with models as keys and their schemas as values. If the passed field + is a model and has sub-models, and those sub-models don't have overrides (as ``title``, ``default``, etc), they + will be included in the definitions and referenced in the schema instead of included recursively. + + :param field: a Pydantic ``ModelField`` + :param by_alias: use the defined alias (if any) in the returned schema + :param model_name_map: used to generate the JSON Schema references to other models included in the definitions + :param ref_prefix: the JSON Pointer prefix to use for references to other schemas, if None, the default of + #/definitions/ will be used + :param ref_template: Use a ``string.format()`` template for ``$ref`` instead of a prefix. This can be useful for + references that cannot be represented by ``ref_prefix`` such as a definition stored in another file. For a + sibling json file in a ``/schemas`` directory use ``"/schemas/${model}.json#"``. + :param known_models: used to solve circular references + :return: tuple of the schema for this field and additional definitions + """ + s, schema_overrides = get_field_info_schema(field) + + validation_schema = get_field_schema_validations(field) + if validation_schema: + s.update(validation_schema) + schema_overrides = True + + f_schema, f_definitions, f_nested_models = field_type_schema( + field, + by_alias=by_alias, + model_name_map=model_name_map, + schema_overrides=schema_overrides, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models or set(), + ) + + # $ref will only be returned when there are no schema_overrides + if '$ref' in f_schema: + return f_schema, f_definitions, f_nested_models + else: + s.update(f_schema) + return s, f_definitions, f_nested_models + + +numeric_types = (int, float, Decimal) +_str_types_attrs: Tuple[Tuple[str, Union[type, Tuple[type, ...]], str], ...] = ( + ('max_length', numeric_types, 'maxLength'), + ('min_length', numeric_types, 'minLength'), + ('regex', str, 'pattern'), +) + +_numeric_types_attrs: Tuple[Tuple[str, Union[type, Tuple[type, ...]], str], ...] = ( + ('gt', numeric_types, 'exclusiveMinimum'), + ('lt', numeric_types, 'exclusiveMaximum'), + ('ge', numeric_types, 'minimum'), + ('le', numeric_types, 'maximum'), + ('multiple_of', numeric_types, 'multipleOf'), +) + + +def get_field_schema_validations(field: ModelField) -> Dict[str, Any]: + """ + Get the JSON Schema validation keywords for a ``field`` with an annotation of + a Pydantic ``FieldInfo`` with validation arguments. + """ + f_schema: Dict[str, Any] = {} + + if lenient_issubclass(field.type_, Enum): + # schema is already updated by `enum_process_schema`; just update with field extra + if field.field_info.extra: + f_schema.update(field.field_info.extra) + return f_schema + + if lenient_issubclass(field.type_, (str, bytes)): + for attr_name, t, keyword in _str_types_attrs: + attr = getattr(field.field_info, attr_name, None) + if isinstance(attr, t): + f_schema[keyword] = attr + if lenient_issubclass(field.type_, numeric_types) and not issubclass(field.type_, bool): + for attr_name, t, keyword in _numeric_types_attrs: + attr = getattr(field.field_info, attr_name, None) + if isinstance(attr, t): + f_schema[keyword] = attr + if field.field_info is not None and field.field_info.const: + f_schema['const'] = field.default + if field.field_info.extra: + f_schema.update(field.field_info.extra) + modify_schema = getattr(field.outer_type_, '__modify_schema__', None) + if modify_schema: + _apply_modify_schema(modify_schema, field, f_schema) + return f_schema + + +def get_model_name_map(unique_models: TypeModelSet) -> Dict[TypeModelOrEnum, str]: + """ + Process a set of models and generate unique names for them to be used as keys in the JSON Schema + definitions. By default the names are the same as the class name. But if two models in different Python + modules have the same name (e.g. "users.Model" and "items.Model"), the generated names will be + based on the Python module path for those conflicting models to prevent name collisions. + + :param unique_models: a Python set of models + :return: dict mapping models to names + """ + name_model_map = {} + conflicting_names: Set[str] = set() + for model in unique_models: + model_name = normalize_name(model.__name__) + if model_name in conflicting_names: + model_name = get_long_model_name(model) + name_model_map[model_name] = model + elif model_name in name_model_map: + conflicting_names.add(model_name) + conflicting_model = name_model_map.pop(model_name) + name_model_map[get_long_model_name(conflicting_model)] = conflicting_model + name_model_map[get_long_model_name(model)] = model + else: + name_model_map[model_name] = model + return {v: k for k, v in name_model_map.items()} + + +def get_flat_models_from_model(model: Type['BaseModel'], known_models: Optional[TypeModelSet] = None) -> TypeModelSet: + """ + Take a single ``model`` and generate a set with itself and all the sub-models in the tree. I.e. if you pass + model ``Foo`` (subclass of Pydantic ``BaseModel``) as ``model``, and it has a field of type ``Bar`` (also + subclass of ``BaseModel``) and that model ``Bar`` has a field of type ``Baz`` (also subclass of ``BaseModel``), + the return value will be ``set([Foo, Bar, Baz])``. + + :param model: a Pydantic ``BaseModel`` subclass + :param known_models: used to solve circular references + :return: a set with the initial model and all its sub-models + """ + known_models = known_models or set() + flat_models: TypeModelSet = set() + flat_models.add(model) + known_models |= flat_models + fields = cast(Sequence[ModelField], model.__fields__.values()) + flat_models |= get_flat_models_from_fields(fields, known_models=known_models) + return flat_models + + +def get_flat_models_from_field(field: ModelField, known_models: TypeModelSet) -> TypeModelSet: + """ + Take a single Pydantic ``ModelField`` (from a model) that could have been declared as a subclass of BaseModel + (so, it could be a submodel), and generate a set with its model and all the sub-models in the tree. + I.e. if you pass a field that was declared to be of type ``Foo`` (subclass of BaseModel) as ``field``, and that + model ``Foo`` has a field of type ``Bar`` (also subclass of ``BaseModel``) and that model ``Bar`` has a field of + type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. + + :param field: a Pydantic ``ModelField`` + :param known_models: used to solve circular references + :return: a set with the model used in the declaration for this field, if any, and all its sub-models + """ + from pydantic.v1.main import BaseModel + + flat_models: TypeModelSet = set() + + field_type = field.type_ + if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), BaseModel): + field_type = field_type.__pydantic_model__ + + if field.sub_fields and not lenient_issubclass(field_type, BaseModel): + flat_models |= get_flat_models_from_fields(field.sub_fields, known_models=known_models) + elif lenient_issubclass(field_type, BaseModel) and field_type not in known_models: + flat_models |= get_flat_models_from_model(field_type, known_models=known_models) + elif lenient_issubclass(field_type, Enum): + flat_models.add(field_type) + return flat_models + + +def get_flat_models_from_fields(fields: Sequence[ModelField], known_models: TypeModelSet) -> TypeModelSet: + """ + Take a list of Pydantic ``ModelField``s (from a model) that could have been declared as subclasses of ``BaseModel`` + (so, any of them could be a submodel), and generate a set with their models and all the sub-models in the tree. + I.e. if you pass a the fields of a model ``Foo`` (subclass of ``BaseModel``) as ``fields``, and on of them has a + field of type ``Bar`` (also subclass of ``BaseModel``) and that model ``Bar`` has a field of type ``Baz`` (also + subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. + + :param fields: a list of Pydantic ``ModelField``s + :param known_models: used to solve circular references + :return: a set with any model declared in the fields, and all their sub-models + """ + flat_models: TypeModelSet = set() + for field in fields: + flat_models |= get_flat_models_from_field(field, known_models=known_models) + return flat_models + + +def get_flat_models_from_models(models: Sequence[Type['BaseModel']]) -> TypeModelSet: + """ + Take a list of ``models`` and generate a set with them and all their sub-models in their trees. I.e. if you pass + a list of two models, ``Foo`` and ``Bar``, both subclasses of Pydantic ``BaseModel`` as models, and ``Bar`` has + a field of type ``Baz`` (also subclass of ``BaseModel``), the return value will be ``set([Foo, Bar, Baz])``. + """ + flat_models: TypeModelSet = set() + for model in models: + flat_models |= get_flat_models_from_model(model) + return flat_models + + +def get_long_model_name(model: TypeModelOrEnum) -> str: + return f'{model.__module__}__{model.__qualname__}'.replace('.', '__') + + +def field_type_schema( + field: ModelField, + *, + by_alias: bool, + model_name_map: Dict[TypeModelOrEnum, str], + ref_template: str, + schema_overrides: bool = False, + ref_prefix: Optional[str] = None, + known_models: TypeModelSet, +) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: + """ + Used by ``field_schema()``, you probably should be using that function. + + Take a single ``field`` and generate the schema for its type only, not including additional + information as title, etc. Also return additional schema definitions, from sub-models. + """ + from pydantic.v1.main import BaseModel # noqa: F811 + + definitions = {} + nested_models: Set[str] = set() + f_schema: Dict[str, Any] + if field.shape in { + SHAPE_LIST, + SHAPE_TUPLE_ELLIPSIS, + SHAPE_SEQUENCE, + SHAPE_SET, + SHAPE_FROZENSET, + SHAPE_ITERABLE, + SHAPE_DEQUE, + }: + items_schema, f_definitions, f_nested_models = field_singleton_schema( + field, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + definitions.update(f_definitions) + nested_models.update(f_nested_models) + f_schema = {'type': 'array', 'items': items_schema} + if field.shape in {SHAPE_SET, SHAPE_FROZENSET}: + f_schema['uniqueItems'] = True + + elif field.shape in MAPPING_LIKE_SHAPES: + f_schema = {'type': 'object'} + key_field = cast(ModelField, field.key_field) + regex = getattr(key_field.type_, 'regex', None) + items_schema, f_definitions, f_nested_models = field_singleton_schema( + field, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + definitions.update(f_definitions) + nested_models.update(f_nested_models) + if regex: + # Dict keys have a regex pattern + # items_schema might be a schema or empty dict, add it either way + f_schema['patternProperties'] = {ConstrainedStr._get_pattern(regex): items_schema} + if items_schema: + # The dict values are not simply Any, so they need a schema + f_schema['additionalProperties'] = items_schema + elif field.shape == SHAPE_TUPLE or (field.shape == SHAPE_GENERIC and not issubclass(field.type_, BaseModel)): + sub_schema = [] + sub_fields = cast(List[ModelField], field.sub_fields) + for sf in sub_fields: + sf_schema, sf_definitions, sf_nested_models = field_type_schema( + sf, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + definitions.update(sf_definitions) + nested_models.update(sf_nested_models) + sub_schema.append(sf_schema) + + sub_fields_len = len(sub_fields) + if field.shape == SHAPE_GENERIC: + all_of_schemas = sub_schema[0] if sub_fields_len == 1 else {'type': 'array', 'items': sub_schema} + f_schema = {'allOf': [all_of_schemas]} + else: + f_schema = { + 'type': 'array', + 'minItems': sub_fields_len, + 'maxItems': sub_fields_len, + } + if sub_fields_len >= 1: + f_schema['items'] = sub_schema + else: + assert field.shape in {SHAPE_SINGLETON, SHAPE_GENERIC}, field.shape + f_schema, f_definitions, f_nested_models = field_singleton_schema( + field, + by_alias=by_alias, + model_name_map=model_name_map, + schema_overrides=schema_overrides, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + definitions.update(f_definitions) + nested_models.update(f_nested_models) + + # check field type to avoid repeated calls to the same __modify_schema__ method + if field.type_ != field.outer_type_: + if field.shape == SHAPE_GENERIC: + field_type = field.type_ + else: + field_type = field.outer_type_ + modify_schema = getattr(field_type, '__modify_schema__', None) + if modify_schema: + _apply_modify_schema(modify_schema, field, f_schema) + return f_schema, definitions, nested_models + + +def model_process_schema( + model: TypeModelOrEnum, + *, + by_alias: bool = True, + model_name_map: Dict[TypeModelOrEnum, str], + ref_prefix: Optional[str] = None, + ref_template: str = default_ref_template, + known_models: Optional[TypeModelSet] = None, + field: Optional[ModelField] = None, +) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: + """ + Used by ``model_schema()``, you probably should be using that function. + + Take a single ``model`` and generate its schema. Also return additional schema definitions, from sub-models. The + sub-models of the returned schema will be referenced, but their definitions will not be included in the schema. All + the definitions are returned as the second value. + """ + from inspect import getdoc, signature + + known_models = known_models or set() + if lenient_issubclass(model, Enum): + model = cast(Type[Enum], model) + s = enum_process_schema(model, field=field) + return s, {}, set() + model = cast(Type['BaseModel'], model) + s = {'title': model.__config__.title or model.__name__} + doc = getdoc(model) + if doc: + s['description'] = doc + known_models.add(model) + m_schema, m_definitions, nested_models = model_type_schema( + model, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + s.update(m_schema) + schema_extra = model.__config__.schema_extra + if callable(schema_extra): + if len(signature(schema_extra).parameters) == 1: + schema_extra(s) + else: + schema_extra(s, model) + else: + s.update(schema_extra) + return s, m_definitions, nested_models + + +def model_type_schema( + model: Type['BaseModel'], + *, + by_alias: bool, + model_name_map: Dict[TypeModelOrEnum, str], + ref_template: str, + ref_prefix: Optional[str] = None, + known_models: TypeModelSet, +) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: + """ + You probably should be using ``model_schema()``, this function is indirectly used by that function. + + Take a single ``model`` and generate the schema for its type only, not including additional + information as title, etc. Also return additional schema definitions, from sub-models. + """ + properties = {} + required = [] + definitions: Dict[str, Any] = {} + nested_models: Set[str] = set() + for k, f in model.__fields__.items(): + try: + f_schema, f_definitions, f_nested_models = field_schema( + f, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + except SkipField as skip: + warnings.warn(skip.message, UserWarning) + continue + definitions.update(f_definitions) + nested_models.update(f_nested_models) + if by_alias: + properties[f.alias] = f_schema + if f.required: + required.append(f.alias) + else: + properties[k] = f_schema + if f.required: + required.append(k) + if ROOT_KEY in properties: + out_schema = properties[ROOT_KEY] + out_schema['title'] = model.__config__.title or model.__name__ + else: + out_schema = {'type': 'object', 'properties': properties} + if required: + out_schema['required'] = required + if model.__config__.extra == 'forbid': + out_schema['additionalProperties'] = False + return out_schema, definitions, nested_models + + +def enum_process_schema(enum: Type[Enum], *, field: Optional[ModelField] = None) -> Dict[str, Any]: + """ + Take a single `enum` and generate its schema. + + This is similar to the `model_process_schema` function, but applies to ``Enum`` objects. + """ + import inspect + + schema_: Dict[str, Any] = { + 'title': enum.__name__, + # Python assigns all enums a default docstring value of 'An enumeration', so + # all enums will have a description field even if not explicitly provided. + 'description': inspect.cleandoc(enum.__doc__ or 'An enumeration.'), + # Add enum values and the enum field type to the schema. + 'enum': [item.value for item in cast(Iterable[Enum], enum)], + } + + add_field_type_to_schema(enum, schema_) + + modify_schema = getattr(enum, '__modify_schema__', None) + if modify_schema: + _apply_modify_schema(modify_schema, field, schema_) + + return schema_ + + +def field_singleton_sub_fields_schema( + field: ModelField, + *, + by_alias: bool, + model_name_map: Dict[TypeModelOrEnum, str], + ref_template: str, + schema_overrides: bool = False, + ref_prefix: Optional[str] = None, + known_models: TypeModelSet, +) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: + """ + This function is indirectly used by ``field_schema()``, you probably should be using that function. + + Take a list of Pydantic ``ModelField`` from the declaration of a type with parameters, and generate their + schema. I.e., fields used as "type parameters", like ``str`` and ``int`` in ``Tuple[str, int]``. + """ + sub_fields = cast(List[ModelField], field.sub_fields) + definitions = {} + nested_models: Set[str] = set() + if len(sub_fields) == 1: + return field_type_schema( + sub_fields[0], + by_alias=by_alias, + model_name_map=model_name_map, + schema_overrides=schema_overrides, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + else: + s: Dict[str, Any] = {} + # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#discriminator-object + field_has_discriminator: bool = field.discriminator_key is not None + if field_has_discriminator: + assert field.sub_fields_mapping is not None + + discriminator_models_refs: Dict[str, Union[str, Dict[str, Any]]] = {} + + for discriminator_value, sub_field in field.sub_fields_mapping.items(): + if isinstance(discriminator_value, Enum): + discriminator_value = str(discriminator_value.value) + # sub_field is either a `BaseModel` or directly an `Annotated` `Union` of many + if is_union(get_origin(sub_field.type_)): + sub_models = get_sub_types(sub_field.type_) + discriminator_models_refs[discriminator_value] = { + model_name_map[sub_model]: get_schema_ref( + model_name_map[sub_model], ref_prefix, ref_template, False + ) + for sub_model in sub_models + } + else: + sub_field_type = sub_field.type_ + if hasattr(sub_field_type, '__pydantic_model__'): + sub_field_type = sub_field_type.__pydantic_model__ + + discriminator_model_name = model_name_map[sub_field_type] + discriminator_model_ref = get_schema_ref(discriminator_model_name, ref_prefix, ref_template, False) + discriminator_models_refs[discriminator_value] = discriminator_model_ref['$ref'] + + s['discriminator'] = { + 'propertyName': field.discriminator_alias, + 'mapping': discriminator_models_refs, + } + + sub_field_schemas = [] + for sf in sub_fields: + sub_schema, sub_definitions, sub_nested_models = field_type_schema( + sf, + by_alias=by_alias, + model_name_map=model_name_map, + schema_overrides=schema_overrides, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + definitions.update(sub_definitions) + if schema_overrides and 'allOf' in sub_schema: + # if the sub_field is a referenced schema we only need the referenced + # object. Otherwise we will end up with several allOf inside anyOf/oneOf. + # See https://github.com/pydantic/pydantic/issues/1209 + sub_schema = sub_schema['allOf'][0] + + if sub_schema.keys() == {'discriminator', 'oneOf'}: + # we don't want discriminator information inside oneOf choices, this is dealt with elsewhere + sub_schema.pop('discriminator') + sub_field_schemas.append(sub_schema) + nested_models.update(sub_nested_models) + s['oneOf' if field_has_discriminator else 'anyOf'] = sub_field_schemas + return s, definitions, nested_models + + +# Order is important, e.g. subclasses of str must go before str +# this is used only for standard library types, custom types should use __modify_schema__ instead +field_class_to_schema: Tuple[Tuple[Any, Dict[str, Any]], ...] = ( + (Path, {'type': 'string', 'format': 'path'}), + (datetime, {'type': 'string', 'format': 'date-time'}), + (date, {'type': 'string', 'format': 'date'}), + (time, {'type': 'string', 'format': 'time'}), + (timedelta, {'type': 'number', 'format': 'time-delta'}), + (IPv4Network, {'type': 'string', 'format': 'ipv4network'}), + (IPv6Network, {'type': 'string', 'format': 'ipv6network'}), + (IPv4Interface, {'type': 'string', 'format': 'ipv4interface'}), + (IPv6Interface, {'type': 'string', 'format': 'ipv6interface'}), + (IPv4Address, {'type': 'string', 'format': 'ipv4'}), + (IPv6Address, {'type': 'string', 'format': 'ipv6'}), + (Pattern, {'type': 'string', 'format': 'regex'}), + (str, {'type': 'string'}), + (bytes, {'type': 'string', 'format': 'binary'}), + (bool, {'type': 'boolean'}), + (int, {'type': 'integer'}), + (float, {'type': 'number'}), + (Decimal, {'type': 'number'}), + (UUID, {'type': 'string', 'format': 'uuid'}), + (dict, {'type': 'object'}), + (list, {'type': 'array', 'items': {}}), + (tuple, {'type': 'array', 'items': {}}), + (set, {'type': 'array', 'items': {}, 'uniqueItems': True}), + (frozenset, {'type': 'array', 'items': {}, 'uniqueItems': True}), +) + +json_scheme = {'type': 'string', 'format': 'json-string'} + + +def add_field_type_to_schema(field_type: Any, schema_: Dict[str, Any]) -> None: + """ + Update the given `schema` with the type-specific metadata for the given `field_type`. + + This function looks through `field_class_to_schema` for a class that matches the given `field_type`, + and then modifies the given `schema` with the information from that type. + """ + for type_, t_schema in field_class_to_schema: + # Fallback for `typing.Pattern` and `re.Pattern` as they are not a valid class + if lenient_issubclass(field_type, type_) or field_type is type_ is Pattern: + schema_.update(t_schema) + break + + +def get_schema_ref(name: str, ref_prefix: Optional[str], ref_template: str, schema_overrides: bool) -> Dict[str, Any]: + if ref_prefix: + schema_ref = {'$ref': ref_prefix + name} + else: + schema_ref = {'$ref': ref_template.format(model=name)} + return {'allOf': [schema_ref]} if schema_overrides else schema_ref + + +def field_singleton_schema( # noqa: C901 (ignore complexity) + field: ModelField, + *, + by_alias: bool, + model_name_map: Dict[TypeModelOrEnum, str], + ref_template: str, + schema_overrides: bool = False, + ref_prefix: Optional[str] = None, + known_models: TypeModelSet, +) -> Tuple[Dict[str, Any], Dict[str, Any], Set[str]]: + """ + This function is indirectly used by ``field_schema()``, you should probably be using that function. + + Take a single Pydantic ``ModelField``, and return its schema and any additional definitions from sub-models. + """ + from pydantic.v1.main import BaseModel + + definitions: Dict[str, Any] = {} + nested_models: Set[str] = set() + field_type = field.type_ + + # Recurse into this field if it contains sub_fields and is NOT a + # BaseModel OR that BaseModel is a const + if field.sub_fields and ( + (field.field_info and field.field_info.const) or not lenient_issubclass(field_type, BaseModel) + ): + return field_singleton_sub_fields_schema( + field, + by_alias=by_alias, + model_name_map=model_name_map, + schema_overrides=schema_overrides, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + if field_type is Any or field_type is object or field_type.__class__ == TypeVar or get_origin(field_type) is type: + return {}, definitions, nested_models # no restrictions + if is_none_type(field_type): + return {'type': 'null'}, definitions, nested_models + if is_callable_type(field_type): + raise SkipField(f'Callable {field.name} was excluded from schema since JSON schema has no equivalent type.') + f_schema: Dict[str, Any] = {} + if field.field_info is not None and field.field_info.const: + f_schema['const'] = field.default + + if is_literal_type(field_type): + values = tuple(x.value if isinstance(x, Enum) else x for x in all_literal_values(field_type)) + + if len({v.__class__ for v in values}) > 1: + return field_schema( + multitypes_literal_field_for_schema(values, field), + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + ) + + # All values have the same type + field_type = values[0].__class__ + f_schema['enum'] = list(values) + add_field_type_to_schema(field_type, f_schema) + elif lenient_issubclass(field_type, Enum): + enum_name = model_name_map[field_type] + f_schema, schema_overrides = get_field_info_schema(field, schema_overrides) + f_schema.update(get_schema_ref(enum_name, ref_prefix, ref_template, schema_overrides)) + definitions[enum_name] = enum_process_schema(field_type, field=field) + elif is_namedtuple(field_type): + sub_schema, *_ = model_process_schema( + field_type.__pydantic_model__, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + field=field, + ) + items_schemas = list(sub_schema['properties'].values()) + f_schema.update( + { + 'type': 'array', + 'items': items_schemas, + 'minItems': len(items_schemas), + 'maxItems': len(items_schemas), + } + ) + elif not hasattr(field_type, '__pydantic_model__'): + add_field_type_to_schema(field_type, f_schema) + + modify_schema = getattr(field_type, '__modify_schema__', None) + if modify_schema: + _apply_modify_schema(modify_schema, field, f_schema) + + if f_schema: + return f_schema, definitions, nested_models + + # Handle dataclass-based models + if lenient_issubclass(getattr(field_type, '__pydantic_model__', None), BaseModel): + field_type = field_type.__pydantic_model__ + + if issubclass(field_type, BaseModel): + model_name = model_name_map[field_type] + if field_type not in known_models: + sub_schema, sub_definitions, sub_nested_models = model_process_schema( + field_type, + by_alias=by_alias, + model_name_map=model_name_map, + ref_prefix=ref_prefix, + ref_template=ref_template, + known_models=known_models, + field=field, + ) + definitions.update(sub_definitions) + definitions[model_name] = sub_schema + nested_models.update(sub_nested_models) + else: + nested_models.add(model_name) + schema_ref = get_schema_ref(model_name, ref_prefix, ref_template, schema_overrides) + return schema_ref, definitions, nested_models + + # For generics with no args + args = get_args(field_type) + if args is not None and not args and Generic in field_type.__bases__: + return f_schema, definitions, nested_models + + raise ValueError(f'Value not declarable with JSON Schema, field: {field}') + + +def multitypes_literal_field_for_schema(values: Tuple[Any, ...], field: ModelField) -> ModelField: + """ + To support `Literal` with values of different types, we split it into multiple `Literal` with same type + e.g. `Literal['qwe', 'asd', 1, 2]` becomes `Union[Literal['qwe', 'asd'], Literal[1, 2]]` + """ + literal_distinct_types = defaultdict(list) + for v in values: + literal_distinct_types[v.__class__].append(v) + distinct_literals = (Literal[tuple(same_type_values)] for same_type_values in literal_distinct_types.values()) + + return ModelField( + name=field.name, + type_=Union[tuple(distinct_literals)], # type: ignore + class_validators=field.class_validators, + model_config=field.model_config, + default=field.default, + required=field.required, + alias=field.alias, + field_info=field.field_info, + ) + + +def encode_default(dft: Any) -> Any: + from pydantic.v1.main import BaseModel + + if isinstance(dft, BaseModel) or is_dataclass(dft): + dft = cast('dict[str, Any]', pydantic_encoder(dft)) + + if isinstance(dft, dict): + return {encode_default(k): encode_default(v) for k, v in dft.items()} + elif isinstance(dft, Enum): + return dft.value + elif isinstance(dft, (int, float, str)): + return dft + elif isinstance(dft, (list, tuple)): + t = dft.__class__ + seq_args = (encode_default(v) for v in dft) + return t(*seq_args) if is_namedtuple(t) else t(seq_args) + elif dft is None: + return None + else: + return pydantic_encoder(dft) + + +_map_types_constraint: Dict[Any, Callable[..., type]] = {int: conint, float: confloat, Decimal: condecimal} + + +def get_annotation_from_field_info( + annotation: Any, field_info: FieldInfo, field_name: str, validate_assignment: bool = False +) -> Type[Any]: + """ + Get an annotation with validation implemented for numbers and strings based on the field_info. + :param annotation: an annotation from a field specification, as ``str``, ``ConstrainedStr`` + :param field_info: an instance of FieldInfo, possibly with declarations for validations and JSON Schema + :param field_name: name of the field for use in error messages + :param validate_assignment: default False, flag for BaseModel Config value of validate_assignment + :return: the same ``annotation`` if unmodified or a new annotation with validation in place + """ + constraints = field_info.get_constraints() + used_constraints: Set[str] = set() + if constraints: + annotation, used_constraints = get_annotation_with_constraints(annotation, field_info) + if validate_assignment: + used_constraints.add('allow_mutation') + + unused_constraints = constraints - used_constraints + if unused_constraints: + raise ValueError( + f'On field "{field_name}" the following field constraints are set but not enforced: ' + f'{", ".join(unused_constraints)}. ' + f'\nFor more details see https://docs.pydantic.dev/usage/schema/#unenforced-field-constraints' + ) + + return annotation + + +def get_annotation_with_constraints(annotation: Any, field_info: FieldInfo) -> Tuple[Type[Any], Set[str]]: # noqa: C901 + """ + Get an annotation with used constraints implemented for numbers and strings based on the field_info. + + :param annotation: an annotation from a field specification, as ``str``, ``ConstrainedStr`` + :param field_info: an instance of FieldInfo, possibly with declarations for validations and JSON Schema + :return: the same ``annotation`` if unmodified or a new annotation along with the used constraints. + """ + used_constraints: Set[str] = set() + + def go(type_: Any) -> Type[Any]: + if ( + is_literal_type(type_) + or isinstance(type_, ForwardRef) + or lenient_issubclass(type_, (ConstrainedList, ConstrainedSet, ConstrainedFrozenSet)) + ): + return type_ + origin = get_origin(type_) + if origin is not None: + args: Tuple[Any, ...] = get_args(type_) + if any(isinstance(a, ForwardRef) for a in args): + # forward refs cause infinite recursion below + return type_ + + if origin is Annotated: + return go(args[0]) + if is_union(origin): + return Union[tuple(go(a) for a in args)] # type: ignore + + if issubclass(origin, List) and ( + field_info.min_items is not None + or field_info.max_items is not None + or field_info.unique_items is not None + ): + used_constraints.update({'min_items', 'max_items', 'unique_items'}) + return conlist( + go(args[0]), + min_items=field_info.min_items, + max_items=field_info.max_items, + unique_items=field_info.unique_items, + ) + + if issubclass(origin, Set) and (field_info.min_items is not None or field_info.max_items is not None): + used_constraints.update({'min_items', 'max_items'}) + return conset(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) + + if issubclass(origin, FrozenSet) and (field_info.min_items is not None or field_info.max_items is not None): + used_constraints.update({'min_items', 'max_items'}) + return confrozenset(go(args[0]), min_items=field_info.min_items, max_items=field_info.max_items) + + for t in (Tuple, List, Set, FrozenSet, Sequence): + if issubclass(origin, t): # type: ignore + return t[tuple(go(a) for a in args)] # type: ignore + + if issubclass(origin, Dict): + return Dict[args[0], go(args[1])] # type: ignore + + attrs: Optional[Tuple[str, ...]] = None + constraint_func: Optional[Callable[..., type]] = None + if isinstance(type_, type): + if issubclass(type_, (SecretStr, SecretBytes)): + attrs = ('max_length', 'min_length') + + def constraint_func(**kw: Any) -> Type[Any]: # noqa: F811 + return type(type_.__name__, (type_,), kw) + + elif issubclass(type_, str) and not issubclass(type_, (EmailStr, AnyUrl)): + attrs = ('max_length', 'min_length', 'regex') + if issubclass(type_, StrictStr): + + def constraint_func(**kw: Any) -> Type[Any]: + return type(type_.__name__, (type_,), kw) + + else: + constraint_func = constr + elif issubclass(type_, bytes): + attrs = ('max_length', 'min_length', 'regex') + if issubclass(type_, StrictBytes): + + def constraint_func(**kw: Any) -> Type[Any]: + return type(type_.__name__, (type_,), kw) + + else: + constraint_func = conbytes + elif issubclass(type_, numeric_types) and not issubclass( + type_, + ( + ConstrainedInt, + ConstrainedFloat, + ConstrainedDecimal, + ConstrainedList, + ConstrainedSet, + ConstrainedFrozenSet, + bool, + ), + ): + # Is numeric type + attrs = ('gt', 'lt', 'ge', 'le', 'multiple_of') + if issubclass(type_, float): + attrs += ('allow_inf_nan',) + if issubclass(type_, Decimal): + attrs += ('max_digits', 'decimal_places') + numeric_type = next(t for t in numeric_types if issubclass(type_, t)) # pragma: no branch + constraint_func = _map_types_constraint[numeric_type] + + if attrs: + used_constraints.update(set(attrs)) + kwargs = { + attr_name: attr + for attr_name, attr in ((attr_name, getattr(field_info, attr_name)) for attr_name in attrs) + if attr is not None + } + if kwargs: + constraint_func = cast(Callable[..., type], constraint_func) + return constraint_func(**kwargs) + return type_ + + return go(annotation), used_constraints + + +def normalize_name(name: str) -> str: + """ + Normalizes the given name. This can be applied to either a model *or* enum. + """ + return re.sub(r'[^a-zA-Z0-9.\-_]', '_', name) + + +class SkipField(Exception): + """ + Utility exception used to exclude fields from schema. + """ + + def __init__(self, message: str) -> None: + self.message = message diff --git a/env/Lib/site-packages/pydantic/v1/tools.py b/env/Lib/site-packages/pydantic/v1/tools.py new file mode 100644 index 0000000..6838a23 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/tools.py @@ -0,0 +1,92 @@ +import json +from functools import lru_cache +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Optional, Type, TypeVar, Union + +from pydantic.v1.parse import Protocol, load_file, load_str_bytes +from pydantic.v1.types import StrBytes +from pydantic.v1.typing import display_as_type + +__all__ = ('parse_file_as', 'parse_obj_as', 'parse_raw_as', 'schema_of', 'schema_json_of') + +NameFactory = Union[str, Callable[[Type[Any]], str]] + +if TYPE_CHECKING: + from pydantic.v1.typing import DictStrAny + + +def _generate_parsing_type_name(type_: Any) -> str: + return f'ParsingModel[{display_as_type(type_)}]' + + +@lru_cache(maxsize=2048) +def _get_parsing_type(type_: Any, *, type_name: Optional[NameFactory] = None) -> Any: + from pydantic.v1.main import create_model + + if type_name is None: + type_name = _generate_parsing_type_name + if not isinstance(type_name, str): + type_name = type_name(type_) + return create_model(type_name, __root__=(type_, ...)) + + +T = TypeVar('T') + + +def parse_obj_as(type_: Type[T], obj: Any, *, type_name: Optional[NameFactory] = None) -> T: + model_type = _get_parsing_type(type_, type_name=type_name) # type: ignore[arg-type] + return model_type(__root__=obj).__root__ + + +def parse_file_as( + type_: Type[T], + path: Union[str, Path], + *, + content_type: str = None, + encoding: str = 'utf8', + proto: Protocol = None, + allow_pickle: bool = False, + json_loads: Callable[[str], Any] = json.loads, + type_name: Optional[NameFactory] = None, +) -> T: + obj = load_file( + path, + proto=proto, + content_type=content_type, + encoding=encoding, + allow_pickle=allow_pickle, + json_loads=json_loads, + ) + return parse_obj_as(type_, obj, type_name=type_name) + + +def parse_raw_as( + type_: Type[T], + b: StrBytes, + *, + content_type: str = None, + encoding: str = 'utf8', + proto: Protocol = None, + allow_pickle: bool = False, + json_loads: Callable[[str], Any] = json.loads, + type_name: Optional[NameFactory] = None, +) -> T: + obj = load_str_bytes( + b, + proto=proto, + content_type=content_type, + encoding=encoding, + allow_pickle=allow_pickle, + json_loads=json_loads, + ) + return parse_obj_as(type_, obj, type_name=type_name) + + +def schema_of(type_: Any, *, title: Optional[NameFactory] = None, **schema_kwargs: Any) -> 'DictStrAny': + """Generate a JSON schema (as dict) for the passed model or dynamically generated one""" + return _get_parsing_type(type_, type_name=title).schema(**schema_kwargs) + + +def schema_json_of(type_: Any, *, title: Optional[NameFactory] = None, **schema_json_kwargs: Any) -> str: + """Generate a JSON schema (as JSON) for the passed model or dynamically generated one""" + return _get_parsing_type(type_, type_name=title).schema_json(**schema_json_kwargs) diff --git a/env/Lib/site-packages/pydantic/v1/types.py b/env/Lib/site-packages/pydantic/v1/types.py new file mode 100644 index 0000000..0cd789a --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/types.py @@ -0,0 +1,1205 @@ +import abc +import math +import re +import warnings +from datetime import date +from decimal import Decimal, InvalidOperation +from enum import Enum +from pathlib import Path +from types import new_class +from typing import ( + TYPE_CHECKING, + Any, + Callable, + ClassVar, + Dict, + FrozenSet, + List, + Optional, + Pattern, + Set, + Tuple, + Type, + TypeVar, + Union, + cast, + overload, +) +from uuid import UUID +from weakref import WeakSet + +from pydantic.v1 import errors +from pydantic.v1.datetime_parse import parse_date +from pydantic.v1.utils import import_string, update_not_none +from pydantic.v1.validators import ( + bytes_validator, + constr_length_validator, + constr_lower, + constr_strip_whitespace, + constr_upper, + decimal_validator, + float_finite_validator, + float_validator, + frozenset_validator, + int_validator, + list_validator, + number_multiple_validator, + number_size_validator, + path_exists_validator, + path_validator, + set_validator, + str_validator, + strict_bytes_validator, + strict_float_validator, + strict_int_validator, + strict_str_validator, +) + +__all__ = [ + 'NoneStr', + 'NoneBytes', + 'StrBytes', + 'NoneStrBytes', + 'StrictStr', + 'ConstrainedBytes', + 'conbytes', + 'ConstrainedList', + 'conlist', + 'ConstrainedSet', + 'conset', + 'ConstrainedFrozenSet', + 'confrozenset', + 'ConstrainedStr', + 'constr', + 'PyObject', + 'ConstrainedInt', + 'conint', + 'PositiveInt', + 'NegativeInt', + 'NonNegativeInt', + 'NonPositiveInt', + 'ConstrainedFloat', + 'confloat', + 'PositiveFloat', + 'NegativeFloat', + 'NonNegativeFloat', + 'NonPositiveFloat', + 'FiniteFloat', + 'ConstrainedDecimal', + 'condecimal', + 'UUID1', + 'UUID3', + 'UUID4', + 'UUID5', + 'FilePath', + 'DirectoryPath', + 'Json', + 'JsonWrapper', + 'SecretField', + 'SecretStr', + 'SecretBytes', + 'StrictBool', + 'StrictBytes', + 'StrictInt', + 'StrictFloat', + 'PaymentCardNumber', + 'ByteSize', + 'PastDate', + 'FutureDate', + 'ConstrainedDate', + 'condate', +] + +NoneStr = Optional[str] +NoneBytes = Optional[bytes] +StrBytes = Union[str, bytes] +NoneStrBytes = Optional[StrBytes] +OptionalInt = Optional[int] +OptionalIntFloat = Union[OptionalInt, float] +OptionalIntFloatDecimal = Union[OptionalIntFloat, Decimal] +OptionalDate = Optional[date] +StrIntFloat = Union[str, int, float] + +if TYPE_CHECKING: + from typing_extensions import Annotated + + from pydantic.v1.dataclasses import Dataclass + from pydantic.v1.main import BaseModel + from pydantic.v1.typing import CallableGenerator + + ModelOrDc = Type[Union[BaseModel, Dataclass]] + +T = TypeVar('T') +_DEFINED_TYPES: 'WeakSet[type]' = WeakSet() + + +@overload +def _registered(typ: Type[T]) -> Type[T]: + pass + + +@overload +def _registered(typ: 'ConstrainedNumberMeta') -> 'ConstrainedNumberMeta': + pass + + +def _registered(typ: Union[Type[T], 'ConstrainedNumberMeta']) -> Union[Type[T], 'ConstrainedNumberMeta']: + # In order to generate valid examples of constrained types, Hypothesis needs + # to inspect the type object - so we keep a weakref to each contype object + # until it can be registered. When (or if) our Hypothesis plugin is loaded, + # it monkeypatches this function. + # If Hypothesis is never used, the total effect is to keep a weak reference + # which has minimal memory usage and doesn't even affect garbage collection. + _DEFINED_TYPES.add(typ) + return typ + + +class ConstrainedNumberMeta(type): + def __new__(cls, name: str, bases: Any, dct: Dict[str, Any]) -> 'ConstrainedInt': # type: ignore + new_cls = cast('ConstrainedInt', type.__new__(cls, name, bases, dct)) + + if new_cls.gt is not None and new_cls.ge is not None: + raise errors.ConfigError('bounds gt and ge cannot be specified at the same time') + if new_cls.lt is not None and new_cls.le is not None: + raise errors.ConfigError('bounds lt and le cannot be specified at the same time') + + return _registered(new_cls) # type: ignore + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BOOLEAN TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +if TYPE_CHECKING: + StrictBool = bool +else: + + class StrictBool(int): + """ + StrictBool to allow for bools which are not type-coerced. + """ + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='boolean') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + + @classmethod + def validate(cls, value: Any) -> bool: + """ + Ensure that we only allow bools. + """ + if isinstance(value, bool): + return value + + raise errors.StrictBoolError() + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ INTEGER TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class ConstrainedInt(int, metaclass=ConstrainedNumberMeta): + strict: bool = False + gt: OptionalInt = None + ge: OptionalInt = None + lt: OptionalInt = None + le: OptionalInt = None + multiple_of: OptionalInt = None + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none( + field_schema, + exclusiveMinimum=cls.gt, + exclusiveMaximum=cls.lt, + minimum=cls.ge, + maximum=cls.le, + multipleOf=cls.multiple_of, + ) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield strict_int_validator if cls.strict else int_validator + yield number_size_validator + yield number_multiple_validator + + +def conint( + *, + strict: bool = False, + gt: Optional[int] = None, + ge: Optional[int] = None, + lt: Optional[int] = None, + le: Optional[int] = None, + multiple_of: Optional[int] = None, +) -> Type[int]: + # use kwargs then define conf in a dict to aid with IDE type hinting + namespace = dict(strict=strict, gt=gt, ge=ge, lt=lt, le=le, multiple_of=multiple_of) + return type('ConstrainedIntValue', (ConstrainedInt,), namespace) + + +if TYPE_CHECKING: + PositiveInt = int + NegativeInt = int + NonPositiveInt = int + NonNegativeInt = int + StrictInt = int +else: + + class PositiveInt(ConstrainedInt): + gt = 0 + + class NegativeInt(ConstrainedInt): + lt = 0 + + class NonPositiveInt(ConstrainedInt): + le = 0 + + class NonNegativeInt(ConstrainedInt): + ge = 0 + + class StrictInt(ConstrainedInt): + strict = True + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ FLOAT TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class ConstrainedFloat(float, metaclass=ConstrainedNumberMeta): + strict: bool = False + gt: OptionalIntFloat = None + ge: OptionalIntFloat = None + lt: OptionalIntFloat = None + le: OptionalIntFloat = None + multiple_of: OptionalIntFloat = None + allow_inf_nan: Optional[bool] = None + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none( + field_schema, + exclusiveMinimum=cls.gt, + exclusiveMaximum=cls.lt, + minimum=cls.ge, + maximum=cls.le, + multipleOf=cls.multiple_of, + ) + # Modify constraints to account for differences between IEEE floats and JSON + if field_schema.get('exclusiveMinimum') == -math.inf: + del field_schema['exclusiveMinimum'] + if field_schema.get('minimum') == -math.inf: + del field_schema['minimum'] + if field_schema.get('exclusiveMaximum') == math.inf: + del field_schema['exclusiveMaximum'] + if field_schema.get('maximum') == math.inf: + del field_schema['maximum'] + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield strict_float_validator if cls.strict else float_validator + yield number_size_validator + yield number_multiple_validator + yield float_finite_validator + + +def confloat( + *, + strict: bool = False, + gt: float = None, + ge: float = None, + lt: float = None, + le: float = None, + multiple_of: float = None, + allow_inf_nan: Optional[bool] = None, +) -> Type[float]: + # use kwargs then define conf in a dict to aid with IDE type hinting + namespace = dict(strict=strict, gt=gt, ge=ge, lt=lt, le=le, multiple_of=multiple_of, allow_inf_nan=allow_inf_nan) + return type('ConstrainedFloatValue', (ConstrainedFloat,), namespace) + + +if TYPE_CHECKING: + PositiveFloat = float + NegativeFloat = float + NonPositiveFloat = float + NonNegativeFloat = float + StrictFloat = float + FiniteFloat = float +else: + + class PositiveFloat(ConstrainedFloat): + gt = 0 + + class NegativeFloat(ConstrainedFloat): + lt = 0 + + class NonPositiveFloat(ConstrainedFloat): + le = 0 + + class NonNegativeFloat(ConstrainedFloat): + ge = 0 + + class StrictFloat(ConstrainedFloat): + strict = True + + class FiniteFloat(ConstrainedFloat): + allow_inf_nan = False + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTES TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class ConstrainedBytes(bytes): + strip_whitespace = False + to_upper = False + to_lower = False + min_length: OptionalInt = None + max_length: OptionalInt = None + strict: bool = False + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none(field_schema, minLength=cls.min_length, maxLength=cls.max_length) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield strict_bytes_validator if cls.strict else bytes_validator + yield constr_strip_whitespace + yield constr_upper + yield constr_lower + yield constr_length_validator + + +def conbytes( + *, + strip_whitespace: bool = False, + to_upper: bool = False, + to_lower: bool = False, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + strict: bool = False, +) -> Type[bytes]: + # use kwargs then define conf in a dict to aid with IDE type hinting + namespace = dict( + strip_whitespace=strip_whitespace, + to_upper=to_upper, + to_lower=to_lower, + min_length=min_length, + max_length=max_length, + strict=strict, + ) + return _registered(type('ConstrainedBytesValue', (ConstrainedBytes,), namespace)) + + +if TYPE_CHECKING: + StrictBytes = bytes +else: + + class StrictBytes(ConstrainedBytes): + strict = True + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ STRING TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class ConstrainedStr(str): + strip_whitespace = False + to_upper = False + to_lower = False + min_length: OptionalInt = None + max_length: OptionalInt = None + curtail_length: OptionalInt = None + regex: Optional[Union[str, Pattern[str]]] = None + strict = False + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none( + field_schema, + minLength=cls.min_length, + maxLength=cls.max_length, + pattern=cls.regex and cls._get_pattern(cls.regex), + ) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield strict_str_validator if cls.strict else str_validator + yield constr_strip_whitespace + yield constr_upper + yield constr_lower + yield constr_length_validator + yield cls.validate + + @classmethod + def validate(cls, value: Union[str]) -> Union[str]: + if cls.curtail_length and len(value) > cls.curtail_length: + value = value[: cls.curtail_length] + + if cls.regex: + if not re.match(cls.regex, value): + raise errors.StrRegexError(pattern=cls._get_pattern(cls.regex)) + + return value + + @staticmethod + def _get_pattern(regex: Union[str, Pattern[str]]) -> str: + return regex if isinstance(regex, str) else regex.pattern + + +def constr( + *, + strip_whitespace: bool = False, + to_upper: bool = False, + to_lower: bool = False, + strict: bool = False, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + curtail_length: Optional[int] = None, + regex: Optional[str] = None, +) -> Type[str]: + # use kwargs then define conf in a dict to aid with IDE type hinting + namespace = dict( + strip_whitespace=strip_whitespace, + to_upper=to_upper, + to_lower=to_lower, + strict=strict, + min_length=min_length, + max_length=max_length, + curtail_length=curtail_length, + regex=regex and re.compile(regex), + ) + return _registered(type('ConstrainedStrValue', (ConstrainedStr,), namespace)) + + +if TYPE_CHECKING: + StrictStr = str +else: + + class StrictStr(ConstrainedStr): + strict = True + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SET TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +# This types superclass should be Set[T], but cython chokes on that... +class ConstrainedSet(set): # type: ignore + # Needed for pydantic to detect that this is a set + __origin__ = set + __args__: Set[Type[T]] # type: ignore + + min_items: Optional[int] = None + max_items: Optional[int] = None + item_type: Type[T] # type: ignore + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.set_length_validator + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items) + + @classmethod + def set_length_validator(cls, v: 'Optional[Set[T]]') -> 'Optional[Set[T]]': + if v is None: + return None + + v = set_validator(v) + v_len = len(v) + + if cls.min_items is not None and v_len < cls.min_items: + raise errors.SetMinLengthError(limit_value=cls.min_items) + + if cls.max_items is not None and v_len > cls.max_items: + raise errors.SetMaxLengthError(limit_value=cls.max_items) + + return v + + +def conset(item_type: Type[T], *, min_items: Optional[int] = None, max_items: Optional[int] = None) -> Type[Set[T]]: + # __args__ is needed to conform to typing generics api + namespace = {'min_items': min_items, 'max_items': max_items, 'item_type': item_type, '__args__': [item_type]} + # We use new_class to be able to deal with Generic types + return new_class('ConstrainedSetValue', (ConstrainedSet,), {}, lambda ns: ns.update(namespace)) + + +# This types superclass should be FrozenSet[T], but cython chokes on that... +class ConstrainedFrozenSet(frozenset): # type: ignore + # Needed for pydantic to detect that this is a set + __origin__ = frozenset + __args__: FrozenSet[Type[T]] # type: ignore + + min_items: Optional[int] = None + max_items: Optional[int] = None + item_type: Type[T] # type: ignore + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.frozenset_length_validator + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items) + + @classmethod + def frozenset_length_validator(cls, v: 'Optional[FrozenSet[T]]') -> 'Optional[FrozenSet[T]]': + if v is None: + return None + + v = frozenset_validator(v) + v_len = len(v) + + if cls.min_items is not None and v_len < cls.min_items: + raise errors.FrozenSetMinLengthError(limit_value=cls.min_items) + + if cls.max_items is not None and v_len > cls.max_items: + raise errors.FrozenSetMaxLengthError(limit_value=cls.max_items) + + return v + + +def confrozenset( + item_type: Type[T], *, min_items: Optional[int] = None, max_items: Optional[int] = None +) -> Type[FrozenSet[T]]: + # __args__ is needed to conform to typing generics api + namespace = {'min_items': min_items, 'max_items': max_items, 'item_type': item_type, '__args__': [item_type]} + # We use new_class to be able to deal with Generic types + return new_class('ConstrainedFrozenSetValue', (ConstrainedFrozenSet,), {}, lambda ns: ns.update(namespace)) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ LIST TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +# This types superclass should be List[T], but cython chokes on that... +class ConstrainedList(list): # type: ignore + # Needed for pydantic to detect that this is a list + __origin__ = list + __args__: Tuple[Type[T], ...] # type: ignore + + min_items: Optional[int] = None + max_items: Optional[int] = None + unique_items: Optional[bool] = None + item_type: Type[T] # type: ignore + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.list_length_validator + if cls.unique_items: + yield cls.unique_items_validator + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none(field_schema, minItems=cls.min_items, maxItems=cls.max_items, uniqueItems=cls.unique_items) + + @classmethod + def list_length_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]': + if v is None: + return None + + v = list_validator(v) + v_len = len(v) + + if cls.min_items is not None and v_len < cls.min_items: + raise errors.ListMinLengthError(limit_value=cls.min_items) + + if cls.max_items is not None and v_len > cls.max_items: + raise errors.ListMaxLengthError(limit_value=cls.max_items) + + return v + + @classmethod + def unique_items_validator(cls, v: 'Optional[List[T]]') -> 'Optional[List[T]]': + if v is None: + return None + + for i, value in enumerate(v, start=1): + if value in v[i:]: + raise errors.ListUniqueItemsError() + + return v + + +def conlist( + item_type: Type[T], *, min_items: Optional[int] = None, max_items: Optional[int] = None, unique_items: bool = None +) -> Type[List[T]]: + # __args__ is needed to conform to typing generics api + namespace = dict( + min_items=min_items, max_items=max_items, unique_items=unique_items, item_type=item_type, __args__=(item_type,) + ) + # We use new_class to be able to deal with Generic types + return new_class('ConstrainedListValue', (ConstrainedList,), {}, lambda ns: ns.update(namespace)) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PYOBJECT TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +if TYPE_CHECKING: + PyObject = Callable[..., Any] +else: + + class PyObject: + validate_always = True + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + + @classmethod + def validate(cls, value: Any) -> Any: + if isinstance(value, Callable): + return value + + try: + value = str_validator(value) + except errors.StrError: + raise errors.PyObjectError(error_message='value is neither a valid import path not a valid callable') + + try: + return import_string(value) + except ImportError as e: + raise errors.PyObjectError(error_message=str(e)) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DECIMAL TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class ConstrainedDecimal(Decimal, metaclass=ConstrainedNumberMeta): + gt: OptionalIntFloatDecimal = None + ge: OptionalIntFloatDecimal = None + lt: OptionalIntFloatDecimal = None + le: OptionalIntFloatDecimal = None + max_digits: OptionalInt = None + decimal_places: OptionalInt = None + multiple_of: OptionalIntFloatDecimal = None + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none( + field_schema, + exclusiveMinimum=cls.gt, + exclusiveMaximum=cls.lt, + minimum=cls.ge, + maximum=cls.le, + multipleOf=cls.multiple_of, + ) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield decimal_validator + yield number_size_validator + yield number_multiple_validator + yield cls.validate + + @classmethod + def validate(cls, value: Decimal) -> Decimal: + try: + normalized_value = value.normalize() + except InvalidOperation: + normalized_value = value + digit_tuple, exponent = normalized_value.as_tuple()[1:] + if exponent in {'F', 'n', 'N'}: + raise errors.DecimalIsNotFiniteError() + + if exponent >= 0: + # A positive exponent adds that many trailing zeros. + digits = len(digit_tuple) + exponent + decimals = 0 + else: + # If the absolute value of the negative exponent is larger than the + # number of digits, then it's the same as the number of digits, + # because it'll consume all of the digits in digit_tuple and then + # add abs(exponent) - len(digit_tuple) leading zeros after the + # decimal point. + if abs(exponent) > len(digit_tuple): + digits = decimals = abs(exponent) + else: + digits = len(digit_tuple) + decimals = abs(exponent) + whole_digits = digits - decimals + + if cls.max_digits is not None and digits > cls.max_digits: + raise errors.DecimalMaxDigitsError(max_digits=cls.max_digits) + + if cls.decimal_places is not None and decimals > cls.decimal_places: + raise errors.DecimalMaxPlacesError(decimal_places=cls.decimal_places) + + if cls.max_digits is not None and cls.decimal_places is not None: + expected = cls.max_digits - cls.decimal_places + if whole_digits > expected: + raise errors.DecimalWholeDigitsError(whole_digits=expected) + + return value + + +def condecimal( + *, + gt: Decimal = None, + ge: Decimal = None, + lt: Decimal = None, + le: Decimal = None, + max_digits: Optional[int] = None, + decimal_places: Optional[int] = None, + multiple_of: Decimal = None, +) -> Type[Decimal]: + # use kwargs then define conf in a dict to aid with IDE type hinting + namespace = dict( + gt=gt, ge=ge, lt=lt, le=le, max_digits=max_digits, decimal_places=decimal_places, multiple_of=multiple_of + ) + return type('ConstrainedDecimalValue', (ConstrainedDecimal,), namespace) + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ UUID TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +if TYPE_CHECKING: + UUID1 = UUID + UUID3 = UUID + UUID4 = UUID + UUID5 = UUID +else: + + class UUID1(UUID): + _required_version = 1 + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='string', format=f'uuid{cls._required_version}') + + class UUID3(UUID1): + _required_version = 3 + + class UUID4(UUID1): + _required_version = 4 + + class UUID5(UUID1): + _required_version = 5 + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PATH TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +if TYPE_CHECKING: + FilePath = Path + DirectoryPath = Path +else: + + class FilePath(Path): + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(format='file-path') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield path_validator + yield path_exists_validator + yield cls.validate + + @classmethod + def validate(cls, value: Path) -> Path: + if not value.is_file(): + raise errors.PathNotAFileError(path=value) + + return value + + class DirectoryPath(Path): + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(format='directory-path') + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield path_validator + yield path_exists_validator + yield cls.validate + + @classmethod + def validate(cls, value: Path) -> Path: + if not value.is_dir(): + raise errors.PathNotADirectoryError(path=value) + + return value + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JSON TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class JsonWrapper: + pass + + +class JsonMeta(type): + def __getitem__(self, t: Type[Any]) -> Type[JsonWrapper]: + if t is Any: + return Json # allow Json[Any] to replecate plain Json + return _registered(type('JsonWrapperValue', (JsonWrapper,), {'inner_type': t})) + + +if TYPE_CHECKING: + Json = Annotated[T, ...] # Json[list[str]] will be recognized by type checkers as list[str] + +else: + + class Json(metaclass=JsonMeta): + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + field_schema.update(type='string', format='json-string') + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SECRET TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class SecretField(abc.ABC): + """ + Note: this should be implemented as a generic like `SecretField(ABC, Generic[T])`, + the `__init__()` should be part of the abstract class and the + `get_secret_value()` method should use the generic `T` type. + + However Cython doesn't support very well generics at the moment and + the generated code fails to be imported (see + https://github.com/cython/cython/issues/2753). + """ + + def __eq__(self, other: Any) -> bool: + return isinstance(other, self.__class__) and self.get_secret_value() == other.get_secret_value() + + def __str__(self) -> str: + return '**********' if self.get_secret_value() else '' + + def __hash__(self) -> int: + return hash(self.get_secret_value()) + + @abc.abstractmethod + def get_secret_value(self) -> Any: # pragma: no cover + ... + + +class SecretStr(SecretField): + min_length: OptionalInt = None + max_length: OptionalInt = None + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none( + field_schema, + type='string', + writeOnly=True, + format='password', + minLength=cls.min_length, + maxLength=cls.max_length, + ) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + yield constr_length_validator + + @classmethod + def validate(cls, value: Any) -> 'SecretStr': + if isinstance(value, cls): + return value + value = str_validator(value) + return cls(value) + + def __init__(self, value: str): + self._secret_value = value + + def __repr__(self) -> str: + return f"SecretStr('{self}')" + + def __len__(self) -> int: + return len(self._secret_value) + + def display(self) -> str: + warnings.warn('`secret_str.display()` is deprecated, use `str(secret_str)` instead', DeprecationWarning) + return str(self) + + def get_secret_value(self) -> str: + return self._secret_value + + +class SecretBytes(SecretField): + min_length: OptionalInt = None + max_length: OptionalInt = None + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none( + field_schema, + type='string', + writeOnly=True, + format='password', + minLength=cls.min_length, + maxLength=cls.max_length, + ) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + yield constr_length_validator + + @classmethod + def validate(cls, value: Any) -> 'SecretBytes': + if isinstance(value, cls): + return value + value = bytes_validator(value) + return cls(value) + + def __init__(self, value: bytes): + self._secret_value = value + + def __repr__(self) -> str: + return f"SecretBytes(b'{self}')" + + def __len__(self) -> int: + return len(self._secret_value) + + def display(self) -> str: + warnings.warn('`secret_bytes.display()` is deprecated, use `str(secret_bytes)` instead', DeprecationWarning) + return str(self) + + def get_secret_value(self) -> bytes: + return self._secret_value + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ PAYMENT CARD TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +class PaymentCardBrand(str, Enum): + # If you add another card type, please also add it to the + # Hypothesis strategy in `pydantic._hypothesis_plugin`. + amex = 'American Express' + mastercard = 'Mastercard' + visa = 'Visa' + other = 'other' + + def __str__(self) -> str: + return self.value + + +class PaymentCardNumber(str): + """ + Based on: https://en.wikipedia.org/wiki/Payment_card_number + """ + + strip_whitespace: ClassVar[bool] = True + min_length: ClassVar[int] = 12 + max_length: ClassVar[int] = 19 + bin: str + last4: str + brand: PaymentCardBrand + + def __init__(self, card_number: str): + self.bin = card_number[:6] + self.last4 = card_number[-4:] + self.brand = self._get_brand(card_number) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield str_validator + yield constr_strip_whitespace + yield constr_length_validator + yield cls.validate_digits + yield cls.validate_luhn_check_digit + yield cls + yield cls.validate_length_for_brand + + @property + def masked(self) -> str: + num_masked = len(self) - 10 # len(bin) + len(last4) == 10 + return f'{self.bin}{"*" * num_masked}{self.last4}' + + @classmethod + def validate_digits(cls, card_number: str) -> str: + if not card_number.isdigit(): + raise errors.NotDigitError + return card_number + + @classmethod + def validate_luhn_check_digit(cls, card_number: str) -> str: + """ + Based on: https://en.wikipedia.org/wiki/Luhn_algorithm + """ + sum_ = int(card_number[-1]) + length = len(card_number) + parity = length % 2 + for i in range(length - 1): + digit = int(card_number[i]) + if i % 2 == parity: + digit *= 2 + if digit > 9: + digit -= 9 + sum_ += digit + valid = sum_ % 10 == 0 + if not valid: + raise errors.LuhnValidationError + return card_number + + @classmethod + def validate_length_for_brand(cls, card_number: 'PaymentCardNumber') -> 'PaymentCardNumber': + """ + Validate length based on BIN for major brands: + https://en.wikipedia.org/wiki/Payment_card_number#Issuer_identification_number_(IIN) + """ + required_length: Union[None, int, str] = None + if card_number.brand in PaymentCardBrand.mastercard: + required_length = 16 + valid = len(card_number) == required_length + elif card_number.brand == PaymentCardBrand.visa: + required_length = '13, 16 or 19' + valid = len(card_number) in {13, 16, 19} + elif card_number.brand == PaymentCardBrand.amex: + required_length = 15 + valid = len(card_number) == required_length + else: + valid = True + if not valid: + raise errors.InvalidLengthForBrand(brand=card_number.brand, required_length=required_length) + return card_number + + @staticmethod + def _get_brand(card_number: str) -> PaymentCardBrand: + if card_number[0] == '4': + brand = PaymentCardBrand.visa + elif 51 <= int(card_number[:2]) <= 55: + brand = PaymentCardBrand.mastercard + elif card_number[:2] in {'34', '37'}: + brand = PaymentCardBrand.amex + else: + brand = PaymentCardBrand.other + return brand + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BYTE SIZE TYPE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +BYTE_SIZES = { + 'b': 1, + 'kb': 10**3, + 'mb': 10**6, + 'gb': 10**9, + 'tb': 10**12, + 'pb': 10**15, + 'eb': 10**18, + 'kib': 2**10, + 'mib': 2**20, + 'gib': 2**30, + 'tib': 2**40, + 'pib': 2**50, + 'eib': 2**60, +} +BYTE_SIZES.update({k.lower()[0]: v for k, v in BYTE_SIZES.items() if 'i' not in k}) +byte_string_re = re.compile(r'^\s*(\d*\.?\d+)\s*(\w+)?', re.IGNORECASE) + + +class ByteSize(int): + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield cls.validate + + @classmethod + def validate(cls, v: StrIntFloat) -> 'ByteSize': + try: + return cls(int(v)) + except ValueError: + pass + + str_match = byte_string_re.match(str(v)) + if str_match is None: + raise errors.InvalidByteSize() + + scalar, unit = str_match.groups() + if unit is None: + unit = 'b' + + try: + unit_mult = BYTE_SIZES[unit.lower()] + except KeyError: + raise errors.InvalidByteSizeUnit(unit=unit) + + return cls(int(float(scalar) * unit_mult)) + + def human_readable(self, decimal: bool = False) -> str: + if decimal: + divisor = 1000 + units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] + final_unit = 'EB' + else: + divisor = 1024 + units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'] + final_unit = 'EiB' + + num = float(self) + for unit in units: + if abs(num) < divisor: + return f'{num:0.1f}{unit}' + num /= divisor + + return f'{num:0.1f}{final_unit}' + + def to(self, unit: str) -> float: + try: + unit_div = BYTE_SIZES[unit.lower()] + except KeyError: + raise errors.InvalidByteSizeUnit(unit=unit) + + return self / unit_div + + +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DATE TYPES ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +if TYPE_CHECKING: + PastDate = date + FutureDate = date +else: + + class PastDate(date): + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield parse_date + yield cls.validate + + @classmethod + def validate(cls, value: date) -> date: + if value >= date.today(): + raise errors.DateNotInThePastError() + + return value + + class FutureDate(date): + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield parse_date + yield cls.validate + + @classmethod + def validate(cls, value: date) -> date: + if value <= date.today(): + raise errors.DateNotInTheFutureError() + + return value + + +class ConstrainedDate(date, metaclass=ConstrainedNumberMeta): + gt: OptionalDate = None + ge: OptionalDate = None + lt: OptionalDate = None + le: OptionalDate = None + + @classmethod + def __modify_schema__(cls, field_schema: Dict[str, Any]) -> None: + update_not_none(field_schema, exclusiveMinimum=cls.gt, exclusiveMaximum=cls.lt, minimum=cls.ge, maximum=cls.le) + + @classmethod + def __get_validators__(cls) -> 'CallableGenerator': + yield parse_date + yield number_size_validator + + +def condate( + *, + gt: date = None, + ge: date = None, + lt: date = None, + le: date = None, +) -> Type[date]: + # use kwargs then define conf in a dict to aid with IDE type hinting + namespace = dict(gt=gt, ge=ge, lt=lt, le=le) + return type('ConstrainedDateValue', (ConstrainedDate,), namespace) diff --git a/env/Lib/site-packages/pydantic/v1/typing.py b/env/Lib/site-packages/pydantic/v1/typing.py new file mode 100644 index 0000000..7dd341c --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/typing.py @@ -0,0 +1,608 @@ +import sys +import typing +from collections.abc import Callable +from os import PathLike +from typing import ( # type: ignore + TYPE_CHECKING, + AbstractSet, + Any, + Callable as TypingCallable, + ClassVar, + Dict, + ForwardRef, + Generator, + Iterable, + List, + Mapping, + NewType, + Optional, + Sequence, + Set, + Tuple, + Type, + TypeVar, + Union, + _eval_type, + cast, + get_type_hints, +) + +from typing_extensions import ( + Annotated, + Final, + Literal, + NotRequired as TypedDictNotRequired, + Required as TypedDictRequired, +) + +try: + from typing import _TypingBase as typing_base # type: ignore +except ImportError: + from typing import _Final as typing_base # type: ignore + +try: + from typing import GenericAlias as TypingGenericAlias # type: ignore +except ImportError: + # python < 3.9 does not have GenericAlias (list[int], tuple[str, ...] and so on) + TypingGenericAlias = () + +try: + from types import UnionType as TypesUnionType # type: ignore +except ImportError: + # python < 3.10 does not have UnionType (str | int, byte | bool and so on) + TypesUnionType = () + + +if sys.version_info < (3, 9): + + def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any: + return type_._evaluate(globalns, localns) + +else: + + def evaluate_forwardref(type_: ForwardRef, globalns: Any, localns: Any) -> Any: + # Even though it is the right signature for python 3.9, mypy complains with + # `error: Too many arguments for "_evaluate" of "ForwardRef"` hence the cast... + # Python 3.13/3.12.4+ made `recursive_guard` a kwarg, so name it explicitly to avoid: + # TypeError: ForwardRef._evaluate() missing 1 required keyword-only argument: 'recursive_guard' + return cast(Any, type_)._evaluate(globalns, localns, recursive_guard=set()) + + +if sys.version_info < (3, 9): + # Ensure we always get all the whole `Annotated` hint, not just the annotated type. + # For 3.7 to 3.8, `get_type_hints` doesn't recognize `typing_extensions.Annotated`, + # so it already returns the full annotation + get_all_type_hints = get_type_hints + +else: + + def get_all_type_hints(obj: Any, globalns: Any = None, localns: Any = None) -> Any: + return get_type_hints(obj, globalns, localns, include_extras=True) + + +_T = TypeVar('_T') + +AnyCallable = TypingCallable[..., Any] +NoArgAnyCallable = TypingCallable[[], Any] + +# workaround for https://github.com/python/mypy/issues/9496 +AnyArgTCallable = TypingCallable[..., _T] + + +# Annotated[...] is implemented by returning an instance of one of these classes, depending on +# python/typing_extensions version. +AnnotatedTypeNames = {'AnnotatedMeta', '_AnnotatedAlias'} + + +LITERAL_TYPES: Set[Any] = {Literal} +if hasattr(typing, 'Literal'): + LITERAL_TYPES.add(typing.Literal) + + +if sys.version_info < (3, 8): + + def get_origin(t: Type[Any]) -> Optional[Type[Any]]: + if type(t).__name__ in AnnotatedTypeNames: + # weirdly this is a runtime requirement, as well as for mypy + return cast(Type[Any], Annotated) + return getattr(t, '__origin__', None) + +else: + from typing import get_origin as _typing_get_origin + + def get_origin(tp: Type[Any]) -> Optional[Type[Any]]: + """ + We can't directly use `typing.get_origin` since we need a fallback to support + custom generic classes like `ConstrainedList` + It should be useless once https://github.com/cython/cython/issues/3537 is + solved and https://github.com/pydantic/pydantic/pull/1753 is merged. + """ + if type(tp).__name__ in AnnotatedTypeNames: + return cast(Type[Any], Annotated) # mypy complains about _SpecialForm + return _typing_get_origin(tp) or getattr(tp, '__origin__', None) + + +if sys.version_info < (3, 8): + from typing import _GenericAlias + + def get_args(t: Type[Any]) -> Tuple[Any, ...]: + """Compatibility version of get_args for python 3.7. + + Mostly compatible with the python 3.8 `typing` module version + and able to handle almost all use cases. + """ + if type(t).__name__ in AnnotatedTypeNames: + return t.__args__ + t.__metadata__ + if isinstance(t, _GenericAlias): + res = t.__args__ + if t.__origin__ is Callable and res and res[0] is not Ellipsis: + res = (list(res[:-1]), res[-1]) + return res + return getattr(t, '__args__', ()) + +else: + from typing import get_args as _typing_get_args + + def _generic_get_args(tp: Type[Any]) -> Tuple[Any, ...]: + """ + In python 3.9, `typing.Dict`, `typing.List`, ... + do have an empty `__args__` by default (instead of the generic ~T for example). + In order to still support `Dict` for example and consider it as `Dict[Any, Any]`, + we retrieve the `_nparams` value that tells us how many parameters it needs. + """ + if hasattr(tp, '_nparams'): + return (Any,) * tp._nparams + # Special case for `tuple[()]`, which used to return ((),) with `typing.Tuple` + # in python 3.10- but now returns () for `tuple` and `Tuple`. + # This will probably be clarified in pydantic v2 + try: + if tp == Tuple[()] or sys.version_info >= (3, 9) and tp == tuple[()]: # type: ignore[misc] + return ((),) + # there is a TypeError when compiled with cython + except TypeError: # pragma: no cover + pass + return () + + def get_args(tp: Type[Any]) -> Tuple[Any, ...]: + """Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + """ + if type(tp).__name__ in AnnotatedTypeNames: + return tp.__args__ + tp.__metadata__ + # the fallback is needed for the same reasons as `get_origin` (see above) + return _typing_get_args(tp) or getattr(tp, '__args__', ()) or _generic_get_args(tp) + + +if sys.version_info < (3, 9): + + def convert_generics(tp: Type[Any]) -> Type[Any]: + """Python 3.9 and older only supports generics from `typing` module. + They convert strings to ForwardRef automatically. + + Examples:: + typing.List['Hero'] == typing.List[ForwardRef('Hero')] + """ + return tp + +else: + from typing import _UnionGenericAlias # type: ignore + + from typing_extensions import _AnnotatedAlias + + def convert_generics(tp: Type[Any]) -> Type[Any]: + """ + Recursively searches for `str` type hints and replaces them with ForwardRef. + + Examples:: + convert_generics(list['Hero']) == list[ForwardRef('Hero')] + convert_generics(dict['Hero', 'Team']) == dict[ForwardRef('Hero'), ForwardRef('Team')] + convert_generics(typing.Dict['Hero', 'Team']) == typing.Dict[ForwardRef('Hero'), ForwardRef('Team')] + convert_generics(list[str | 'Hero'] | int) == list[str | ForwardRef('Hero')] | int + """ + origin = get_origin(tp) + if not origin or not hasattr(tp, '__args__'): + return tp + + args = get_args(tp) + + # typing.Annotated needs special treatment + if origin is Annotated: + return _AnnotatedAlias(convert_generics(args[0]), args[1:]) + + # recursively replace `str` instances inside of `GenericAlias` with `ForwardRef(arg)` + converted = tuple( + ForwardRef(arg) if isinstance(arg, str) and isinstance(tp, TypingGenericAlias) else convert_generics(arg) + for arg in args + ) + + if converted == args: + return tp + elif isinstance(tp, TypingGenericAlias): + return TypingGenericAlias(origin, converted) + elif isinstance(tp, TypesUnionType): + # recreate types.UnionType (PEP604, Python >= 3.10) + return _UnionGenericAlias(origin, converted) + else: + try: + setattr(tp, '__args__', converted) + except AttributeError: + pass + return tp + + +if sys.version_info < (3, 10): + + def is_union(tp: Optional[Type[Any]]) -> bool: + return tp is Union + + WithArgsTypes = (TypingGenericAlias,) + +else: + import types + import typing + + def is_union(tp: Optional[Type[Any]]) -> bool: + return tp is Union or tp is types.UnionType # noqa: E721 + + WithArgsTypes = (typing._GenericAlias, types.GenericAlias, types.UnionType) + + +StrPath = Union[str, PathLike] + + +if TYPE_CHECKING: + from pydantic.v1.fields import ModelField + + TupleGenerator = Generator[Tuple[str, Any], None, None] + DictStrAny = Dict[str, Any] + DictAny = Dict[Any, Any] + SetStr = Set[str] + ListStr = List[str] + IntStr = Union[int, str] + AbstractSetIntStr = AbstractSet[IntStr] + DictIntStrAny = Dict[IntStr, Any] + MappingIntStrAny = Mapping[IntStr, Any] + CallableGenerator = Generator[AnyCallable, None, None] + ReprArgs = Sequence[Tuple[Optional[str], Any]] + + MYPY = False + if MYPY: + AnyClassMethod = classmethod[Any] + else: + # classmethod[TargetType, CallableParamSpecType, CallableReturnType] + AnyClassMethod = classmethod[Any, Any, Any] + +__all__ = ( + 'AnyCallable', + 'NoArgAnyCallable', + 'NoneType', + 'is_none_type', + 'display_as_type', + 'resolve_annotations', + 'is_callable_type', + 'is_literal_type', + 'all_literal_values', + 'is_namedtuple', + 'is_typeddict', + 'is_typeddict_special', + 'is_new_type', + 'new_type_supertype', + 'is_classvar', + 'is_finalvar', + 'update_field_forward_refs', + 'update_model_forward_refs', + 'TupleGenerator', + 'DictStrAny', + 'DictAny', + 'SetStr', + 'ListStr', + 'IntStr', + 'AbstractSetIntStr', + 'DictIntStrAny', + 'CallableGenerator', + 'ReprArgs', + 'AnyClassMethod', + 'CallableGenerator', + 'WithArgsTypes', + 'get_args', + 'get_origin', + 'get_sub_types', + 'typing_base', + 'get_all_type_hints', + 'is_union', + 'StrPath', + 'MappingIntStrAny', +) + + +NoneType = None.__class__ + + +NONE_TYPES: Tuple[Any, Any, Any] = (None, NoneType, Literal[None]) + + +if sys.version_info < (3, 8): + # Even though this implementation is slower, we need it for python 3.7: + # In python 3.7 "Literal" is not a builtin type and uses a different + # mechanism. + # for this reason `Literal[None] is Literal[None]` evaluates to `False`, + # breaking the faster implementation used for the other python versions. + + def is_none_type(type_: Any) -> bool: + return type_ in NONE_TYPES + +elif sys.version_info[:2] == (3, 8): + + def is_none_type(type_: Any) -> bool: + for none_type in NONE_TYPES: + if type_ is none_type: + return True + # With python 3.8, specifically 3.8.10, Literal "is" check sare very flakey + # can change on very subtle changes like use of types in other modules, + # hopefully this check avoids that issue. + if is_literal_type(type_): # pragma: no cover + return all_literal_values(type_) == (None,) + return False + +else: + + def is_none_type(type_: Any) -> bool: + return type_ in NONE_TYPES + + +def display_as_type(v: Type[Any]) -> str: + if not isinstance(v, typing_base) and not isinstance(v, WithArgsTypes) and not isinstance(v, type): + v = v.__class__ + + if is_union(get_origin(v)): + return f'Union[{", ".join(map(display_as_type, get_args(v)))}]' + + if isinstance(v, WithArgsTypes): + # Generic alias are constructs like `list[int]` + return str(v).replace('typing.', '') + + try: + return v.__name__ + except AttributeError: + # happens with typing objects + return str(v).replace('typing.', '') + + +def resolve_annotations(raw_annotations: Dict[str, Type[Any]], module_name: Optional[str]) -> Dict[str, Type[Any]]: + """ + Partially taken from typing.get_type_hints. + + Resolve string or ForwardRef annotations into type objects if possible. + """ + base_globals: Optional[Dict[str, Any]] = None + if module_name: + try: + module = sys.modules[module_name] + except KeyError: + # happens occasionally, see https://github.com/pydantic/pydantic/issues/2363 + pass + else: + base_globals = module.__dict__ + + annotations = {} + for name, value in raw_annotations.items(): + if isinstance(value, str): + if (3, 10) > sys.version_info >= (3, 9, 8) or sys.version_info >= (3, 10, 1): + value = ForwardRef(value, is_argument=False, is_class=True) + else: + value = ForwardRef(value, is_argument=False) + try: + if sys.version_info >= (3, 13): + value = _eval_type(value, base_globals, None, type_params=()) + else: + value = _eval_type(value, base_globals, None) + except NameError: + # this is ok, it can be fixed with update_forward_refs + pass + annotations[name] = value + return annotations + + +def is_callable_type(type_: Type[Any]) -> bool: + return type_ is Callable or get_origin(type_) is Callable + + +def is_literal_type(type_: Type[Any]) -> bool: + return Literal is not None and get_origin(type_) in LITERAL_TYPES + + +def literal_values(type_: Type[Any]) -> Tuple[Any, ...]: + return get_args(type_) + + +def all_literal_values(type_: Type[Any]) -> Tuple[Any, ...]: + """ + This method is used to retrieve all Literal values as + Literal can be used recursively (see https://www.python.org/dev/peps/pep-0586) + e.g. `Literal[Literal[Literal[1, 2, 3], "foo"], 5, None]` + """ + if not is_literal_type(type_): + return (type_,) + + values = literal_values(type_) + return tuple(x for value in values for x in all_literal_values(value)) + + +def is_namedtuple(type_: Type[Any]) -> bool: + """ + Check if a given class is a named tuple. + It can be either a `typing.NamedTuple` or `collections.namedtuple` + """ + from pydantic.v1.utils import lenient_issubclass + + return lenient_issubclass(type_, tuple) and hasattr(type_, '_fields') + + +def is_typeddict(type_: Type[Any]) -> bool: + """ + Check if a given class is a typed dict (from `typing` or `typing_extensions`) + In 3.10, there will be a public method (https://docs.python.org/3.10/library/typing.html#typing.is_typeddict) + """ + from pydantic.v1.utils import lenient_issubclass + + return lenient_issubclass(type_, dict) and hasattr(type_, '__total__') + + +def _check_typeddict_special(type_: Any) -> bool: + return type_ is TypedDictRequired or type_ is TypedDictNotRequired + + +def is_typeddict_special(type_: Any) -> bool: + """ + Check if type is a TypedDict special form (Required or NotRequired). + """ + return _check_typeddict_special(type_) or _check_typeddict_special(get_origin(type_)) + + +test_type = NewType('test_type', str) + + +def is_new_type(type_: Type[Any]) -> bool: + """ + Check whether type_ was created using typing.NewType + """ + return isinstance(type_, test_type.__class__) and hasattr(type_, '__supertype__') # type: ignore + + +def new_type_supertype(type_: Type[Any]) -> Type[Any]: + while hasattr(type_, '__supertype__'): + type_ = type_.__supertype__ + return type_ + + +def _check_classvar(v: Optional[Type[Any]]) -> bool: + if v is None: + return False + + return v.__class__ == ClassVar.__class__ and getattr(v, '_name', None) == 'ClassVar' + + +def _check_finalvar(v: Optional[Type[Any]]) -> bool: + """ + Check if a given type is a `typing.Final` type. + """ + if v is None: + return False + + return v.__class__ == Final.__class__ and (sys.version_info < (3, 8) or getattr(v, '_name', None) == 'Final') + + +def is_classvar(ann_type: Type[Any]) -> bool: + if _check_classvar(ann_type) or _check_classvar(get_origin(ann_type)): + return True + + # this is an ugly workaround for class vars that contain forward references and are therefore themselves + # forward references, see #3679 + if ann_type.__class__ == ForwardRef and ann_type.__forward_arg__.startswith('ClassVar['): + return True + + return False + + +def is_finalvar(ann_type: Type[Any]) -> bool: + return _check_finalvar(ann_type) or _check_finalvar(get_origin(ann_type)) + + +def update_field_forward_refs(field: 'ModelField', globalns: Any, localns: Any) -> None: + """ + Try to update ForwardRefs on fields based on this ModelField, globalns and localns. + """ + prepare = False + if field.type_.__class__ == ForwardRef: + prepare = True + field.type_ = evaluate_forwardref(field.type_, globalns, localns or None) + if field.outer_type_.__class__ == ForwardRef: + prepare = True + field.outer_type_ = evaluate_forwardref(field.outer_type_, globalns, localns or None) + if prepare: + field.prepare() + + if field.sub_fields: + for sub_f in field.sub_fields: + update_field_forward_refs(sub_f, globalns=globalns, localns=localns) + + if field.discriminator_key is not None: + field.prepare_discriminated_union_sub_fields() + + +def update_model_forward_refs( + model: Type[Any], + fields: Iterable['ModelField'], + json_encoders: Dict[Union[Type[Any], str, ForwardRef], AnyCallable], + localns: 'DictStrAny', + exc_to_suppress: Tuple[Type[BaseException], ...] = (), +) -> None: + """ + Try to update model fields ForwardRefs based on model and localns. + """ + if model.__module__ in sys.modules: + globalns = sys.modules[model.__module__].__dict__.copy() + else: + globalns = {} + + globalns.setdefault(model.__name__, model) + + for f in fields: + try: + update_field_forward_refs(f, globalns=globalns, localns=localns) + except exc_to_suppress: + pass + + for key in set(json_encoders.keys()): + if isinstance(key, str): + fr: ForwardRef = ForwardRef(key) + elif isinstance(key, ForwardRef): + fr = key + else: + continue + + try: + new_key = evaluate_forwardref(fr, globalns, localns or None) + except exc_to_suppress: # pragma: no cover + continue + + json_encoders[new_key] = json_encoders.pop(key) + + +def get_class(type_: Type[Any]) -> Union[None, bool, Type[Any]]: + """ + Tries to get the class of a Type[T] annotation. Returns True if Type is used + without brackets. Otherwise returns None. + """ + if type_ is type: + return True + + if get_origin(type_) is None: + return None + + args = get_args(type_) + if not args or not isinstance(args[0], type): + return True + else: + return args[0] + + +def get_sub_types(tp: Any) -> List[Any]: + """ + Return all the types that are allowed by type `tp` + `tp` can be a `Union` of allowed types or an `Annotated` type + """ + origin = get_origin(tp) + if origin is Annotated: + return get_sub_types(get_args(tp)[0]) + elif is_union(origin): + return [x for t in get_args(tp) for x in get_sub_types(t)] + else: + return [tp] diff --git a/env/Lib/site-packages/pydantic/v1/utils.py b/env/Lib/site-packages/pydantic/v1/utils.py new file mode 100644 index 0000000..a09997b --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/utils.py @@ -0,0 +1,803 @@ +import keyword +import warnings +import weakref +from collections import OrderedDict, defaultdict, deque +from copy import deepcopy +from itertools import islice, zip_longest +from types import BuiltinFunctionType, CodeType, FunctionType, GeneratorType, LambdaType, ModuleType +from typing import ( + TYPE_CHECKING, + AbstractSet, + Any, + Callable, + Collection, + Dict, + Generator, + Iterable, + Iterator, + List, + Mapping, + NoReturn, + Optional, + Set, + Tuple, + Type, + TypeVar, + Union, +) + +from typing_extensions import Annotated + +from pydantic.v1.errors import ConfigError +from pydantic.v1.typing import ( + NoneType, + WithArgsTypes, + all_literal_values, + display_as_type, + get_args, + get_origin, + is_literal_type, + is_union, +) +from pydantic.v1.version import version_info + +if TYPE_CHECKING: + from inspect import Signature + from pathlib import Path + + from pydantic.v1.config import BaseConfig + from pydantic.v1.dataclasses import Dataclass + from pydantic.v1.fields import ModelField + from pydantic.v1.main import BaseModel + from pydantic.v1.typing import AbstractSetIntStr, DictIntStrAny, IntStr, MappingIntStrAny, ReprArgs + + RichReprResult = Iterable[Union[Any, Tuple[Any], Tuple[str, Any], Tuple[str, Any, Any]]] + +__all__ = ( + 'import_string', + 'sequence_like', + 'validate_field_name', + 'lenient_isinstance', + 'lenient_issubclass', + 'in_ipython', + 'is_valid_identifier', + 'deep_update', + 'update_not_none', + 'almost_equal_floats', + 'get_model', + 'to_camel', + 'is_valid_field', + 'smart_deepcopy', + 'PyObjectStr', + 'Representation', + 'GetterDict', + 'ValueItems', + 'version_info', # required here to match behaviour in v1.3 + 'ClassAttribute', + 'path_type', + 'ROOT_KEY', + 'get_unique_discriminator_alias', + 'get_discriminator_alias_and_values', + 'DUNDER_ATTRIBUTES', +) + +ROOT_KEY = '__root__' +# these are types that are returned unchanged by deepcopy +IMMUTABLE_NON_COLLECTIONS_TYPES: Set[Type[Any]] = { + int, + float, + complex, + str, + bool, + bytes, + type, + NoneType, + FunctionType, + BuiltinFunctionType, + LambdaType, + weakref.ref, + CodeType, + # note: including ModuleType will differ from behaviour of deepcopy by not producing error. + # It might be not a good idea in general, but considering that this function used only internally + # against default values of fields, this will allow to actually have a field with module as default value + ModuleType, + NotImplemented.__class__, + Ellipsis.__class__, +} + +# these are types that if empty, might be copied with simple copy() instead of deepcopy() +BUILTIN_COLLECTIONS: Set[Type[Any]] = { + list, + set, + tuple, + frozenset, + dict, + OrderedDict, + defaultdict, + deque, +} + + +def import_string(dotted_path: str) -> Any: + """ + Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the + last name in the path. Raise ImportError if the import fails. + """ + from importlib import import_module + + try: + module_path, class_name = dotted_path.strip(' ').rsplit('.', 1) + except ValueError as e: + raise ImportError(f'"{dotted_path}" doesn\'t look like a module path') from e + + module = import_module(module_path) + try: + return getattr(module, class_name) + except AttributeError as e: + raise ImportError(f'Module "{module_path}" does not define a "{class_name}" attribute') from e + + +def truncate(v: Union[str], *, max_len: int = 80) -> str: + """ + Truncate a value and add a unicode ellipsis (three dots) to the end if it was too long + """ + warnings.warn('`truncate` is no-longer used by pydantic and is deprecated', DeprecationWarning) + if isinstance(v, str) and len(v) > (max_len - 2): + # -3 so quote + string + … + quote has correct length + return (v[: (max_len - 3)] + '…').__repr__() + try: + v = v.__repr__() + except TypeError: + v = v.__class__.__repr__(v) # in case v is a type + if len(v) > max_len: + v = v[: max_len - 1] + '…' + return v + + +def sequence_like(v: Any) -> bool: + return isinstance(v, (list, tuple, set, frozenset, GeneratorType, deque)) + + +def validate_field_name(bases: List[Type['BaseModel']], field_name: str) -> None: + """ + Ensure that the field's name does not shadow an existing attribute of the model. + """ + for base in bases: + if getattr(base, field_name, None): + raise NameError( + f'Field name "{field_name}" shadows a BaseModel attribute; ' + f'use a different field name with "alias=\'{field_name}\'".' + ) + + +def lenient_isinstance(o: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...], None]) -> bool: + try: + return isinstance(o, class_or_tuple) # type: ignore[arg-type] + except TypeError: + return False + + +def lenient_issubclass(cls: Any, class_or_tuple: Union[Type[Any], Tuple[Type[Any], ...], None]) -> bool: + try: + return isinstance(cls, type) and issubclass(cls, class_or_tuple) # type: ignore[arg-type] + except TypeError: + if isinstance(cls, WithArgsTypes): + return False + raise # pragma: no cover + + +def in_ipython() -> bool: + """ + Check whether we're in an ipython environment, including jupyter notebooks. + """ + try: + eval('__IPYTHON__') + except NameError: + return False + else: # pragma: no cover + return True + + +def is_valid_identifier(identifier: str) -> bool: + """ + Checks that a string is a valid identifier and not a Python keyword. + :param identifier: The identifier to test. + :return: True if the identifier is valid. + """ + return identifier.isidentifier() and not keyword.iskeyword(identifier) + + +KeyType = TypeVar('KeyType') + + +def deep_update(mapping: Dict[KeyType, Any], *updating_mappings: Dict[KeyType, Any]) -> Dict[KeyType, Any]: + updated_mapping = mapping.copy() + for updating_mapping in updating_mappings: + for k, v in updating_mapping.items(): + if k in updated_mapping and isinstance(updated_mapping[k], dict) and isinstance(v, dict): + updated_mapping[k] = deep_update(updated_mapping[k], v) + else: + updated_mapping[k] = v + return updated_mapping + + +def update_not_none(mapping: Dict[Any, Any], **update: Any) -> None: + mapping.update({k: v for k, v in update.items() if v is not None}) + + +def almost_equal_floats(value_1: float, value_2: float, *, delta: float = 1e-8) -> bool: + """ + Return True if two floats are almost equal + """ + return abs(value_1 - value_2) <= delta + + +def generate_model_signature( + init: Callable[..., None], fields: Dict[str, 'ModelField'], config: Type['BaseConfig'] +) -> 'Signature': + """ + Generate signature for model based on its fields + """ + from inspect import Parameter, Signature, signature + + from pydantic.v1.config import Extra + + present_params = signature(init).parameters.values() + merged_params: Dict[str, Parameter] = {} + var_kw = None + use_var_kw = False + + for param in islice(present_params, 1, None): # skip self arg + if param.kind is param.VAR_KEYWORD: + var_kw = param + continue + merged_params[param.name] = param + + if var_kw: # if custom init has no var_kw, fields which are not declared in it cannot be passed through + allow_names = config.allow_population_by_field_name + for field_name, field in fields.items(): + param_name = field.alias + if field_name in merged_params or param_name in merged_params: + continue + elif not is_valid_identifier(param_name): + if allow_names and is_valid_identifier(field_name): + param_name = field_name + else: + use_var_kw = True + continue + + # TODO: replace annotation with actual expected types once #1055 solved + kwargs = {'default': field.default} if not field.required else {} + merged_params[param_name] = Parameter( + param_name, Parameter.KEYWORD_ONLY, annotation=field.annotation, **kwargs + ) + + if config.extra is Extra.allow: + use_var_kw = True + + if var_kw and use_var_kw: + # Make sure the parameter for extra kwargs + # does not have the same name as a field + default_model_signature = [ + ('__pydantic_self__', Parameter.POSITIONAL_OR_KEYWORD), + ('data', Parameter.VAR_KEYWORD), + ] + if [(p.name, p.kind) for p in present_params] == default_model_signature: + # if this is the standard model signature, use extra_data as the extra args name + var_kw_name = 'extra_data' + else: + # else start from var_kw + var_kw_name = var_kw.name + + # generate a name that's definitely unique + while var_kw_name in fields: + var_kw_name += '_' + merged_params[var_kw_name] = var_kw.replace(name=var_kw_name) + + return Signature(parameters=list(merged_params.values()), return_annotation=None) + + +def get_model(obj: Union[Type['BaseModel'], Type['Dataclass']]) -> Type['BaseModel']: + from pydantic.v1.main import BaseModel + + try: + model_cls = obj.__pydantic_model__ # type: ignore + except AttributeError: + model_cls = obj + + if not issubclass(model_cls, BaseModel): + raise TypeError('Unsupported type, must be either BaseModel or dataclass') + return model_cls + + +def to_camel(string: str) -> str: + return ''.join(word.capitalize() for word in string.split('_')) + + +def to_lower_camel(string: str) -> str: + if len(string) >= 1: + pascal_string = to_camel(string) + return pascal_string[0].lower() + pascal_string[1:] + return string.lower() + + +T = TypeVar('T') + + +def unique_list( + input_list: Union[List[T], Tuple[T, ...]], + *, + name_factory: Callable[[T], str] = str, +) -> List[T]: + """ + Make a list unique while maintaining order. + We update the list if another one with the same name is set + (e.g. root validator overridden in subclass) + """ + result: List[T] = [] + result_names: List[str] = [] + for v in input_list: + v_name = name_factory(v) + if v_name not in result_names: + result_names.append(v_name) + result.append(v) + else: + result[result_names.index(v_name)] = v + + return result + + +class PyObjectStr(str): + """ + String class where repr doesn't include quotes. Useful with Representation when you want to return a string + representation of something that valid (or pseudo-valid) python. + """ + + def __repr__(self) -> str: + return str(self) + + +class Representation: + """ + Mixin to provide __str__, __repr__, and __pretty__ methods. See #884 for more details. + + __pretty__ is used by [devtools](https://python-devtools.helpmanual.io/) to provide human readable representations + of objects. + """ + + __slots__: Tuple[str, ...] = tuple() + + def __repr_args__(self) -> 'ReprArgs': + """ + Returns the attributes to show in __str__, __repr__, and __pretty__ this is generally overridden. + + Can either return: + * name - value pairs, e.g.: `[('foo_name', 'foo'), ('bar_name', ['b', 'a', 'r'])]` + * or, just values, e.g.: `[(None, 'foo'), (None, ['b', 'a', 'r'])]` + """ + attrs = ((s, getattr(self, s)) for s in self.__slots__) + return [(a, v) for a, v in attrs if v is not None] + + def __repr_name__(self) -> str: + """ + Name of the instance's class, used in __repr__. + """ + return self.__class__.__name__ + + def __repr_str__(self, join_str: str) -> str: + return join_str.join(repr(v) if a is None else f'{a}={v!r}' for a, v in self.__repr_args__()) + + def __pretty__(self, fmt: Callable[[Any], Any], **kwargs: Any) -> Generator[Any, None, None]: + """ + Used by devtools (https://python-devtools.helpmanual.io/) to provide a human readable representations of objects + """ + yield self.__repr_name__() + '(' + yield 1 + for name, value in self.__repr_args__(): + if name is not None: + yield name + '=' + yield fmt(value) + yield ',' + yield 0 + yield -1 + yield ')' + + def __str__(self) -> str: + return self.__repr_str__(' ') + + def __repr__(self) -> str: + return f'{self.__repr_name__()}({self.__repr_str__(", ")})' + + def __rich_repr__(self) -> 'RichReprResult': + """Get fields for Rich library""" + for name, field_repr in self.__repr_args__(): + if name is None: + yield field_repr + else: + yield name, field_repr + + +class GetterDict(Representation): + """ + Hack to make object's smell just enough like dicts for validate_model. + + We can't inherit from Mapping[str, Any] because it upsets cython so we have to implement all methods ourselves. + """ + + __slots__ = ('_obj',) + + def __init__(self, obj: Any): + self._obj = obj + + def __getitem__(self, key: str) -> Any: + try: + return getattr(self._obj, key) + except AttributeError as e: + raise KeyError(key) from e + + def get(self, key: Any, default: Any = None) -> Any: + return getattr(self._obj, key, default) + + def extra_keys(self) -> Set[Any]: + """ + We don't want to get any other attributes of obj if the model didn't explicitly ask for them + """ + return set() + + def keys(self) -> List[Any]: + """ + Keys of the pseudo dictionary, uses a list not set so order information can be maintained like python + dictionaries. + """ + return list(self) + + def values(self) -> List[Any]: + return [self[k] for k in self] + + def items(self) -> Iterator[Tuple[str, Any]]: + for k in self: + yield k, self.get(k) + + def __iter__(self) -> Iterator[str]: + for name in dir(self._obj): + if not name.startswith('_'): + yield name + + def __len__(self) -> int: + return sum(1 for _ in self) + + def __contains__(self, item: Any) -> bool: + return item in self.keys() + + def __eq__(self, other: Any) -> bool: + return dict(self) == dict(other.items()) + + def __repr_args__(self) -> 'ReprArgs': + return [(None, dict(self))] + + def __repr_name__(self) -> str: + return f'GetterDict[{display_as_type(self._obj)}]' + + +class ValueItems(Representation): + """ + Class for more convenient calculation of excluded or included fields on values. + """ + + __slots__ = ('_items', '_type') + + def __init__(self, value: Any, items: Union['AbstractSetIntStr', 'MappingIntStrAny']) -> None: + items = self._coerce_items(items) + + if isinstance(value, (list, tuple)): + items = self._normalize_indexes(items, len(value)) + + self._items: 'MappingIntStrAny' = items + + def is_excluded(self, item: Any) -> bool: + """ + Check if item is fully excluded. + + :param item: key or index of a value + """ + return self.is_true(self._items.get(item)) + + def is_included(self, item: Any) -> bool: + """ + Check if value is contained in self._items + + :param item: key or index of value + """ + return item in self._items + + def for_element(self, e: 'IntStr') -> Optional[Union['AbstractSetIntStr', 'MappingIntStrAny']]: + """ + :param e: key or index of element on value + :return: raw values for element if self._items is dict and contain needed element + """ + + item = self._items.get(e) + return item if not self.is_true(item) else None + + def _normalize_indexes(self, items: 'MappingIntStrAny', v_length: int) -> 'DictIntStrAny': + """ + :param items: dict or set of indexes which will be normalized + :param v_length: length of sequence indexes of which will be + + >>> self._normalize_indexes({0: True, -2: True, -1: True}, 4) + {0: True, 2: True, 3: True} + >>> self._normalize_indexes({'__all__': True}, 4) + {0: True, 1: True, 2: True, 3: True} + """ + + normalized_items: 'DictIntStrAny' = {} + all_items = None + for i, v in items.items(): + if not (isinstance(v, Mapping) or isinstance(v, AbstractSet) or self.is_true(v)): + raise TypeError(f'Unexpected type of exclude value for index "{i}" {v.__class__}') + if i == '__all__': + all_items = self._coerce_value(v) + continue + if not isinstance(i, int): + raise TypeError( + 'Excluding fields from a sequence of sub-models or dicts must be performed index-wise: ' + 'expected integer keys or keyword "__all__"' + ) + normalized_i = v_length + i if i < 0 else i + normalized_items[normalized_i] = self.merge(v, normalized_items.get(normalized_i)) + + if not all_items: + return normalized_items + if self.is_true(all_items): + for i in range(v_length): + normalized_items.setdefault(i, ...) + return normalized_items + for i in range(v_length): + normalized_item = normalized_items.setdefault(i, {}) + if not self.is_true(normalized_item): + normalized_items[i] = self.merge(all_items, normalized_item) + return normalized_items + + @classmethod + def merge(cls, base: Any, override: Any, intersect: bool = False) -> Any: + """ + Merge a ``base`` item with an ``override`` item. + + Both ``base`` and ``override`` are converted to dictionaries if possible. + Sets are converted to dictionaries with the sets entries as keys and + Ellipsis as values. + + Each key-value pair existing in ``base`` is merged with ``override``, + while the rest of the key-value pairs are updated recursively with this function. + + Merging takes place based on the "union" of keys if ``intersect`` is + set to ``False`` (default) and on the intersection of keys if + ``intersect`` is set to ``True``. + """ + override = cls._coerce_value(override) + base = cls._coerce_value(base) + if override is None: + return base + if cls.is_true(base) or base is None: + return override + if cls.is_true(override): + return base if intersect else override + + # intersection or union of keys while preserving ordering: + if intersect: + merge_keys = [k for k in base if k in override] + [k for k in override if k in base] + else: + merge_keys = list(base) + [k for k in override if k not in base] + + merged: 'DictIntStrAny' = {} + for k in merge_keys: + merged_item = cls.merge(base.get(k), override.get(k), intersect=intersect) + if merged_item is not None: + merged[k] = merged_item + + return merged + + @staticmethod + def _coerce_items(items: Union['AbstractSetIntStr', 'MappingIntStrAny']) -> 'MappingIntStrAny': + if isinstance(items, Mapping): + pass + elif isinstance(items, AbstractSet): + items = dict.fromkeys(items, ...) + else: + class_name = getattr(items, '__class__', '???') + assert_never( + items, + f'Unexpected type of exclude value {class_name}', + ) + return items + + @classmethod + def _coerce_value(cls, value: Any) -> Any: + if value is None or cls.is_true(value): + return value + return cls._coerce_items(value) + + @staticmethod + def is_true(v: Any) -> bool: + return v is True or v is ... + + def __repr_args__(self) -> 'ReprArgs': + return [(None, self._items)] + + +class ClassAttribute: + """ + Hide class attribute from its instances + """ + + __slots__ = ( + 'name', + 'value', + ) + + def __init__(self, name: str, value: Any) -> None: + self.name = name + self.value = value + + def __get__(self, instance: Any, owner: Type[Any]) -> None: + if instance is None: + return self.value + raise AttributeError(f'{self.name!r} attribute of {owner.__name__!r} is class-only') + + +path_types = { + 'is_dir': 'directory', + 'is_file': 'file', + 'is_mount': 'mount point', + 'is_symlink': 'symlink', + 'is_block_device': 'block device', + 'is_char_device': 'char device', + 'is_fifo': 'FIFO', + 'is_socket': 'socket', +} + + +def path_type(p: 'Path') -> str: + """ + Find out what sort of thing a path is. + """ + assert p.exists(), 'path does not exist' + for method, name in path_types.items(): + if getattr(p, method)(): + return name + + return 'unknown' + + +Obj = TypeVar('Obj') + + +def smart_deepcopy(obj: Obj) -> Obj: + """ + Return type as is for immutable built-in types + Use obj.copy() for built-in empty collections + Use copy.deepcopy() for non-empty collections and unknown objects + """ + + obj_type = obj.__class__ + if obj_type in IMMUTABLE_NON_COLLECTIONS_TYPES: + return obj # fastest case: obj is immutable and not collection therefore will not be copied anyway + try: + if not obj and obj_type in BUILTIN_COLLECTIONS: + # faster way for empty collections, no need to copy its members + return obj if obj_type is tuple else obj.copy() # type: ignore # tuple doesn't have copy method + except (TypeError, ValueError, RuntimeError): + # do we really dare to catch ALL errors? Seems a bit risky + pass + + return deepcopy(obj) # slowest way when we actually might need a deepcopy + + +def is_valid_field(name: str) -> bool: + if not name.startswith('_'): + return True + return ROOT_KEY == name + + +DUNDER_ATTRIBUTES = { + '__annotations__', + '__classcell__', + '__doc__', + '__module__', + '__orig_bases__', + '__orig_class__', + '__qualname__', +} + + +def is_valid_private_name(name: str) -> bool: + return not is_valid_field(name) and name not in DUNDER_ATTRIBUTES + + +_EMPTY = object() + + +def all_identical(left: Iterable[Any], right: Iterable[Any]) -> bool: + """ + Check that the items of `left` are the same objects as those in `right`. + + >>> a, b = object(), object() + >>> all_identical([a, b, a], [a, b, a]) + True + >>> all_identical([a, b, [a]], [a, b, [a]]) # new list object, while "equal" is not "identical" + False + """ + for left_item, right_item in zip_longest(left, right, fillvalue=_EMPTY): + if left_item is not right_item: + return False + return True + + +def assert_never(obj: NoReturn, msg: str) -> NoReturn: + """ + Helper to make sure that we have covered all possible types. + + This is mostly useful for ``mypy``, docs: + https://mypy.readthedocs.io/en/latest/literal_types.html#exhaustive-checks + """ + raise TypeError(msg) + + +def get_unique_discriminator_alias(all_aliases: Collection[str], discriminator_key: str) -> str: + """Validate that all aliases are the same and if that's the case return the alias""" + unique_aliases = set(all_aliases) + if len(unique_aliases) > 1: + raise ConfigError( + f'Aliases for discriminator {discriminator_key!r} must be the same (got {", ".join(sorted(all_aliases))})' + ) + return unique_aliases.pop() + + +def get_discriminator_alias_and_values(tp: Any, discriminator_key: str) -> Tuple[str, Tuple[str, ...]]: + """ + Get alias and all valid values in the `Literal` type of the discriminator field + `tp` can be a `BaseModel` class or directly an `Annotated` `Union` of many. + """ + is_root_model = getattr(tp, '__custom_root_type__', False) + + if get_origin(tp) is Annotated: + tp = get_args(tp)[0] + + if hasattr(tp, '__pydantic_model__'): + tp = tp.__pydantic_model__ + + if is_union(get_origin(tp)): + alias, all_values = _get_union_alias_and_all_values(tp, discriminator_key) + return alias, tuple(v for values in all_values for v in values) + elif is_root_model: + union_type = tp.__fields__[ROOT_KEY].type_ + alias, all_values = _get_union_alias_and_all_values(union_type, discriminator_key) + + if len(set(all_values)) > 1: + raise ConfigError( + f'Field {discriminator_key!r} is not the same for all submodels of {display_as_type(tp)!r}' + ) + + return alias, all_values[0] + + else: + try: + t_discriminator_type = tp.__fields__[discriminator_key].type_ + except AttributeError as e: + raise TypeError(f'Type {tp.__name__!r} is not a valid `BaseModel` or `dataclass`') from e + except KeyError as e: + raise ConfigError(f'Model {tp.__name__!r} needs a discriminator field for key {discriminator_key!r}') from e + + if not is_literal_type(t_discriminator_type): + raise ConfigError(f'Field {discriminator_key!r} of model {tp.__name__!r} needs to be a `Literal`') + + return tp.__fields__[discriminator_key].alias, all_literal_values(t_discriminator_type) + + +def _get_union_alias_and_all_values( + union_type: Type[Any], discriminator_key: str +) -> Tuple[str, Tuple[Tuple[str, ...], ...]]: + zipped_aliases_values = [get_discriminator_alias_and_values(t, discriminator_key) for t in get_args(union_type)] + # unzip: [('alias_a',('v1', 'v2)), ('alias_b', ('v3',))] => [('alias_a', 'alias_b'), (('v1', 'v2'), ('v3',))] + all_aliases, all_values = zip(*zipped_aliases_values) + return get_unique_discriminator_alias(all_aliases, discriminator_key), all_values diff --git a/env/Lib/site-packages/pydantic/v1/validators.py b/env/Lib/site-packages/pydantic/v1/validators.py new file mode 100644 index 0000000..7c39aa9 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/validators.py @@ -0,0 +1,765 @@ +import math +import re +from collections import OrderedDict, deque +from collections.abc import Hashable as CollectionsHashable +from datetime import date, datetime, time, timedelta +from decimal import Decimal, DecimalException +from enum import Enum, IntEnum +from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Deque, + Dict, + ForwardRef, + FrozenSet, + Generator, + Hashable, + List, + NamedTuple, + Pattern, + Set, + Tuple, + Type, + TypeVar, + Union, +) +from uuid import UUID + +from pydantic.v1 import errors +from pydantic.v1.datetime_parse import parse_date, parse_datetime, parse_duration, parse_time +from pydantic.v1.typing import ( + AnyCallable, + all_literal_values, + display_as_type, + get_class, + is_callable_type, + is_literal_type, + is_namedtuple, + is_none_type, + is_typeddict, +) +from pydantic.v1.utils import almost_equal_floats, lenient_issubclass, sequence_like + +if TYPE_CHECKING: + from typing_extensions import Literal, TypedDict + + from pydantic.v1.config import BaseConfig + from pydantic.v1.fields import ModelField + from pydantic.v1.types import ConstrainedDecimal, ConstrainedFloat, ConstrainedInt + + ConstrainedNumber = Union[ConstrainedDecimal, ConstrainedFloat, ConstrainedInt] + AnyOrderedDict = OrderedDict[Any, Any] + Number = Union[int, float, Decimal] + StrBytes = Union[str, bytes] + + +def str_validator(v: Any) -> Union[str]: + if isinstance(v, str): + if isinstance(v, Enum): + return v.value + else: + return v + elif isinstance(v, (float, int, Decimal)): + # is there anything else we want to add here? If you think so, create an issue. + return str(v) + elif isinstance(v, (bytes, bytearray)): + return v.decode() + else: + raise errors.StrError() + + +def strict_str_validator(v: Any) -> Union[str]: + if isinstance(v, str) and not isinstance(v, Enum): + return v + raise errors.StrError() + + +def bytes_validator(v: Any) -> Union[bytes]: + if isinstance(v, bytes): + return v + elif isinstance(v, bytearray): + return bytes(v) + elif isinstance(v, str): + return v.encode() + elif isinstance(v, (float, int, Decimal)): + return str(v).encode() + else: + raise errors.BytesError() + + +def strict_bytes_validator(v: Any) -> Union[bytes]: + if isinstance(v, bytes): + return v + elif isinstance(v, bytearray): + return bytes(v) + else: + raise errors.BytesError() + + +BOOL_FALSE = {0, '0', 'off', 'f', 'false', 'n', 'no'} +BOOL_TRUE = {1, '1', 'on', 't', 'true', 'y', 'yes'} + + +def bool_validator(v: Any) -> bool: + if v is True or v is False: + return v + if isinstance(v, bytes): + v = v.decode() + if isinstance(v, str): + v = v.lower() + try: + if v in BOOL_TRUE: + return True + if v in BOOL_FALSE: + return False + except TypeError: + raise errors.BoolError() + raise errors.BoolError() + + +# matches the default limit cpython, see https://github.com/python/cpython/pull/96500 +max_str_int = 4_300 + + +def int_validator(v: Any) -> int: + if isinstance(v, int) and not (v is True or v is False): + return v + + # see https://github.com/pydantic/pydantic/issues/1477 and in turn, https://github.com/python/cpython/issues/95778 + # this check should be unnecessary once patch releases are out for 3.7, 3.8, 3.9 and 3.10 + # but better to check here until then. + # NOTICE: this does not fully protect user from the DOS risk since the standard library JSON implementation + # (and other std lib modules like xml) use `int()` and are likely called before this, the best workaround is to + # 1. update to the latest patch release of python once released, 2. use a different JSON library like ujson + if isinstance(v, (str, bytes, bytearray)) and len(v) > max_str_int: + raise errors.IntegerError() + + try: + return int(v) + except (TypeError, ValueError, OverflowError): + raise errors.IntegerError() + + +def strict_int_validator(v: Any) -> int: + if isinstance(v, int) and not (v is True or v is False): + return v + raise errors.IntegerError() + + +def float_validator(v: Any) -> float: + if isinstance(v, float): + return v + + try: + return float(v) + except (TypeError, ValueError): + raise errors.FloatError() + + +def strict_float_validator(v: Any) -> float: + if isinstance(v, float): + return v + raise errors.FloatError() + + +def float_finite_validator(v: 'Number', field: 'ModelField', config: 'BaseConfig') -> 'Number': + allow_inf_nan = getattr(field.type_, 'allow_inf_nan', None) + if allow_inf_nan is None: + allow_inf_nan = config.allow_inf_nan + + if allow_inf_nan is False and (math.isnan(v) or math.isinf(v)): + raise errors.NumberNotFiniteError() + return v + + +def number_multiple_validator(v: 'Number', field: 'ModelField') -> 'Number': + field_type: ConstrainedNumber = field.type_ + if field_type.multiple_of is not None: + mod = float(v) / float(field_type.multiple_of) % 1 + if not almost_equal_floats(mod, 0.0) and not almost_equal_floats(mod, 1.0): + raise errors.NumberNotMultipleError(multiple_of=field_type.multiple_of) + return v + + +def number_size_validator(v: 'Number', field: 'ModelField') -> 'Number': + field_type: ConstrainedNumber = field.type_ + if field_type.gt is not None and not v > field_type.gt: + raise errors.NumberNotGtError(limit_value=field_type.gt) + elif field_type.ge is not None and not v >= field_type.ge: + raise errors.NumberNotGeError(limit_value=field_type.ge) + + if field_type.lt is not None and not v < field_type.lt: + raise errors.NumberNotLtError(limit_value=field_type.lt) + if field_type.le is not None and not v <= field_type.le: + raise errors.NumberNotLeError(limit_value=field_type.le) + + return v + + +def constant_validator(v: 'Any', field: 'ModelField') -> 'Any': + """Validate ``const`` fields. + + The value provided for a ``const`` field must be equal to the default value + of the field. This is to support the keyword of the same name in JSON + Schema. + """ + if v != field.default: + raise errors.WrongConstantError(given=v, permitted=[field.default]) + + return v + + +def anystr_length_validator(v: 'StrBytes', config: 'BaseConfig') -> 'StrBytes': + v_len = len(v) + + min_length = config.min_anystr_length + if v_len < min_length: + raise errors.AnyStrMinLengthError(limit_value=min_length) + + max_length = config.max_anystr_length + if max_length is not None and v_len > max_length: + raise errors.AnyStrMaxLengthError(limit_value=max_length) + + return v + + +def anystr_strip_whitespace(v: 'StrBytes') -> 'StrBytes': + return v.strip() + + +def anystr_upper(v: 'StrBytes') -> 'StrBytes': + return v.upper() + + +def anystr_lower(v: 'StrBytes') -> 'StrBytes': + return v.lower() + + +def ordered_dict_validator(v: Any) -> 'AnyOrderedDict': + if isinstance(v, OrderedDict): + return v + + try: + return OrderedDict(v) + except (TypeError, ValueError): + raise errors.DictError() + + +def dict_validator(v: Any) -> Dict[Any, Any]: + if isinstance(v, dict): + return v + + try: + return dict(v) + except (TypeError, ValueError): + raise errors.DictError() + + +def list_validator(v: Any) -> List[Any]: + if isinstance(v, list): + return v + elif sequence_like(v): + return list(v) + else: + raise errors.ListError() + + +def tuple_validator(v: Any) -> Tuple[Any, ...]: + if isinstance(v, tuple): + return v + elif sequence_like(v): + return tuple(v) + else: + raise errors.TupleError() + + +def set_validator(v: Any) -> Set[Any]: + if isinstance(v, set): + return v + elif sequence_like(v): + return set(v) + else: + raise errors.SetError() + + +def frozenset_validator(v: Any) -> FrozenSet[Any]: + if isinstance(v, frozenset): + return v + elif sequence_like(v): + return frozenset(v) + else: + raise errors.FrozenSetError() + + +def deque_validator(v: Any) -> Deque[Any]: + if isinstance(v, deque): + return v + elif sequence_like(v): + return deque(v) + else: + raise errors.DequeError() + + +def enum_member_validator(v: Any, field: 'ModelField', config: 'BaseConfig') -> Enum: + try: + enum_v = field.type_(v) + except ValueError: + # field.type_ should be an enum, so will be iterable + raise errors.EnumMemberError(enum_values=list(field.type_)) + return enum_v.value if config.use_enum_values else enum_v + + +def uuid_validator(v: Any, field: 'ModelField') -> UUID: + try: + if isinstance(v, str): + v = UUID(v) + elif isinstance(v, (bytes, bytearray)): + try: + v = UUID(v.decode()) + except ValueError: + # 16 bytes in big-endian order as the bytes argument fail + # the above check + v = UUID(bytes=v) + except ValueError: + raise errors.UUIDError() + + if not isinstance(v, UUID): + raise errors.UUIDError() + + required_version = getattr(field.type_, '_required_version', None) + if required_version and v.version != required_version: + raise errors.UUIDVersionError(required_version=required_version) + + return v + + +def decimal_validator(v: Any) -> Decimal: + if isinstance(v, Decimal): + return v + elif isinstance(v, (bytes, bytearray)): + v = v.decode() + + v = str(v).strip() + + try: + v = Decimal(v) + except DecimalException: + raise errors.DecimalError() + + if not v.is_finite(): + raise errors.DecimalIsNotFiniteError() + + return v + + +def hashable_validator(v: Any) -> Hashable: + if isinstance(v, Hashable): + return v + + raise errors.HashableError() + + +def ip_v4_address_validator(v: Any) -> IPv4Address: + if isinstance(v, IPv4Address): + return v + + try: + return IPv4Address(v) + except ValueError: + raise errors.IPv4AddressError() + + +def ip_v6_address_validator(v: Any) -> IPv6Address: + if isinstance(v, IPv6Address): + return v + + try: + return IPv6Address(v) + except ValueError: + raise errors.IPv6AddressError() + + +def ip_v4_network_validator(v: Any) -> IPv4Network: + """ + Assume IPv4Network initialised with a default ``strict`` argument + + See more: + https://docs.python.org/library/ipaddress.html#ipaddress.IPv4Network + """ + if isinstance(v, IPv4Network): + return v + + try: + return IPv4Network(v) + except ValueError: + raise errors.IPv4NetworkError() + + +def ip_v6_network_validator(v: Any) -> IPv6Network: + """ + Assume IPv6Network initialised with a default ``strict`` argument + + See more: + https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network + """ + if isinstance(v, IPv6Network): + return v + + try: + return IPv6Network(v) + except ValueError: + raise errors.IPv6NetworkError() + + +def ip_v4_interface_validator(v: Any) -> IPv4Interface: + if isinstance(v, IPv4Interface): + return v + + try: + return IPv4Interface(v) + except ValueError: + raise errors.IPv4InterfaceError() + + +def ip_v6_interface_validator(v: Any) -> IPv6Interface: + if isinstance(v, IPv6Interface): + return v + + try: + return IPv6Interface(v) + except ValueError: + raise errors.IPv6InterfaceError() + + +def path_validator(v: Any) -> Path: + if isinstance(v, Path): + return v + + try: + return Path(v) + except TypeError: + raise errors.PathError() + + +def path_exists_validator(v: Any) -> Path: + if not v.exists(): + raise errors.PathNotExistsError(path=v) + + return v + + +def callable_validator(v: Any) -> AnyCallable: + """ + Perform a simple check if the value is callable. + + Note: complete matching of argument type hints and return types is not performed + """ + if callable(v): + return v + + raise errors.CallableError(value=v) + + +def enum_validator(v: Any) -> Enum: + if isinstance(v, Enum): + return v + + raise errors.EnumError(value=v) + + +def int_enum_validator(v: Any) -> IntEnum: + if isinstance(v, IntEnum): + return v + + raise errors.IntEnumError(value=v) + + +def make_literal_validator(type_: Any) -> Callable[[Any], Any]: + permitted_choices = all_literal_values(type_) + + # To have a O(1) complexity and still return one of the values set inside the `Literal`, + # we create a dict with the set values (a set causes some problems with the way intersection works). + # In some cases the set value and checked value can indeed be different (see `test_literal_validator_str_enum`) + allowed_choices = {v: v for v in permitted_choices} + + def literal_validator(v: Any) -> Any: + try: + return allowed_choices[v] + except (KeyError, TypeError): + raise errors.WrongConstantError(given=v, permitted=permitted_choices) + + return literal_validator + + +def constr_length_validator(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': + v_len = len(v) + + min_length = field.type_.min_length if field.type_.min_length is not None else config.min_anystr_length + if v_len < min_length: + raise errors.AnyStrMinLengthError(limit_value=min_length) + + max_length = field.type_.max_length if field.type_.max_length is not None else config.max_anystr_length + if max_length is not None and v_len > max_length: + raise errors.AnyStrMaxLengthError(limit_value=max_length) + + return v + + +def constr_strip_whitespace(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': + strip_whitespace = field.type_.strip_whitespace or config.anystr_strip_whitespace + if strip_whitespace: + v = v.strip() + + return v + + +def constr_upper(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': + upper = field.type_.to_upper or config.anystr_upper + if upper: + v = v.upper() + + return v + + +def constr_lower(v: 'StrBytes', field: 'ModelField', config: 'BaseConfig') -> 'StrBytes': + lower = field.type_.to_lower or config.anystr_lower + if lower: + v = v.lower() + return v + + +def validate_json(v: Any, config: 'BaseConfig') -> Any: + if v is None: + # pass None through to other validators + return v + try: + return config.json_loads(v) # type: ignore + except ValueError: + raise errors.JsonError() + except TypeError: + raise errors.JsonTypeError() + + +T = TypeVar('T') + + +def make_arbitrary_type_validator(type_: Type[T]) -> Callable[[T], T]: + def arbitrary_type_validator(v: Any) -> T: + if isinstance(v, type_): + return v + raise errors.ArbitraryTypeError(expected_arbitrary_type=type_) + + return arbitrary_type_validator + + +def make_class_validator(type_: Type[T]) -> Callable[[Any], Type[T]]: + def class_validator(v: Any) -> Type[T]: + if lenient_issubclass(v, type_): + return v + raise errors.SubclassError(expected_class=type_) + + return class_validator + + +def any_class_validator(v: Any) -> Type[T]: + if isinstance(v, type): + return v + raise errors.ClassError() + + +def none_validator(v: Any) -> 'Literal[None]': + if v is None: + return v + raise errors.NotNoneError() + + +def pattern_validator(v: Any) -> Pattern[str]: + if isinstance(v, Pattern): + return v + + str_value = str_validator(v) + + try: + return re.compile(str_value) + except re.error: + raise errors.PatternError() + + +NamedTupleT = TypeVar('NamedTupleT', bound=NamedTuple) + + +def make_namedtuple_validator( + namedtuple_cls: Type[NamedTupleT], config: Type['BaseConfig'] +) -> Callable[[Tuple[Any, ...]], NamedTupleT]: + from pydantic.v1.annotated_types import create_model_from_namedtuple + + NamedTupleModel = create_model_from_namedtuple( + namedtuple_cls, + __config__=config, + __module__=namedtuple_cls.__module__, + ) + namedtuple_cls.__pydantic_model__ = NamedTupleModel # type: ignore[attr-defined] + + def namedtuple_validator(values: Tuple[Any, ...]) -> NamedTupleT: + annotations = NamedTupleModel.__annotations__ + + if len(values) > len(annotations): + raise errors.ListMaxLengthError(limit_value=len(annotations)) + + dict_values: Dict[str, Any] = dict(zip(annotations, values)) + validated_dict_values: Dict[str, Any] = dict(NamedTupleModel(**dict_values)) + return namedtuple_cls(**validated_dict_values) + + return namedtuple_validator + + +def make_typeddict_validator( + typeddict_cls: Type['TypedDict'], config: Type['BaseConfig'] # type: ignore[valid-type] +) -> Callable[[Any], Dict[str, Any]]: + from pydantic.v1.annotated_types import create_model_from_typeddict + + TypedDictModel = create_model_from_typeddict( + typeddict_cls, + __config__=config, + __module__=typeddict_cls.__module__, + ) + typeddict_cls.__pydantic_model__ = TypedDictModel # type: ignore[attr-defined] + + def typeddict_validator(values: 'TypedDict') -> Dict[str, Any]: # type: ignore[valid-type] + return TypedDictModel.parse_obj(values).dict(exclude_unset=True) + + return typeddict_validator + + +class IfConfig: + def __init__(self, validator: AnyCallable, *config_attr_names: str, ignored_value: Any = False) -> None: + self.validator = validator + self.config_attr_names = config_attr_names + self.ignored_value = ignored_value + + def check(self, config: Type['BaseConfig']) -> bool: + return any(getattr(config, name) not in {None, self.ignored_value} for name in self.config_attr_names) + + +# order is important here, for example: bool is a subclass of int so has to come first, datetime before date same, +# IPv4Interface before IPv4Address, etc +_VALIDATORS: List[Tuple[Type[Any], List[Any]]] = [ + (IntEnum, [int_validator, enum_member_validator]), + (Enum, [enum_member_validator]), + ( + str, + [ + str_validator, + IfConfig(anystr_strip_whitespace, 'anystr_strip_whitespace'), + IfConfig(anystr_upper, 'anystr_upper'), + IfConfig(anystr_lower, 'anystr_lower'), + IfConfig(anystr_length_validator, 'min_anystr_length', 'max_anystr_length'), + ], + ), + ( + bytes, + [ + bytes_validator, + IfConfig(anystr_strip_whitespace, 'anystr_strip_whitespace'), + IfConfig(anystr_upper, 'anystr_upper'), + IfConfig(anystr_lower, 'anystr_lower'), + IfConfig(anystr_length_validator, 'min_anystr_length', 'max_anystr_length'), + ], + ), + (bool, [bool_validator]), + (int, [int_validator]), + (float, [float_validator, IfConfig(float_finite_validator, 'allow_inf_nan', ignored_value=True)]), + (Path, [path_validator]), + (datetime, [parse_datetime]), + (date, [parse_date]), + (time, [parse_time]), + (timedelta, [parse_duration]), + (OrderedDict, [ordered_dict_validator]), + (dict, [dict_validator]), + (list, [list_validator]), + (tuple, [tuple_validator]), + (set, [set_validator]), + (frozenset, [frozenset_validator]), + (deque, [deque_validator]), + (UUID, [uuid_validator]), + (Decimal, [decimal_validator]), + (IPv4Interface, [ip_v4_interface_validator]), + (IPv6Interface, [ip_v6_interface_validator]), + (IPv4Address, [ip_v4_address_validator]), + (IPv6Address, [ip_v6_address_validator]), + (IPv4Network, [ip_v4_network_validator]), + (IPv6Network, [ip_v6_network_validator]), +] + + +def find_validators( # noqa: C901 (ignore complexity) + type_: Type[Any], config: Type['BaseConfig'] +) -> Generator[AnyCallable, None, None]: + from pydantic.v1.dataclasses import is_builtin_dataclass, make_dataclass_validator + + if type_ is Any or type_ is object: + return + type_type = type_.__class__ + if type_type == ForwardRef or type_type == TypeVar: + return + + if is_none_type(type_): + yield none_validator + return + if type_ is Pattern or type_ is re.Pattern: + yield pattern_validator + return + if type_ is Hashable or type_ is CollectionsHashable: + yield hashable_validator + return + if is_callable_type(type_): + yield callable_validator + return + if is_literal_type(type_): + yield make_literal_validator(type_) + return + if is_builtin_dataclass(type_): + yield from make_dataclass_validator(type_, config) + return + if type_ is Enum: + yield enum_validator + return + if type_ is IntEnum: + yield int_enum_validator + return + if is_namedtuple(type_): + yield tuple_validator + yield make_namedtuple_validator(type_, config) + return + if is_typeddict(type_): + yield make_typeddict_validator(type_, config) + return + + class_ = get_class(type_) + if class_ is not None: + if class_ is not Any and isinstance(class_, type): + yield make_class_validator(class_) + else: + yield any_class_validator + return + + for val_type, validators in _VALIDATORS: + try: + if issubclass(type_, val_type): + for v in validators: + if isinstance(v, IfConfig): + if v.check(config): + yield v.validator + else: + yield v + return + except TypeError: + raise RuntimeError(f'error checking inheritance of {type_!r} (type: {display_as_type(type_)})') + + if config.arbitrary_types_allowed: + yield make_arbitrary_type_validator(type_) + else: + raise RuntimeError(f'no validator found for {type_}, see `arbitrary_types_allowed` in Config') diff --git a/env/Lib/site-packages/pydantic/v1/version.py b/env/Lib/site-packages/pydantic/v1/version.py new file mode 100644 index 0000000..8127c11 --- /dev/null +++ b/env/Lib/site-packages/pydantic/v1/version.py @@ -0,0 +1,38 @@ +__all__ = 'compiled', 'VERSION', 'version_info' + +VERSION = '1.10.17' + +try: + import cython # type: ignore +except ImportError: + compiled: bool = False +else: # pragma: no cover + try: + compiled = cython.compiled + except AttributeError: + compiled = False + + +def version_info() -> str: + import platform + import sys + from importlib import import_module + from pathlib import Path + + optional_deps = [] + for p in ('devtools', 'dotenv', 'email-validator', 'typing-extensions'): + try: + import_module(p.replace('-', '_')) + except ImportError: + continue + optional_deps.append(p) + + info = { + 'pydantic version': VERSION, + 'pydantic compiled': compiled, + 'install path': Path(__file__).resolve().parent, + 'python version': sys.version, + 'platform': platform.platform(), + 'optional deps. installed': optional_deps, + } + return '\n'.join('{:>30} {}'.format(k + ':', str(v).replace('\n', ' ')) for k, v in info.items()) diff --git a/env/Lib/site-packages/pydantic/validate_call_decorator.py b/env/Lib/site-packages/pydantic/validate_call_decorator.py new file mode 100644 index 0000000..5314c92 --- /dev/null +++ b/env/Lib/site-packages/pydantic/validate_call_decorator.py @@ -0,0 +1,69 @@ +"""Decorator for validating function calls.""" + +from __future__ import annotations as _annotations + +import functools +from typing import TYPE_CHECKING, Any, Callable, TypeVar, overload + +from ._internal import _typing_extra, _validate_call + +__all__ = ('validate_call',) + +if TYPE_CHECKING: + from .config import ConfigDict + + AnyCallableT = TypeVar('AnyCallableT', bound=Callable[..., Any]) + + +@overload +def validate_call( + *, config: ConfigDict | None = None, validate_return: bool = False +) -> Callable[[AnyCallableT], AnyCallableT]: ... + + +@overload +def validate_call(func: AnyCallableT, /) -> AnyCallableT: ... + + +def validate_call( + func: AnyCallableT | None = None, + /, + *, + config: ConfigDict | None = None, + validate_return: bool = False, +) -> AnyCallableT | Callable[[AnyCallableT], AnyCallableT]: + """Usage docs: https://docs.pydantic.dev/2.8/concepts/validation_decorator/ + + Returns a decorated wrapper around the function that validates the arguments and, optionally, the return value. + + Usage may be either as a plain decorator `@validate_call` or with arguments `@validate_call(...)`. + + Args: + func: The function to be decorated. + config: The configuration dictionary. + validate_return: Whether to validate the return value. + + Returns: + The decorated function. + """ + local_ns = _typing_extra.parent_frame_namespace() + + def validate(function: AnyCallableT) -> AnyCallableT: + if isinstance(function, (classmethod, staticmethod)): + name = type(function).__name__ + raise TypeError(f'The `@{name}` decorator should be applied after `@validate_call` (put `@{name}` on top)') + + validate_call_wrapper = _validate_call.ValidateCallWrapper(function, config, validate_return, local_ns) + + @functools.wraps(function) + def wrapper_function(*args, **kwargs): + return validate_call_wrapper(*args, **kwargs) + + wrapper_function.raw_function = function # type: ignore + + return wrapper_function # type: ignore + + if func: + return validate(func) + else: + return validate diff --git a/env/Lib/site-packages/pydantic/validators.py b/env/Lib/site-packages/pydantic/validators.py new file mode 100644 index 0000000..7921b04 --- /dev/null +++ b/env/Lib/site-packages/pydantic/validators.py @@ -0,0 +1,5 @@ +"""The `validators` module is a backport module from V1.""" + +from ._migration import getattr_migration + +__getattr__ = getattr_migration(__name__) diff --git a/env/Lib/site-packages/pydantic/version.py b/env/Lib/site-packages/pydantic/version.py new file mode 100644 index 0000000..fa69a3a --- /dev/null +++ b/env/Lib/site-packages/pydantic/version.py @@ -0,0 +1,78 @@ +"""The `version` module holds the version information for Pydantic.""" + +from __future__ import annotations as _annotations + +__all__ = 'VERSION', 'version_info' + +VERSION = '2.8.2' +"""The version of Pydantic.""" + + +def version_short() -> str: + """Return the `major.minor` part of Pydantic version. + + It returns '2.1' if Pydantic version is '2.1.1'. + """ + return '.'.join(VERSION.split('.')[:2]) + + +def version_info() -> str: + """Return complete version information for Pydantic and its dependencies.""" + import importlib.metadata as importlib_metadata + import os + import platform + import sys + from pathlib import Path + + import pydantic_core._pydantic_core as pdc + + from ._internal import _git as git + + # get data about packages that are closely related to pydantic, use pydantic or often conflict with pydantic + package_names = { + 'email-validator', + 'fastapi', + 'mypy', + 'pydantic-extra-types', + 'pydantic-settings', + 'pyright', + 'typing_extensions', + } + related_packages = [] + + for dist in importlib_metadata.distributions(): + name = dist.metadata['Name'] + if name in package_names: + related_packages.append(f'{name}-{dist.version}') + + pydantic_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + most_recent_commit = ( + git.git_revision(pydantic_dir) if git.is_git_repo(pydantic_dir) and git.have_git() else 'unknown' + ) + + info = { + 'pydantic version': VERSION, + 'pydantic-core version': pdc.__version__, + 'pydantic-core build': getattr(pdc, 'build_info', None) or pdc.build_profile, + 'install path': Path(__file__).resolve().parent, + 'python version': sys.version, + 'platform': platform.platform(), + 'related packages': ' '.join(related_packages), + 'commit': most_recent_commit, + } + return '\n'.join('{:>30} {}'.format(k + ':', str(v).replace('\n', ' ')) for k, v in info.items()) + + +def parse_mypy_version(version: str) -> tuple[int, ...]: + """Parse mypy string version to tuple of ints. + + It parses normal version like `0.930` and extra info followed by a `+` sign + like `0.940+dev.04cac4b5d911c4f9529e6ce86a27b44f28846f5d.dirty`. + + Args: + version: The mypy version string. + + Returns: + A tuple of ints. e.g. (0, 930). + """ + return tuple(map(int, version.partition('+')[0].split('.'))) diff --git a/env/Lib/site-packages/pydantic/warnings.py b/env/Lib/site-packages/pydantic/warnings.py new file mode 100644 index 0000000..ea9fa6d --- /dev/null +++ b/env/Lib/site-packages/pydantic/warnings.py @@ -0,0 +1,72 @@ +"""Pydantic-specific warnings.""" + +from __future__ import annotations as _annotations + +from .version import version_short + +__all__ = ( + 'PydanticDeprecatedSince20', + 'PydanticDeprecationWarning', + 'PydanticDeprecatedSince26', + 'PydanticExperimentalWarning', +) + + +class PydanticDeprecationWarning(DeprecationWarning): + """A Pydantic specific deprecation warning. + + This warning is raised when using deprecated functionality in Pydantic. It provides information on when the + deprecation was introduced and the expected version in which the corresponding functionality will be removed. + + Attributes: + message: Description of the warning. + since: Pydantic version in what the deprecation was introduced. + expected_removal: Pydantic version in what the corresponding functionality expected to be removed. + """ + + message: str + since: tuple[int, int] + expected_removal: tuple[int, int] + + def __init__( + self, message: str, *args: object, since: tuple[int, int], expected_removal: tuple[int, int] | None = None + ) -> None: + super().__init__(message, *args) + self.message = message.rstrip('.') + self.since = since + self.expected_removal = expected_removal if expected_removal is not None else (since[0] + 1, 0) + + def __str__(self) -> str: + message = ( + f'{self.message}. Deprecated in Pydantic V{self.since[0]}.{self.since[1]}' + f' to be removed in V{self.expected_removal[0]}.{self.expected_removal[1]}.' + ) + if self.since == (2, 0): + message += f' See Pydantic V2 Migration Guide at https://errors.pydantic.dev/{version_short()}/migration/' + return message + + +class PydanticDeprecatedSince20(PydanticDeprecationWarning): + """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.0.""" + + def __init__(self, message: str, *args: object) -> None: + super().__init__(message, *args, since=(2, 0), expected_removal=(3, 0)) + + +class PydanticDeprecatedSince26(PydanticDeprecationWarning): + """A specific `PydanticDeprecationWarning` subclass defining functionality deprecated since Pydantic 2.6.""" + + def __init__(self, message: str, *args: object) -> None: + super().__init__(message, *args, since=(2, 0), expected_removal=(3, 0)) + + +class GenericBeforeBaseModelWarning(Warning): + pass + + +class PydanticExperimentalWarning(Warning): + """A Pydantic specific experimental functionality warning. + + This warning is raised when using experimental functionality in Pydantic. + It is raised to warn users that the functionality may change or be removed in future versions of Pydantic. + """ diff --git a/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/INSTALLER b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/METADATA b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/METADATA new file mode 100644 index 0000000..a5efeb6 --- /dev/null +++ b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/METADATA @@ -0,0 +1,161 @@ +Metadata-Version: 2.3 +Name: pydantic_core +Version: 2.20.1 +Classifier: Development Status :: 3 - Alpha +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Rust +Classifier: Framework :: Pydantic +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Information Technology +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: POSIX :: Linux +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: MacOS +Classifier: Typing :: Typed +Requires-Dist: typing-extensions >=4.6.0, !=4.7.0 +License-File: LICENSE +Summary: Core functionality for Pydantic validation and serialization +Home-Page: https://github.com/pydantic/pydantic-core +Author-email: Samuel Colvin +License: MIT +Requires-Python: >=3.8 +Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM +Project-URL: Homepage, https://github.com/pydantic/pydantic-core +Project-URL: Funding, https://github.com/sponsors/samuelcolvin +Project-URL: Source, https://github.com/pydantic/pydantic-core + +# pydantic-core + +[![CI](https://github.com/pydantic/pydantic-core/workflows/ci/badge.svg?event=push)](https://github.com/pydantic/pydantic-core/actions?query=event%3Apush+branch%3Amain+workflow%3Aci) +[![Coverage](https://codecov.io/gh/pydantic/pydantic-core/branch/main/graph/badge.svg)](https://codecov.io/gh/pydantic/pydantic-core) +[![pypi](https://img.shields.io/pypi/v/pydantic-core.svg)](https://pypi.python.org/pypi/pydantic-core) +[![versions](https://img.shields.io/pypi/pyversions/pydantic-core.svg)](https://github.com/pydantic/pydantic-core) +[![license](https://img.shields.io/github/license/pydantic/pydantic-core.svg)](https://github.com/pydantic/pydantic-core/blob/main/LICENSE) + +This package provides the core functionality for [pydantic](https://docs.pydantic.dev) validation and serialization. + +Pydantic-core is currently around 17x faster than pydantic V1. +See [`tests/benchmarks/`](./tests/benchmarks/) for details. + +## Example of direct usage + +_NOTE: You should not need to use pydantic-core directly; instead, use pydantic, which in turn uses pydantic-core._ + +```py +from pydantic_core import SchemaValidator, ValidationError + + +v = SchemaValidator( + { + 'type': 'typed-dict', + 'fields': { + 'name': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'str', + }, + }, + 'age': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'int', + 'ge': 18, + }, + }, + 'is_developer': { + 'type': 'typed-dict-field', + 'schema': { + 'type': 'default', + 'schema': {'type': 'bool'}, + 'default': True, + }, + }, + }, + } +) + +r1 = v.validate_python({'name': 'Samuel', 'age': 35}) +assert r1 == {'name': 'Samuel', 'age': 35, 'is_developer': True} + +# pydantic-core can also validate JSON directly +r2 = v.validate_json('{"name": "Samuel", "age": 35}') +assert r1 == r2 + +try: + v.validate_python({'name': 'Samuel', 'age': 11}) +except ValidationError as e: + print(e) + """ + 1 validation error for model + age + Input should be greater than or equal to 18 + [type=greater_than_equal, context={ge: 18}, input_value=11, input_type=int] + """ +``` + +## Getting Started + +You'll need rust stable [installed](https://rustup.rs/), or rust nightly if you want to generate accurate coverage. + +With rust and python 3.8+ installed, compiling pydantic-core should be possible with roughly the following: + +```bash +# clone this repo or your fork +git clone git@github.com:pydantic/pydantic-core.git +cd pydantic-core +# create a new virtual env +python3 -m venv env +source env/bin/activate +# install dependencies and install pydantic-core +make install +``` + +That should be it, the example shown above should now run. + +You might find it useful to look at [`python/pydantic_core/_pydantic_core.pyi`](./python/pydantic_core/_pydantic_core.pyi) and +[`python/pydantic_core/core_schema.py`](./python/pydantic_core/core_schema.py) for more information on the python API, +beyond that, [`tests/`](./tests) provide a large number of examples of usage. + +If you want to contribute to pydantic-core, you'll want to use some other make commands: +* `make build-dev` to build the package during development +* `make build-prod` to perform an optimised build for benchmarking +* `make test` to run the tests +* `make testcov` to run the tests and generate a coverage report +* `make lint` to run the linter +* `make format` to format python and rust code +* `make` to run `format build-dev lint test` + +## Profiling + +It's possible to profile the code using the [`flamegraph` utility from `flamegraph-rs`](https://github.com/flamegraph-rs/flamegraph). (Tested on Linux.) You can install this with `cargo install flamegraph`. + +Run `make build-profiling` to install a release build with debugging symbols included (needed for profiling). + +Once that is built, you can profile pytest benchmarks with (e.g.): + +```bash +flamegraph -- pytest tests/benchmarks/test_micro_benchmarks.py -k test_list_of_ints_core_py --benchmark-enable +``` +The `flamegraph` command will produce an interactive SVG at `flamegraph.svg`. + +## Releasing + +1. Bump package version locally. Do not just edit `Cargo.toml` on Github, you need both `Cargo.toml` and `Cargo.lock` to be updated. +2. Make a PR for the version bump and merge it. +3. Go to https://github.com/pydantic/pydantic-core/releases and click "Draft a new release" +4. In the "Choose a tag" dropdown enter the new tag `v` and select "Create new tag on publish" when the option appears. +5. Enter the release title in the form "v " +6. Click Generate release notes button +7. Click Publish release +8. Go to https://github.com/pydantic/pydantic-core/actions and ensure that all build for release are done successfully. +9. Go to https://pypi.org/project/pydantic-core/ and ensure that the latest release is published. +10. Done 🎉 + diff --git a/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/RECORD b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/RECORD new file mode 100644 index 0000000..df60d5a --- /dev/null +++ b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/RECORD @@ -0,0 +1,12 @@ +pydantic_core-2.20.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +pydantic_core-2.20.1.dist-info/METADATA,sha256=qAqRrEvYKJGzNlDiGv779DhZbe-ruBg6K_7Bcoj9oT4,6711 +pydantic_core-2.20.1.dist-info/RECORD,, +pydantic_core-2.20.1.dist-info/WHEEL,sha256=DzHgklH-N2Rm5CKeMVkz9xJT6rK_2P-i_Xf1Csdhcdo,95 +pydantic_core-2.20.1.dist-info/license_files/LICENSE,sha256=--f2FfGNE1wHAA5ahjJdsn9Cx3KWme8WasH3o_RYa_Q,1101 +pydantic_core/__init__.py,sha256=DTBLhkPl5ANdVSdJiItk1d9jtno2ZUTwyMw2zmnLx6Q,4336 +pydantic_core/__pycache__/__init__.cpython-311.pyc,, +pydantic_core/__pycache__/core_schema.cpython-311.pyc,, +pydantic_core/_pydantic_core.cp311-win_amd64.pyd,sha256=9bHbBwGd6jn7os4DfwofOR4WywcmT9_OMXE2R5tsNvQ,5021696 +pydantic_core/_pydantic_core.pyi,sha256=CYb_5evOcv9rR1ScvX_0f1snRV8SIVTI8I6cqEwo1h8,36062 +pydantic_core/core_schema.py,sha256=qNWrObkmOlxoSblaERlr5VISc5G1EcKesMcHY1h2j-w,142069 +pydantic_core/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/WHEEL b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/WHEEL new file mode 100644 index 0000000..5522df5 --- /dev/null +++ b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: maturin (1.6.0) +Root-Is-Purelib: false +Tag: cp311-none-win_amd64 diff --git a/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/license_files/LICENSE b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/license_files/LICENSE new file mode 100644 index 0000000..0716871 --- /dev/null +++ b/env/Lib/site-packages/pydantic_core-2.20.1.dist-info/license_files/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Samuel Colvin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/env/Lib/site-packages/pydantic_core/__init__.py b/env/Lib/site-packages/pydantic_core/__init__.py new file mode 100644 index 0000000..5b2655c --- /dev/null +++ b/env/Lib/site-packages/pydantic_core/__init__.py @@ -0,0 +1,139 @@ +from __future__ import annotations + +import sys as _sys +from typing import Any as _Any + +from ._pydantic_core import ( + ArgsKwargs, + MultiHostUrl, + PydanticCustomError, + PydanticKnownError, + PydanticOmit, + PydanticSerializationError, + PydanticSerializationUnexpectedValue, + PydanticUndefined, + PydanticUndefinedType, + PydanticUseDefault, + SchemaError, + SchemaSerializer, + SchemaValidator, + Some, + TzInfo, + Url, + ValidationError, + __version__, + from_json, + to_json, + to_jsonable_python, + validate_core_schema, +) +from .core_schema import CoreConfig, CoreSchema, CoreSchemaType, ErrorType + +if _sys.version_info < (3, 11): + from typing_extensions import NotRequired as _NotRequired +else: + from typing import NotRequired as _NotRequired + +if _sys.version_info < (3, 9): + from typing_extensions import TypedDict as _TypedDict +else: + from typing import TypedDict as _TypedDict + +__all__ = [ + '__version__', + 'CoreConfig', + 'CoreSchema', + 'CoreSchemaType', + 'SchemaValidator', + 'SchemaSerializer', + 'Some', + 'Url', + 'MultiHostUrl', + 'ArgsKwargs', + 'PydanticUndefined', + 'PydanticUndefinedType', + 'SchemaError', + 'ErrorDetails', + 'InitErrorDetails', + 'ValidationError', + 'PydanticCustomError', + 'PydanticKnownError', + 'PydanticOmit', + 'PydanticUseDefault', + 'PydanticSerializationError', + 'PydanticSerializationUnexpectedValue', + 'TzInfo', + 'to_json', + 'from_json', + 'to_jsonable_python', + 'validate_core_schema', +] + + +class ErrorDetails(_TypedDict): + type: str + """ + The type of error that occurred, this is an identifier designed for + programmatic use that will change rarely or never. + + `type` is unique for each error message, and can hence be used as an identifier to build custom error messages. + """ + loc: tuple[int | str, ...] + """Tuple of strings and ints identifying where in the schema the error occurred.""" + msg: str + """A human readable error message.""" + input: _Any + """The input data at this `loc` that caused the error.""" + ctx: _NotRequired[dict[str, _Any]] + """ + Values which are required to render the error message, and could hence be useful in rendering custom error messages. + Also useful for passing custom error data forward. + """ + + +class InitErrorDetails(_TypedDict): + type: str | PydanticCustomError + """The type of error that occurred, this should a "slug" identifier that changes rarely or never.""" + loc: _NotRequired[tuple[int | str, ...]] + """Tuple of strings and ints identifying where in the schema the error occurred.""" + input: _Any + """The input data at this `loc` that caused the error.""" + ctx: _NotRequired[dict[str, _Any]] + """ + Values which are required to render the error message, and could hence be useful in rendering custom error messages. + Also useful for passing custom error data forward. + """ + + +class ErrorTypeInfo(_TypedDict): + """ + Gives information about errors. + """ + + type: ErrorType + """The type of error that occurred, this should a "slug" identifier that changes rarely or never.""" + message_template_python: str + """String template to render a human readable error message from using context, when the input is Python.""" + example_message_python: str + """Example of a human readable error message, when the input is Python.""" + message_template_json: _NotRequired[str] + """String template to render a human readable error message from using context, when the input is JSON data.""" + example_message_json: _NotRequired[str] + """Example of a human readable error message, when the input is JSON data.""" + example_context: dict[str, _Any] | None + """Example of context values.""" + + +class MultiHostHost(_TypedDict): + """ + A host part of a multi-host URL. + """ + + username: str | None + """The username part of this host, or `None`.""" + password: str | None + """The password part of this host, or `None`.""" + host: str | None + """The host part of this host, or `None`.""" + port: int | None + """The port part of this host, or `None`.""" diff --git a/env/Lib/site-packages/pydantic_core/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/pydantic_core/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..71a43d3 Binary files /dev/null and b/env/Lib/site-packages/pydantic_core/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic_core/__pycache__/core_schema.cpython-311.pyc b/env/Lib/site-packages/pydantic_core/__pycache__/core_schema.cpython-311.pyc new file mode 100644 index 0000000..5062f41 Binary files /dev/null and b/env/Lib/site-packages/pydantic_core/__pycache__/core_schema.cpython-311.pyc differ diff --git a/env/Lib/site-packages/pydantic_core/_pydantic_core.cp311-win_amd64.pyd b/env/Lib/site-packages/pydantic_core/_pydantic_core.cp311-win_amd64.pyd new file mode 100644 index 0000000..a10c613 Binary files /dev/null and b/env/Lib/site-packages/pydantic_core/_pydantic_core.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/pydantic_core/_pydantic_core.pyi b/env/Lib/site-packages/pydantic_core/_pydantic_core.pyi new file mode 100644 index 0000000..05fe48e --- /dev/null +++ b/env/Lib/site-packages/pydantic_core/_pydantic_core.pyi @@ -0,0 +1,899 @@ +import datetime +from typing import Any, Callable, Generic, Literal, TypeVar, final + +from _typeshed import SupportsAllComparisons +from typing_extensions import LiteralString, Self, TypeAlias + +from pydantic_core import ErrorDetails, ErrorTypeInfo, InitErrorDetails, MultiHostHost +from pydantic_core.core_schema import CoreConfig, CoreSchema, ErrorType + +__all__ = [ + '__version__', + 'build_profile', + 'build_info', + '_recursion_limit', + 'ArgsKwargs', + 'SchemaValidator', + 'SchemaSerializer', + 'Url', + 'MultiHostUrl', + 'SchemaError', + 'ValidationError', + 'PydanticCustomError', + 'PydanticKnownError', + 'PydanticOmit', + 'PydanticUseDefault', + 'PydanticSerializationError', + 'PydanticSerializationUnexpectedValue', + 'PydanticUndefined', + 'PydanticUndefinedType', + 'Some', + 'to_json', + 'from_json', + 'to_jsonable_python', + 'list_all_errors', + 'TzInfo', + 'validate_core_schema', +] +__version__: str +build_profile: str +build_info: str +_recursion_limit: int + +_T = TypeVar('_T', default=Any, covariant=True) + +_StringInput: TypeAlias = 'dict[str, _StringInput]' + +@final +class Some(Generic[_T]): + """ + Similar to Rust's [`Option::Some`](https://doc.rust-lang.org/std/option/enum.Option.html) type, this + identifies a value as being present, and provides a way to access it. + + Generally used in a union with `None` to different between "some value which could be None" and no value. + """ + + __match_args__ = ('value',) + + @property + def value(self) -> _T: + """ + Returns the value wrapped by `Some`. + """ + @classmethod + def __class_getitem__(cls, item: Any, /) -> type[Self]: ... + +@final +class SchemaValidator: + """ + `SchemaValidator` is the Python wrapper for `pydantic-core`'s Rust validation logic, internally it owns one + `CombinedValidator` which may in turn own more `CombinedValidator`s which make up the full schema validator. + """ + + def __new__(cls, schema: CoreSchema, config: CoreConfig | None = None) -> Self: + """ + Create a new SchemaValidator. + + Arguments: + schema: The [`CoreSchema`][pydantic_core.core_schema.CoreSchema] to use for validation. + config: Optionally a [`CoreConfig`][pydantic_core.core_schema.CoreConfig] to configure validation. + """ + @property + def title(self) -> str: + """ + The title of the schema, as used in the heading of [`ValidationError.__str__()`][pydantic_core.ValidationError]. + """ + def validate_python( + self, + input: Any, + *, + strict: bool | None = None, + from_attributes: bool | None = None, + context: Any | None = None, + self_instance: Any | None = None, + ) -> Any: + """ + Validate a Python object against the schema and return the validated object. + + Arguments: + input: The Python object to validate. + strict: Whether to validate the object in strict mode. + If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used. + from_attributes: Whether to validate objects as inputs to models by extracting attributes. + If `None`, the value of [`CoreConfig.from_attributes`][pydantic_core.core_schema.CoreConfig] is used. + context: The context to use for validation, this is passed to functional validators as + [`info.context`][pydantic_core.core_schema.ValidationInfo.context]. + self_instance: An instance of a model set attributes on from validation, this is used when running + validation from the `__init__` method of a model. + + Raises: + ValidationError: If validation fails. + Exception: Other error types maybe raised if internal errors occur. + + Returns: + The validated object. + """ + def isinstance_python( + self, + input: Any, + *, + strict: bool | None = None, + from_attributes: bool | None = None, + context: Any | None = None, + self_instance: Any | None = None, + ) -> bool: + """ + Similar to [`validate_python()`][pydantic_core.SchemaValidator.validate_python] but returns a boolean. + + Arguments match `validate_python()`. This method will not raise `ValidationError`s but will raise internal + errors. + + Returns: + `True` if validation succeeds, `False` if validation fails. + """ + def validate_json( + self, + input: str | bytes | bytearray, + *, + strict: bool | None = None, + context: Any | None = None, + self_instance: Any | None = None, + ) -> Any: + """ + Validate JSON data directly against the schema and return the validated Python object. + + This method should be significantly faster than `validate_python(json.loads(json_data))` as it avoids the + need to create intermediate Python objects + + It also handles constructing the correct Python type even in strict mode, where + `validate_python(json.loads(json_data))` would fail validation. + + Arguments: + input: The JSON data to validate. + strict: Whether to validate the object in strict mode. + If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used. + context: The context to use for validation, this is passed to functional validators as + [`info.context`][pydantic_core.core_schema.ValidationInfo.context]. + self_instance: An instance of a model set attributes on from validation. + + Raises: + ValidationError: If validation fails or if the JSON data is invalid. + Exception: Other error types maybe raised if internal errors occur. + + Returns: + The validated Python object. + """ + def validate_strings(self, input: _StringInput, *, strict: bool | None = None, context: Any | None = None) -> Any: + """ + Validate a string against the schema and return the validated Python object. + + This is similar to `validate_json` but applies to scenarios where the input will be a string but not + JSON data, e.g. URL fragments, query parameters, etc. + + Arguments: + input: The input as a string, or bytes/bytearray if `strict=False`. + strict: Whether to validate the object in strict mode. + If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used. + context: The context to use for validation, this is passed to functional validators as + [`info.context`][pydantic_core.core_schema.ValidationInfo.context]. + + Raises: + ValidationError: If validation fails or if the JSON data is invalid. + Exception: Other error types maybe raised if internal errors occur. + + Returns: + The validated Python object. + """ + def validate_assignment( + self, + obj: Any, + field_name: str, + field_value: Any, + *, + strict: bool | None = None, + from_attributes: bool | None = None, + context: Any | None = None, + ) -> dict[str, Any] | tuple[dict[str, Any], dict[str, Any] | None, set[str]]: + """ + Validate an assignment to a field on a model. + + Arguments: + obj: The model instance being assigned to. + field_name: The name of the field to validate assignment for. + field_value: The value to assign to the field. + strict: Whether to validate the object in strict mode. + If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used. + from_attributes: Whether to validate objects as inputs to models by extracting attributes. + If `None`, the value of [`CoreConfig.from_attributes`][pydantic_core.core_schema.CoreConfig] is used. + context: The context to use for validation, this is passed to functional validators as + [`info.context`][pydantic_core.core_schema.ValidationInfo.context]. + + Raises: + ValidationError: If validation fails. + Exception: Other error types maybe raised if internal errors occur. + + Returns: + Either the model dict or a tuple of `(model_data, model_extra, fields_set)` + """ + def get_default_value(self, *, strict: bool | None = None, context: Any = None) -> Some | None: + """ + Get the default value for the schema, including running default value validation. + + Arguments: + strict: Whether to validate the default value in strict mode. + If `None`, the value of [`CoreConfig.strict`][pydantic_core.core_schema.CoreConfig] is used. + context: The context to use for validation, this is passed to functional validators as + [`info.context`][pydantic_core.core_schema.ValidationInfo.context]. + + Raises: + ValidationError: If validation fails. + Exception: Other error types maybe raised if internal errors occur. + + Returns: + `None` if the schema has no default value, otherwise a [`Some`][pydantic_core.Some] containing the default. + """ + +_IncEx: TypeAlias = set[int] | set[str] | dict[int, _IncEx] | dict[str, _IncEx] | None + +@final +class SchemaSerializer: + """ + `SchemaSerializer` is the Python wrapper for `pydantic-core`'s Rust serialization logic, internally it owns one + `CombinedSerializer` which may in turn own more `CombinedSerializer`s which make up the full schema serializer. + """ + + def __new__(cls, schema: CoreSchema, config: CoreConfig | None = None) -> Self: + """ + Create a new SchemaSerializer. + + Arguments: + schema: The [`CoreSchema`][pydantic_core.core_schema.CoreSchema] to use for serialization. + config: Optionally a [`CoreConfig`][pydantic_core.core_schema.CoreConfig] to to configure serialization. + """ + def to_python( + self, + value: Any, + *, + mode: str | None = None, + include: _IncEx = None, + exclude: _IncEx = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool | Literal['none', 'warn', 'error'] = True, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + context: Any | None = None, + ) -> Any: + """ + Serialize/marshal a Python object to a Python object including transforming and filtering data. + + Arguments: + value: The Python object to serialize. + mode: The serialization mode to use, either `'python'` or `'json'`, defaults to `'python'`. In JSON mode, + all values are converted to JSON compatible types, e.g. `None`, `int`, `float`, `str`, `list`, `dict`. + include: A set of fields to include, if `None` all fields are included. + exclude: A set of fields to exclude, if `None` no fields are excluded. + by_alias: Whether to use the alias names of fields. + exclude_unset: Whether to exclude fields that are not set, + e.g. are not included in `__pydantic_fields_set__`. + exclude_defaults: Whether to exclude fields that are equal to their default value. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: Whether to enable serialization and validation round-trip support. + warnings: How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + fallback: A function to call when an unknown value is encountered, + if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + context: The context to use for serialization, this is passed to functional serializers as + [`info.context`][pydantic_core.core_schema.SerializationInfo.context]. + + Raises: + PydanticSerializationError: If serialization fails and no `fallback` function is provided. + + Returns: + The serialized Python object. + """ + def to_json( + self, + value: Any, + *, + indent: int | None = None, + include: _IncEx = None, + exclude: _IncEx = None, + by_alias: bool = True, + exclude_unset: bool = False, + exclude_defaults: bool = False, + exclude_none: bool = False, + round_trip: bool = False, + warnings: bool | Literal['none', 'warn', 'error'] = True, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + context: Any | None = None, + ) -> bytes: + """ + Serialize a Python object to JSON including transforming and filtering data. + + Arguments: + value: The Python object to serialize. + indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided. + include: A set of fields to include, if `None` all fields are included. + exclude: A set of fields to exclude, if `None` no fields are excluded. + by_alias: Whether to use the alias names of fields. + exclude_unset: Whether to exclude fields that are not set, + e.g. are not included in `__pydantic_fields_set__`. + exclude_defaults: Whether to exclude fields that are equal to their default value. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: Whether to enable serialization and validation round-trip support. + warnings: How to handle invalid fields. False/"none" ignores them, True/"warn" logs errors, + "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError]. + fallback: A function to call when an unknown value is encountered, + if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + context: The context to use for serialization, this is passed to functional serializers as + [`info.context`][pydantic_core.core_schema.SerializationInfo.context]. + + Raises: + PydanticSerializationError: If serialization fails and no `fallback` function is provided. + + Returns: + JSON bytes. + """ + +def to_json( + value: Any, + *, + indent: int | None = None, + include: _IncEx = None, + exclude: _IncEx = None, + by_alias: bool = True, + exclude_none: bool = False, + round_trip: bool = False, + timedelta_mode: Literal['iso8601', 'float'] = 'iso8601', + bytes_mode: Literal['utf8', 'base64'] = 'utf8', + inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants', + serialize_unknown: bool = False, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + context: Any | None = None, +) -> bytes: + """ + Serialize a Python object to JSON including transforming and filtering data. + + This is effectively a standalone version of [`SchemaSerializer.to_json`][pydantic_core.SchemaSerializer.to_json]. + + Arguments: + value: The Python object to serialize. + indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided. + include: A set of fields to include, if `None` all fields are included. + exclude: A set of fields to exclude, if `None` no fields are excluded. + by_alias: Whether to use the alias names of fields. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: Whether to enable serialization and validation round-trip support. + timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`. + bytes_mode: How to serialize `bytes` objects, either `'utf8'` or `'base64'`. + inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`. + serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails + `""` will be used. + fallback: A function to call when an unknown value is encountered, + if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + context: The context to use for serialization, this is passed to functional serializers as + [`info.context`][pydantic_core.core_schema.SerializationInfo.context]. + + Raises: + PydanticSerializationError: If serialization fails and no `fallback` function is provided. + + Returns: + JSON bytes. + """ + +def from_json( + data: str | bytes | bytearray, + *, + allow_inf_nan: bool = True, + cache_strings: bool | Literal['all', 'keys', 'none'] = True, + allow_partial: bool = False, +) -> Any: + """ + Deserialize JSON data to a Python object. + + This is effectively a faster version of `json.loads()`, with some extra functionality. + + Arguments: + data: The JSON data to deserialize. + allow_inf_nan: Whether to allow `Infinity`, `-Infinity` and `NaN` values as `json.loads()` does by default. + cache_strings: Whether to cache strings to avoid constructing new Python objects, + this should have a significant impact on performance while increasing memory usage slightly, + `all/True` means cache all strings, `keys` means cache only dict keys, `none/False` means no caching. + allow_partial: Whether to allow partial deserialization, if `True` JSON data is returned if the end of the + input is reached before the full object is deserialized, e.g. `["aa", "bb", "c` would return `['aa', 'bb']`. + + Raises: + ValueError: If deserialization fails. + + Returns: + The deserialized Python object. + """ + +def to_jsonable_python( + value: Any, + *, + include: _IncEx = None, + exclude: _IncEx = None, + by_alias: bool = True, + exclude_none: bool = False, + round_trip: bool = False, + timedelta_mode: Literal['iso8601', 'float'] = 'iso8601', + bytes_mode: Literal['utf8', 'base64'] = 'utf8', + inf_nan_mode: Literal['null', 'constants', 'strings'] = 'constants', + serialize_unknown: bool = False, + fallback: Callable[[Any], Any] | None = None, + serialize_as_any: bool = False, + context: Any | None = None, +) -> Any: + """ + Serialize/marshal a Python object to a JSON-serializable Python object including transforming and filtering data. + + This is effectively a standalone version of + [`SchemaSerializer.to_python(mode='json')`][pydantic_core.SchemaSerializer.to_python]. + + Args: + value: The Python object to serialize. + include: A set of fields to include, if `None` all fields are included. + exclude: A set of fields to exclude, if `None` no fields are excluded. + by_alias: Whether to use the alias names of fields. + exclude_none: Whether to exclude fields that have a value of `None`. + round_trip: Whether to enable serialization and validation round-trip support. + timedelta_mode: How to serialize `timedelta` objects, either `'iso8601'` or `'float'`. + bytes_mode: How to serialize `bytes` objects, either `'utf8'` or `'base64'`. + inf_nan_mode: How to serialize `Infinity`, `-Infinity` and `NaN` values, either `'null'`, `'constants'`, or `'strings'`. + serialize_unknown: Attempt to serialize unknown types, `str(value)` will be used, if that fails + `""` will be used. + fallback: A function to call when an unknown value is encountered, + if `None` a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised. + serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. + context: The context to use for serialization, this is passed to functional serializers as + [`info.context`][pydantic_core.core_schema.SerializationInfo.context]. + + Raises: + PydanticSerializationError: If serialization fails and no `fallback` function is provided. + + Returns: + The serialized Python object. + """ + +class Url(SupportsAllComparisons): + """ + A URL type, internal logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed + by Mozilla. + """ + + def __new__(cls, url: str) -> Self: + """ + Create a new `Url` instance. + + Args: + url: String representation of a URL. + + Returns: + A new `Url` instance. + + Raises: + ValidationError: If the URL is invalid. + """ + @property + def scheme(self) -> str: + """ + The scheme part of the URL. + + e.g. `https` in `https://user:pass@host:port/path?query#fragment` + """ + @property + def username(self) -> str | None: + """ + The username part of the URL, or `None`. + + e.g. `user` in `https://user:pass@host:port/path?query#fragment` + """ + @property + def password(self) -> str | None: + """ + The password part of the URL, or `None`. + + e.g. `pass` in `https://user:pass@host:port/path?query#fragment` + """ + @property + def host(self) -> str | None: + """ + The host part of the URL, or `None`. + + If the URL must be punycode encoded, this is the encoded host, e.g if the input URL is `https://£££.com`, + `host` will be `xn--9aaa.com` + """ + def unicode_host(self) -> str | None: + """ + The host part of the URL as a unicode string, or `None`. + + e.g. `host` in `https://user:pass@host:port/path?query#fragment` + + If the URL must be punycode encoded, this is the decoded host, e.g if the input URL is `https://£££.com`, + `unicode_host()` will be `£££.com` + """ + @property + def port(self) -> int | None: + """ + The port part of the URL, or `None`. + + e.g. `port` in `https://user:pass@host:port/path?query#fragment` + """ + @property + def path(self) -> str | None: + """ + The path part of the URL, or `None`. + + e.g. `/path` in `https://user:pass@host:port/path?query#fragment` + """ + @property + def query(self) -> str | None: + """ + The query part of the URL, or `None`. + + e.g. `query` in `https://user:pass@host:port/path?query#fragment` + """ + def query_params(self) -> list[tuple[str, str]]: + """ + The query part of the URL as a list of key-value pairs. + + e.g. `[('foo', 'bar')]` in `https://user:pass@host:port/path?foo=bar#fragment` + """ + @property + def fragment(self) -> str | None: + """ + The fragment part of the URL, or `None`. + + e.g. `fragment` in `https://user:pass@host:port/path?query#fragment` + """ + def unicode_string(self) -> str: + """ + The URL as a unicode string, unlike `__str__()` this will not punycode encode the host. + + If the URL must be punycode encoded, this is the decoded string, e.g if the input URL is `https://£££.com`, + `unicode_string()` will be `https://£££.com` + """ + def __repr__(self) -> str: ... + def __str__(self) -> str: + """ + The URL as a string, this will punycode encode the host if required. + """ + def __deepcopy__(self, memo: dict) -> str: ... + @classmethod + def build( + cls, + *, + scheme: str, + username: str | None = None, + password: str | None = None, + host: str, + port: int | None = None, + path: str | None = None, + query: str | None = None, + fragment: str | None = None, + ) -> Self: + """ + Build a new `Url` instance from its component parts. + + Args: + scheme: The scheme part of the URL. + username: The username part of the URL, or omit for no username. + password: The password part of the URL, or omit for no password. + host: The host part of the URL. + port: The port part of the URL, or omit for no port. + path: The path part of the URL, or omit for no path. + query: The query part of the URL, or omit for no query. + fragment: The fragment part of the URL, or omit for no fragment. + + Returns: + An instance of URL + """ + +class MultiHostUrl(SupportsAllComparisons): + """ + A URL type with support for multiple hosts, as used by some databases for DSNs, e.g. `https://foo.com,bar.com/path`. + + Internal URL logic uses the [url rust crate](https://docs.rs/url/latest/url/) originally developed + by Mozilla. + """ + + def __new__(cls, url: str) -> Self: + """ + Create a new `MultiHostUrl` instance. + + Args: + url: String representation of a URL. + + Returns: + A new `MultiHostUrl` instance. + + Raises: + ValidationError: If the URL is invalid. + """ + @property + def scheme(self) -> str: + """ + The scheme part of the URL. + + e.g. `https` in `https://foo.com,bar.com/path?query#fragment` + """ + @property + def path(self) -> str | None: + """ + The path part of the URL, or `None`. + + e.g. `/path` in `https://foo.com,bar.com/path?query#fragment` + """ + @property + def query(self) -> str | None: + """ + The query part of the URL, or `None`. + + e.g. `query` in `https://foo.com,bar.com/path?query#fragment` + """ + def query_params(self) -> list[tuple[str, str]]: + """ + The query part of the URL as a list of key-value pairs. + + e.g. `[('foo', 'bar')]` in `https://foo.com,bar.com/path?query#fragment` + """ + @property + def fragment(self) -> str | None: + """ + The fragment part of the URL, or `None`. + + e.g. `fragment` in `https://foo.com,bar.com/path?query#fragment` + """ + def hosts(self) -> list[MultiHostHost]: + ''' + + The hosts of the `MultiHostUrl` as [`MultiHostHost`][pydantic_core.MultiHostHost] typed dicts. + + ```py + from pydantic_core import MultiHostUrl + + mhu = MultiHostUrl('https://foo.com:123,foo:bar@bar.com/path') + print(mhu.hosts()) + """ + [ + {'username': None, 'password': None, 'host': 'foo.com', 'port': 123}, + {'username': 'foo', 'password': 'bar', 'host': 'bar.com', 'port': 443} + ] + ``` + Returns: + A list of dicts, each representing a host. + ''' + def unicode_string(self) -> str: + """ + The URL as a unicode string, unlike `__str__()` this will not punycode encode the hosts. + """ + def __repr__(self) -> str: ... + def __str__(self) -> str: + """ + The URL as a string, this will punycode encode the hosts if required. + """ + def __deepcopy__(self, memo: dict) -> Self: ... + @classmethod + def build( + cls, + *, + scheme: str, + hosts: list[MultiHostHost] | None = None, + username: str | None = None, + password: str | None = None, + host: str | None = None, + port: int | None = None, + path: str | None = None, + query: str | None = None, + fragment: str | None = None, + ) -> Self: + """ + Build a new `MultiHostUrl` instance from its component parts. + + This method takes either `hosts` - a list of `MultiHostHost` typed dicts, or the individual components + `username`, `password`, `host` and `port`. + + Args: + scheme: The scheme part of the URL. + hosts: Multiple hosts to build the URL from. + username: The username part of the URL. + password: The password part of the URL. + host: The host part of the URL. + port: The port part of the URL. + path: The path part of the URL. + query: The query part of the URL, or omit for no query. + fragment: The fragment part of the URL, or omit for no fragment. + + Returns: + An instance of `MultiHostUrl` + """ + +@final +class SchemaError(Exception): + """ + Information about errors that occur while building a [`SchemaValidator`][pydantic_core.SchemaValidator] + or [`SchemaSerializer`][pydantic_core.SchemaSerializer]. + """ + + def error_count(self) -> int: + """ + Returns: + The number of errors in the schema. + """ + def errors(self) -> list[ErrorDetails]: + """ + Returns: + A list of [`ErrorDetails`][pydantic_core.ErrorDetails] for each error in the schema. + """ + +@final +class ValidationError(ValueError): + """ + `ValidationError` is the exception raised by `pydantic-core` when validation fails, it contains a list of errors + which detail why validation failed. + """ + + @staticmethod + def from_exception_data( + title: str, + line_errors: list[InitErrorDetails], + input_type: Literal['python', 'json'] = 'python', + hide_input: bool = False, + ) -> ValidationError: + """ + Python constructor for a Validation Error. + + The API for constructing validation errors will probably change in the future, + hence the static method rather than `__init__`. + + Arguments: + title: The title of the error, as used in the heading of `str(validation_error)` + line_errors: A list of [`InitErrorDetails`][pydantic_core.InitErrorDetails] which contain information + about errors that occurred during validation. + input_type: Whether the error is for a Python object or JSON. + hide_input: Whether to hide the input value in the error message. + """ + @property + def title(self) -> str: + """ + The title of the error, as used in the heading of `str(validation_error)`. + """ + def error_count(self) -> int: + """ + Returns: + The number of errors in the validation error. + """ + def errors( + self, *, include_url: bool = True, include_context: bool = True, include_input: bool = True + ) -> list[ErrorDetails]: + """ + Details about each error in the validation error. + + Args: + include_url: Whether to include a URL to documentation on the error each error. + include_context: Whether to include the context of each error. + include_input: Whether to include the input value of each error. + + Returns: + A list of [`ErrorDetails`][pydantic_core.ErrorDetails] for each error in the validation error. + """ + def json( + self, + *, + indent: int | None = None, + include_url: bool = True, + include_context: bool = True, + include_input: bool = True, + ) -> str: + """ + Same as [`errors()`][pydantic_core.ValidationError.errors] but returns a JSON string. + + Args: + indent: The number of spaces to indent the JSON by, or `None` for no indentation - compact JSON. + include_url: Whether to include a URL to documentation on the error each error. + include_context: Whether to include the context of each error. + include_input: Whether to include the input value of each error. + + Returns: + a JSON string. + """ + + def __repr__(self) -> str: + """ + A string representation of the validation error. + + Whether or not documentation URLs are included in the repr is controlled by the + environment variable `PYDANTIC_ERRORS_INCLUDE_URL` being set to `1` or + `true`; by default, URLs are shown. + + Due to implementation details, this environment variable can only be set once, + before the first validation error is created. + """ + +@final +class PydanticCustomError(ValueError): + def __new__( + cls, error_type: LiteralString, message_template: LiteralString, context: dict[str, Any] | None = None + ) -> Self: ... + @property + def context(self) -> dict[str, Any] | None: ... + @property + def type(self) -> str: ... + @property + def message_template(self) -> str: ... + def message(self) -> str: ... + +@final +class PydanticKnownError(ValueError): + def __new__(cls, error_type: ErrorType, context: dict[str, Any] | None = None) -> Self: ... + @property + def context(self) -> dict[str, Any] | None: ... + @property + def type(self) -> ErrorType: ... + @property + def message_template(self) -> str: ... + def message(self) -> str: ... + +@final +class PydanticOmit(Exception): + def __new__(cls) -> Self: ... + +@final +class PydanticUseDefault(Exception): + def __new__(cls) -> Self: ... + +@final +class PydanticSerializationError(ValueError): + def __new__(cls, message: str) -> Self: ... + +@final +class PydanticSerializationUnexpectedValue(ValueError): + def __new__(cls, message: str | None = None) -> Self: ... + +@final +class ArgsKwargs: + def __new__(cls, args: tuple[Any, ...], kwargs: dict[str, Any] | None = None) -> Self: ... + @property + def args(self) -> tuple[Any, ...]: ... + @property + def kwargs(self) -> dict[str, Any] | None: ... + +@final +class PydanticUndefinedType: + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any) -> Self: ... + +PydanticUndefined: PydanticUndefinedType + +def list_all_errors() -> list[ErrorTypeInfo]: + """ + Get information about all built-in errors. + + Returns: + A list of `ErrorTypeInfo` typed dicts. + """ +@final +class TzInfo(datetime.tzinfo): + def tzname(self, _dt: datetime.datetime | None) -> str | None: ... + def utcoffset(self, _dt: datetime.datetime | None) -> datetime.timedelta: ... + def dst(self, _dt: datetime.datetime | None) -> datetime.timedelta: ... + def fromutc(self, dt: datetime.datetime) -> datetime.datetime: ... + def __deepcopy__(self, _memo: dict[Any, Any]) -> TzInfo: ... + +def validate_core_schema(schema: CoreSchema, *, strict: bool | None = None) -> CoreSchema: + """Validate a CoreSchema + This currently uses lax mode for validation (i.e. will coerce strings to dates and such) + but may use strict mode in the future. + We may also remove this function altogether, do not rely on it being present if you are + using pydantic-core directly. + """ diff --git a/env/Lib/site-packages/pydantic_core/core_schema.py b/env/Lib/site-packages/pydantic_core/core_schema.py new file mode 100644 index 0000000..5405d96 --- /dev/null +++ b/env/Lib/site-packages/pydantic_core/core_schema.py @@ -0,0 +1,4061 @@ +""" +This module contains definitions to build schemas which `pydantic_core` can +validate and serialize. +""" + +from __future__ import annotations as _annotations + +import sys +import warnings +from collections.abc import Mapping +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from typing import TYPE_CHECKING, Any, Callable, Dict, Hashable, List, Pattern, Set, Tuple, Type, Union + +from typing_extensions import deprecated + +if sys.version_info < (3, 12): + from typing_extensions import TypedDict +else: + from typing import TypedDict + +if sys.version_info < (3, 11): + from typing_extensions import Protocol, Required, TypeAlias +else: + from typing import Protocol, Required, TypeAlias + +if sys.version_info < (3, 9): + from typing_extensions import Literal +else: + from typing import Literal + +if TYPE_CHECKING: + from pydantic_core import PydanticUndefined +else: + # The initial build of pydantic_core requires PydanticUndefined to generate + # the core schema; so we need to conditionally skip it. mypy doesn't like + # this at all, hence the TYPE_CHECKING branch above. + try: + from pydantic_core import PydanticUndefined + except ImportError: + PydanticUndefined = object() + + +ExtraBehavior = Literal['allow', 'forbid', 'ignore'] + + +class CoreConfig(TypedDict, total=False): + """ + Base class for schema configuration options. + + Attributes: + title: The name of the configuration. + strict: Whether the configuration should strictly adhere to specified rules. + extra_fields_behavior: The behavior for handling extra fields. + typed_dict_total: Whether the TypedDict should be considered total. Default is `True`. + from_attributes: Whether to use attributes for models, dataclasses, and tagged union keys. + loc_by_alias: Whether to use the used alias (or first alias for "field required" errors) instead of + `field_names` to construct error `loc`s. Default is `True`. + revalidate_instances: Whether instances of models and dataclasses should re-validate. Default is 'never'. + validate_default: Whether to validate default values during validation. Default is `False`. + populate_by_name: Whether an aliased field may be populated by its name as given by the model attribute, + as well as the alias. (Replaces 'allow_population_by_field_name' in Pydantic v1.) Default is `False`. + str_max_length: The maximum length for string fields. + str_min_length: The minimum length for string fields. + str_strip_whitespace: Whether to strip whitespace from string fields. + str_to_lower: Whether to convert string fields to lowercase. + str_to_upper: Whether to convert string fields to uppercase. + allow_inf_nan: Whether to allow infinity and NaN values for float fields. Default is `True`. + ser_json_timedelta: The serialization option for `timedelta` values. Default is 'iso8601'. + ser_json_bytes: The serialization option for `bytes` values. Default is 'utf8'. + ser_json_inf_nan: The serialization option for infinity and NaN values + in float fields. Default is 'null'. + hide_input_in_errors: Whether to hide input data from `ValidationError` representation. + validation_error_cause: Whether to add user-python excs to the __cause__ of a ValidationError. + Requires exceptiongroup backport pre Python 3.11. + coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). + regex_engine: The regex engine to use for regex pattern validation. Default is 'rust-regex'. See `StringSchema`. + cache_strings: Whether to cache strings. Default is `True`, `True` or `'all'` is required to cache strings + during general validation since validators don't know if they're in a key or a value. + """ + + title: str + strict: bool + # settings related to typed dicts, model fields, dataclass fields + extra_fields_behavior: ExtraBehavior + typed_dict_total: bool # default: True + # used for models, dataclasses, and tagged union keys + from_attributes: bool + # whether to use the used alias (or first alias for "field required" errors) instead of field_names + # to construct error `loc`s, default True + loc_by_alias: bool + # whether instances of models and dataclasses (including subclass instances) should re-validate, default 'never' + revalidate_instances: Literal['always', 'never', 'subclass-instances'] + # whether to validate default values during validation, default False + validate_default: bool + # used on typed-dicts and arguments + populate_by_name: bool # replaces `allow_population_by_field_name` in pydantic v1 + # fields related to string fields only + str_max_length: int + str_min_length: int + str_strip_whitespace: bool + str_to_lower: bool + str_to_upper: bool + # fields related to float fields only + allow_inf_nan: bool # default: True + # the config options are used to customise serialization to JSON + ser_json_timedelta: Literal['iso8601', 'float'] # default: 'iso8601' + ser_json_bytes: Literal['utf8', 'base64', 'hex'] # default: 'utf8' + ser_json_inf_nan: Literal['null', 'constants', 'strings'] # default: 'null' + # used to hide input data from ValidationError repr + hide_input_in_errors: bool + validation_error_cause: bool # default: False + coerce_numbers_to_str: bool # default: False + regex_engine: Literal['rust-regex', 'python-re'] # default: 'rust-regex' + cache_strings: Union[bool, Literal['all', 'keys', 'none']] # default: 'True' + + +IncExCall: TypeAlias = 'set[int | str] | dict[int | str, IncExCall] | None' + + +class SerializationInfo(Protocol): + @property + def include(self) -> IncExCall: ... + + @property + def exclude(self) -> IncExCall: ... + + @property + def context(self) -> Any | None: + """Current serialization context.""" + + @property + def mode(self) -> str: ... + + @property + def by_alias(self) -> bool: ... + + @property + def exclude_unset(self) -> bool: ... + + @property + def exclude_defaults(self) -> bool: ... + + @property + def exclude_none(self) -> bool: ... + + @property + def serialize_as_any(self) -> bool: ... + + def round_trip(self) -> bool: ... + + def mode_is_json(self) -> bool: ... + + def __str__(self) -> str: ... + + def __repr__(self) -> str: ... + + +class FieldSerializationInfo(SerializationInfo, Protocol): + @property + def field_name(self) -> str: ... + + +class ValidationInfo(Protocol): + """ + Argument passed to validation functions. + """ + + @property + def context(self) -> Any | None: + """Current validation context.""" + ... + + @property + def config(self) -> CoreConfig | None: + """The CoreConfig that applies to this validation.""" + ... + + @property + def mode(self) -> Literal['python', 'json']: + """The type of input data we are currently validating""" + ... + + @property + def data(self) -> Dict[str, Any]: + """The data being validated for this model.""" + ... + + @property + def field_name(self) -> str | None: + """ + The name of the current field being validated if this validator is + attached to a model field. + """ + ... + + +ExpectedSerializationTypes = Literal[ + 'none', + 'int', + 'bool', + 'float', + 'str', + 'bytes', + 'bytearray', + 'list', + 'tuple', + 'set', + 'frozenset', + 'generator', + 'dict', + 'datetime', + 'date', + 'time', + 'timedelta', + 'url', + 'multi-host-url', + 'json', + 'uuid', +] + + +class SimpleSerSchema(TypedDict, total=False): + type: Required[ExpectedSerializationTypes] + + +def simple_ser_schema(type: ExpectedSerializationTypes) -> SimpleSerSchema: + """ + Returns a schema for serialization with a custom type. + + Args: + type: The type to use for serialization + """ + return SimpleSerSchema(type=type) + + +# (input_value: Any, /) -> Any +GeneralPlainNoInfoSerializerFunction = Callable[[Any], Any] +# (input_value: Any, info: FieldSerializationInfo, /) -> Any +GeneralPlainInfoSerializerFunction = Callable[[Any, SerializationInfo], Any] +# (model: Any, input_value: Any, /) -> Any +FieldPlainNoInfoSerializerFunction = Callable[[Any, Any], Any] +# (model: Any, input_value: Any, info: FieldSerializationInfo, /) -> Any +FieldPlainInfoSerializerFunction = Callable[[Any, Any, FieldSerializationInfo], Any] +SerializerFunction = Union[ + GeneralPlainNoInfoSerializerFunction, + GeneralPlainInfoSerializerFunction, + FieldPlainNoInfoSerializerFunction, + FieldPlainInfoSerializerFunction, +] + +WhenUsed = Literal['always', 'unless-none', 'json', 'json-unless-none'] +""" +Values have the following meanings: + +* `'always'` means always use +* `'unless-none'` means use unless the value is `None` +* `'json'` means use when serializing to JSON +* `'json-unless-none'` means use when serializing to JSON and the value is not `None` +""" + + +class PlainSerializerFunctionSerSchema(TypedDict, total=False): + type: Required[Literal['function-plain']] + function: Required[SerializerFunction] + is_field_serializer: bool # default False + info_arg: bool # default False + return_schema: CoreSchema # if omitted, AnySchema is used + when_used: WhenUsed # default: 'always' + + +def plain_serializer_function_ser_schema( + function: SerializerFunction, + *, + is_field_serializer: bool | None = None, + info_arg: bool | None = None, + return_schema: CoreSchema | None = None, + when_used: WhenUsed = 'always', +) -> PlainSerializerFunctionSerSchema: + """ + Returns a schema for serialization with a function, can be either a "general" or "field" function. + + Args: + function: The function to use for serialization + is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument, + and `info` includes `field_name` + info_arg: Whether the function takes an `info` argument + return_schema: Schema to use for serializing return value + when_used: When the function should be called + """ + if when_used == 'always': + # just to avoid extra elements in schema, and to use the actual default defined in rust + when_used = None # type: ignore + return _dict_not_none( + type='function-plain', + function=function, + is_field_serializer=is_field_serializer, + info_arg=info_arg, + return_schema=return_schema, + when_used=when_used, + ) + + +class SerializerFunctionWrapHandler(Protocol): # pragma: no cover + def __call__(self, input_value: Any, index_key: int | str | None = None, /) -> Any: ... + + +# (input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any +GeneralWrapNoInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler], Any] +# (input_value: Any, serializer: SerializerFunctionWrapHandler, info: SerializationInfo, /) -> Any +GeneralWrapInfoSerializerFunction = Callable[[Any, SerializerFunctionWrapHandler, SerializationInfo], Any] +# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, /) -> Any +FieldWrapNoInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler], Any] +# (model: Any, input_value: Any, serializer: SerializerFunctionWrapHandler, info: FieldSerializationInfo, /) -> Any +FieldWrapInfoSerializerFunction = Callable[[Any, Any, SerializerFunctionWrapHandler, FieldSerializationInfo], Any] +WrapSerializerFunction = Union[ + GeneralWrapNoInfoSerializerFunction, + GeneralWrapInfoSerializerFunction, + FieldWrapNoInfoSerializerFunction, + FieldWrapInfoSerializerFunction, +] + + +class WrapSerializerFunctionSerSchema(TypedDict, total=False): + type: Required[Literal['function-wrap']] + function: Required[WrapSerializerFunction] + is_field_serializer: bool # default False + info_arg: bool # default False + schema: CoreSchema # if omitted, the schema on which this serializer is defined is used + return_schema: CoreSchema # if omitted, AnySchema is used + when_used: WhenUsed # default: 'always' + + +def wrap_serializer_function_ser_schema( + function: WrapSerializerFunction, + *, + is_field_serializer: bool | None = None, + info_arg: bool | None = None, + schema: CoreSchema | None = None, + return_schema: CoreSchema | None = None, + when_used: WhenUsed = 'always', +) -> WrapSerializerFunctionSerSchema: + """ + Returns a schema for serialization with a wrap function, can be either a "general" or "field" function. + + Args: + function: The function to use for serialization + is_field_serializer: Whether the serializer is for a field, e.g. takes `model` as the first argument, + and `info` includes `field_name` + info_arg: Whether the function takes an `info` argument + schema: The schema to use for the inner serialization + return_schema: Schema to use for serializing return value + when_used: When the function should be called + """ + if when_used == 'always': + # just to avoid extra elements in schema, and to use the actual default defined in rust + when_used = None # type: ignore + return _dict_not_none( + type='function-wrap', + function=function, + is_field_serializer=is_field_serializer, + info_arg=info_arg, + schema=schema, + return_schema=return_schema, + when_used=when_used, + ) + + +class FormatSerSchema(TypedDict, total=False): + type: Required[Literal['format']] + formatting_string: Required[str] + when_used: WhenUsed # default: 'json-unless-none' + + +def format_ser_schema(formatting_string: str, *, when_used: WhenUsed = 'json-unless-none') -> FormatSerSchema: + """ + Returns a schema for serialization using python's `format` method. + + Args: + formatting_string: String defining the format to use + when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default + """ + if when_used == 'json-unless-none': + # just to avoid extra elements in schema, and to use the actual default defined in rust + when_used = None # type: ignore + return _dict_not_none(type='format', formatting_string=formatting_string, when_used=when_used) + + +class ToStringSerSchema(TypedDict, total=False): + type: Required[Literal['to-string']] + when_used: WhenUsed # default: 'json-unless-none' + + +def to_string_ser_schema(*, when_used: WhenUsed = 'json-unless-none') -> ToStringSerSchema: + """ + Returns a schema for serialization using python's `str()` / `__str__` method. + + Args: + when_used: Same meaning as for [general_function_plain_ser_schema], but with a different default + """ + s = dict(type='to-string') + if when_used != 'json-unless-none': + # just to avoid extra elements in schema, and to use the actual default defined in rust + s['when_used'] = when_used + return s # type: ignore + + +class ModelSerSchema(TypedDict, total=False): + type: Required[Literal['model']] + cls: Required[Type[Any]] + schema: Required[CoreSchema] + + +def model_ser_schema(cls: Type[Any], schema: CoreSchema) -> ModelSerSchema: + """ + Returns a schema for serialization using a model. + + Args: + cls: The expected class type, used to generate warnings if the wrong type is passed + schema: Internal schema to use to serialize the model dict + """ + return ModelSerSchema(type='model', cls=cls, schema=schema) + + +SerSchema = Union[ + SimpleSerSchema, + PlainSerializerFunctionSerSchema, + WrapSerializerFunctionSerSchema, + FormatSerSchema, + ToStringSerSchema, + ModelSerSchema, +] + + +class ComputedField(TypedDict, total=False): + type: Required[Literal['computed-field']] + property_name: Required[str] + return_schema: Required[CoreSchema] + alias: str + metadata: Any + + +def computed_field( + property_name: str, return_schema: CoreSchema, *, alias: str | None = None, metadata: Any = None +) -> ComputedField: + """ + ComputedFields are properties of a model or dataclass that are included in serialization. + + Args: + property_name: The name of the property on the model or dataclass + return_schema: The schema used for the type returned by the computed field + alias: The name to use in the serialized output + metadata: Any other information you want to include with the schema, not used by pydantic-core + """ + return _dict_not_none( + type='computed-field', property_name=property_name, return_schema=return_schema, alias=alias, metadata=metadata + ) + + +class AnySchema(TypedDict, total=False): + type: Required[Literal['any']] + ref: str + metadata: Any + serialization: SerSchema + + +def any_schema(*, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None) -> AnySchema: + """ + Returns a schema that matches any value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.any_schema() + v = SchemaValidator(schema) + assert v.validate_python(1) == 1 + ``` + + Args: + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none(type='any', ref=ref, metadata=metadata, serialization=serialization) + + +class NoneSchema(TypedDict, total=False): + type: Required[Literal['none']] + ref: str + metadata: Any + serialization: SerSchema + + +def none_schema(*, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None) -> NoneSchema: + """ + Returns a schema that matches a None value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.none_schema() + v = SchemaValidator(schema) + assert v.validate_python(None) is None + ``` + + Args: + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none(type='none', ref=ref, metadata=metadata, serialization=serialization) + + +class BoolSchema(TypedDict, total=False): + type: Required[Literal['bool']] + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def bool_schema( + strict: bool | None = None, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None +) -> BoolSchema: + """ + Returns a schema that matches a bool value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.bool_schema() + v = SchemaValidator(schema) + assert v.validate_python('True') is True + ``` + + Args: + strict: Whether the value should be a bool or a value that can be converted to a bool + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none(type='bool', strict=strict, ref=ref, metadata=metadata, serialization=serialization) + + +class IntSchema(TypedDict, total=False): + type: Required[Literal['int']] + multiple_of: int + le: int + ge: int + lt: int + gt: int + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def int_schema( + *, + multiple_of: int | None = None, + le: int | None = None, + ge: int | None = None, + lt: int | None = None, + gt: int | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> IntSchema: + """ + Returns a schema that matches a int value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.int_schema(multiple_of=2, le=6, ge=2) + v = SchemaValidator(schema) + assert v.validate_python('4') == 4 + ``` + + Args: + multiple_of: The value must be a multiple of this number + le: The value must be less than or equal to this number + ge: The value must be greater than or equal to this number + lt: The value must be strictly less than this number + gt: The value must be strictly greater than this number + strict: Whether the value should be a int or a value that can be converted to a int + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='int', + multiple_of=multiple_of, + le=le, + ge=ge, + lt=lt, + gt=gt, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class FloatSchema(TypedDict, total=False): + type: Required[Literal['float']] + allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: True + multiple_of: float + le: float + ge: float + lt: float + gt: float + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def float_schema( + *, + allow_inf_nan: bool | None = None, + multiple_of: float | None = None, + le: float | None = None, + ge: float | None = None, + lt: float | None = None, + gt: float | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> FloatSchema: + """ + Returns a schema that matches a float value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.float_schema(le=0.8, ge=0.2) + v = SchemaValidator(schema) + assert v.validate_python('0.5') == 0.5 + ``` + + Args: + allow_inf_nan: Whether to allow inf and nan values + multiple_of: The value must be a multiple of this number + le: The value must be less than or equal to this number + ge: The value must be greater than or equal to this number + lt: The value must be strictly less than this number + gt: The value must be strictly greater than this number + strict: Whether the value should be a float or a value that can be converted to a float + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='float', + allow_inf_nan=allow_inf_nan, + multiple_of=multiple_of, + le=le, + ge=ge, + lt=lt, + gt=gt, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class DecimalSchema(TypedDict, total=False): + type: Required[Literal['decimal']] + allow_inf_nan: bool # whether 'NaN', '+inf', '-inf' should be forbidden. default: False + multiple_of: Decimal + le: Decimal + ge: Decimal + lt: Decimal + gt: Decimal + max_digits: int + decimal_places: int + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def decimal_schema( + *, + allow_inf_nan: bool = None, + multiple_of: Decimal | None = None, + le: Decimal | None = None, + ge: Decimal | None = None, + lt: Decimal | None = None, + gt: Decimal | None = None, + max_digits: int | None = None, + decimal_places: int | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> DecimalSchema: + """ + Returns a schema that matches a decimal value, e.g.: + + ```py + from decimal import Decimal + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.decimal_schema(le=0.8, ge=0.2) + v = SchemaValidator(schema) + assert v.validate_python('0.5') == Decimal('0.5') + ``` + + Args: + allow_inf_nan: Whether to allow inf and nan values + multiple_of: The value must be a multiple of this number + le: The value must be less than or equal to this number + ge: The value must be greater than or equal to this number + lt: The value must be strictly less than this number + gt: The value must be strictly greater than this number + max_digits: The maximum number of decimal digits allowed + decimal_places: The maximum number of decimal places allowed + strict: Whether the value should be a float or a value that can be converted to a float + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='decimal', + gt=gt, + ge=ge, + lt=lt, + le=le, + max_digits=max_digits, + decimal_places=decimal_places, + multiple_of=multiple_of, + allow_inf_nan=allow_inf_nan, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class StringSchema(TypedDict, total=False): + type: Required[Literal['str']] + pattern: Union[str, Pattern[str]] + max_length: int + min_length: int + strip_whitespace: bool + to_lower: bool + to_upper: bool + regex_engine: Literal['rust-regex', 'python-re'] # default: 'rust-regex' + strict: bool + coerce_numbers_to_str: bool + ref: str + metadata: Any + serialization: SerSchema + + +def str_schema( + *, + pattern: str | Pattern[str] | None = None, + max_length: int | None = None, + min_length: int | None = None, + strip_whitespace: bool | None = None, + to_lower: bool | None = None, + to_upper: bool | None = None, + regex_engine: Literal['rust-regex', 'python-re'] | None = None, + strict: bool | None = None, + coerce_numbers_to_str: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> StringSchema: + """ + Returns a schema that matches a string value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.str_schema(max_length=10, min_length=2) + v = SchemaValidator(schema) + assert v.validate_python('hello') == 'hello' + ``` + + Args: + pattern: A regex pattern that the value must match + max_length: The value must be at most this length + min_length: The value must be at least this length + strip_whitespace: Whether to strip whitespace from the value + to_lower: Whether to convert the value to lowercase + to_upper: Whether to convert the value to uppercase + regex_engine: The regex engine to use for pattern validation. Default is 'rust-regex'. + - `rust-regex` uses the [`regex`](https://docs.rs/regex) Rust + crate, which is non-backtracking and therefore more DDoS + resistant, but does not support all regex features. + - `python-re` use the [`re`](https://docs.python.org/3/library/re.html) module, + which supports all regex features, but may be slower. + strict: Whether the value should be a string or a value that can be converted to a string + coerce_numbers_to_str: Whether to enable coercion of any `Number` type to `str` (not applicable in `strict` mode). + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='str', + pattern=pattern, + max_length=max_length, + min_length=min_length, + strip_whitespace=strip_whitespace, + to_lower=to_lower, + to_upper=to_upper, + regex_engine=regex_engine, + strict=strict, + coerce_numbers_to_str=coerce_numbers_to_str, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class BytesSchema(TypedDict, total=False): + type: Required[Literal['bytes']] + max_length: int + min_length: int + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def bytes_schema( + *, + max_length: int | None = None, + min_length: int | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> BytesSchema: + """ + Returns a schema that matches a bytes value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.bytes_schema(max_length=10, min_length=2) + v = SchemaValidator(schema) + assert v.validate_python(b'hello') == b'hello' + ``` + + Args: + max_length: The value must be at most this length + min_length: The value must be at least this length + strict: Whether the value should be a bytes or a value that can be converted to a bytes + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='bytes', + max_length=max_length, + min_length=min_length, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class DateSchema(TypedDict, total=False): + type: Required[Literal['date']] + strict: bool + le: date + ge: date + lt: date + gt: date + now_op: Literal['past', 'future'] + # defaults to current local utc offset from `time.localtime().tm_gmtoff` + # value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py + now_utc_offset: int + ref: str + metadata: Any + serialization: SerSchema + + +def date_schema( + *, + strict: bool | None = None, + le: date | None = None, + ge: date | None = None, + lt: date | None = None, + gt: date | None = None, + now_op: Literal['past', 'future'] | None = None, + now_utc_offset: int | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> DateSchema: + """ + Returns a schema that matches a date value, e.g.: + + ```py + from datetime import date + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.date_schema(le=date(2020, 1, 1), ge=date(2019, 1, 1)) + v = SchemaValidator(schema) + assert v.validate_python(date(2019, 6, 1)) == date(2019, 6, 1) + ``` + + Args: + strict: Whether the value should be a date or a value that can be converted to a date + le: The value must be less than or equal to this date + ge: The value must be greater than or equal to this date + lt: The value must be strictly less than this date + gt: The value must be strictly greater than this date + now_op: The value must be in the past or future relative to the current date + now_utc_offset: The value must be in the past or future relative to the current date with this utc offset + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='date', + strict=strict, + le=le, + ge=ge, + lt=lt, + gt=gt, + now_op=now_op, + now_utc_offset=now_utc_offset, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class TimeSchema(TypedDict, total=False): + type: Required[Literal['time']] + strict: bool + le: time + ge: time + lt: time + gt: time + tz_constraint: Union[Literal['aware', 'naive'], int] + microseconds_precision: Literal['truncate', 'error'] + ref: str + metadata: Any + serialization: SerSchema + + +def time_schema( + *, + strict: bool | None = None, + le: time | None = None, + ge: time | None = None, + lt: time | None = None, + gt: time | None = None, + tz_constraint: Literal['aware', 'naive'] | int | None = None, + microseconds_precision: Literal['truncate', 'error'] = 'truncate', + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> TimeSchema: + """ + Returns a schema that matches a time value, e.g.: + + ```py + from datetime import time + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.time_schema(le=time(12, 0, 0), ge=time(6, 0, 0)) + v = SchemaValidator(schema) + assert v.validate_python(time(9, 0, 0)) == time(9, 0, 0) + ``` + + Args: + strict: Whether the value should be a time or a value that can be converted to a time + le: The value must be less than or equal to this time + ge: The value must be greater than or equal to this time + lt: The value must be strictly less than this time + gt: The value must be strictly greater than this time + tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset + microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='time', + strict=strict, + le=le, + ge=ge, + lt=lt, + gt=gt, + tz_constraint=tz_constraint, + microseconds_precision=microseconds_precision, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class DatetimeSchema(TypedDict, total=False): + type: Required[Literal['datetime']] + strict: bool + le: datetime + ge: datetime + lt: datetime + gt: datetime + now_op: Literal['past', 'future'] + tz_constraint: Union[Literal['aware', 'naive'], int] + # defaults to current local utc offset from `time.localtime().tm_gmtoff` + # value is restricted to -86_400 < offset < 86_400 by bounds in generate_self_schema.py + now_utc_offset: int + microseconds_precision: Literal['truncate', 'error'] # default: 'truncate' + ref: str + metadata: Any + serialization: SerSchema + + +def datetime_schema( + *, + strict: bool | None = None, + le: datetime | None = None, + ge: datetime | None = None, + lt: datetime | None = None, + gt: datetime | None = None, + now_op: Literal['past', 'future'] | None = None, + tz_constraint: Literal['aware', 'naive'] | int | None = None, + now_utc_offset: int | None = None, + microseconds_precision: Literal['truncate', 'error'] = 'truncate', + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> DatetimeSchema: + """ + Returns a schema that matches a datetime value, e.g.: + + ```py + from datetime import datetime + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.datetime_schema() + v = SchemaValidator(schema) + now = datetime.now() + assert v.validate_python(str(now)) == now + ``` + + Args: + strict: Whether the value should be a datetime or a value that can be converted to a datetime + le: The value must be less than or equal to this datetime + ge: The value must be greater than or equal to this datetime + lt: The value must be strictly less than this datetime + gt: The value must be strictly greater than this datetime + now_op: The value must be in the past or future relative to the current datetime + tz_constraint: The value must be timezone aware or naive, or an int to indicate required tz offset + TODO: use of a tzinfo where offset changes based on the datetime is not yet supported + now_utc_offset: The value must be in the past or future relative to the current datetime with this utc offset + microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='datetime', + strict=strict, + le=le, + ge=ge, + lt=lt, + gt=gt, + now_op=now_op, + tz_constraint=tz_constraint, + now_utc_offset=now_utc_offset, + microseconds_precision=microseconds_precision, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class TimedeltaSchema(TypedDict, total=False): + type: Required[Literal['timedelta']] + strict: bool + le: timedelta + ge: timedelta + lt: timedelta + gt: timedelta + microseconds_precision: Literal['truncate', 'error'] + ref: str + metadata: Any + serialization: SerSchema + + +def timedelta_schema( + *, + strict: bool | None = None, + le: timedelta | None = None, + ge: timedelta | None = None, + lt: timedelta | None = None, + gt: timedelta | None = None, + microseconds_precision: Literal['truncate', 'error'] = 'truncate', + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> TimedeltaSchema: + """ + Returns a schema that matches a timedelta value, e.g.: + + ```py + from datetime import timedelta + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.timedelta_schema(le=timedelta(days=1), ge=timedelta(days=0)) + v = SchemaValidator(schema) + assert v.validate_python(timedelta(hours=12)) == timedelta(hours=12) + ``` + + Args: + strict: Whether the value should be a timedelta or a value that can be converted to a timedelta + le: The value must be less than or equal to this timedelta + ge: The value must be greater than or equal to this timedelta + lt: The value must be strictly less than this timedelta + gt: The value must be strictly greater than this timedelta + microseconds_precision: The behavior when seconds have more than 6 digits or microseconds is too large + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='timedelta', + strict=strict, + le=le, + ge=ge, + lt=lt, + gt=gt, + microseconds_precision=microseconds_precision, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class LiteralSchema(TypedDict, total=False): + type: Required[Literal['literal']] + expected: Required[List[Any]] + ref: str + metadata: Any + serialization: SerSchema + + +def literal_schema( + expected: list[Any], *, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None +) -> LiteralSchema: + """ + Returns a schema that matches a literal value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.literal_schema(['hello', 'world']) + v = SchemaValidator(schema) + assert v.validate_python('hello') == 'hello' + ``` + + Args: + expected: The value must be one of these values + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none(type='literal', expected=expected, ref=ref, metadata=metadata, serialization=serialization) + + +class EnumSchema(TypedDict, total=False): + type: Required[Literal['enum']] + cls: Required[Any] + members: Required[List[Any]] + sub_type: Literal['str', 'int', 'float'] + missing: Callable[[Any], Any] + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def enum_schema( + cls: Any, + members: list[Any], + *, + sub_type: Literal['str', 'int', 'float'] | None = None, + missing: Callable[[Any], Any] | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> EnumSchema: + """ + Returns a schema that matches an enum value, e.g.: + + ```py + from enum import Enum + from pydantic_core import SchemaValidator, core_schema + + class Color(Enum): + RED = 1 + GREEN = 2 + BLUE = 3 + + schema = core_schema.enum_schema(Color, list(Color.__members__.values())) + v = SchemaValidator(schema) + assert v.validate_python(2) is Color.GREEN + ``` + + Args: + cls: The enum class + members: The members of the enum, generally `list(MyEnum.__members__.values())` + sub_type: The type of the enum, either 'str' or 'int' or None for plain enums + missing: A function to use when the value is not found in the enum, from `_missing_` + strict: Whether to use strict mode, defaults to False + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='enum', + cls=cls, + members=members, + sub_type=sub_type, + missing=missing, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +# must match input/parse_json.rs::JsonType::try_from +JsonType = Literal['null', 'bool', 'int', 'float', 'str', 'list', 'dict'] + + +class IsInstanceSchema(TypedDict, total=False): + type: Required[Literal['is-instance']] + cls: Required[Any] + cls_repr: str + ref: str + metadata: Any + serialization: SerSchema + + +def is_instance_schema( + cls: Any, + *, + cls_repr: str | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> IsInstanceSchema: + """ + Returns a schema that checks if a value is an instance of a class, equivalent to python's `isinstance` method, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + class A: + pass + + schema = core_schema.is_instance_schema(cls=A) + v = SchemaValidator(schema) + v.validate_python(A()) + ``` + + Args: + cls: The value must be an instance of this class + cls_repr: If provided this string is used in the validator name instead of `repr(cls)` + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='is-instance', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization + ) + + +class IsSubclassSchema(TypedDict, total=False): + type: Required[Literal['is-subclass']] + cls: Required[Type[Any]] + cls_repr: str + ref: str + metadata: Any + serialization: SerSchema + + +def is_subclass_schema( + cls: Type[Any], + *, + cls_repr: str | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> IsInstanceSchema: + """ + Returns a schema that checks if a value is a subtype of a class, equivalent to python's `issubclass` method, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + class A: + pass + + class B(A): + pass + + schema = core_schema.is_subclass_schema(cls=A) + v = SchemaValidator(schema) + v.validate_python(B) + ``` + + Args: + cls: The value must be a subclass of this class + cls_repr: If provided this string is used in the validator name instead of `repr(cls)` + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='is-subclass', cls=cls, cls_repr=cls_repr, ref=ref, metadata=metadata, serialization=serialization + ) + + +class CallableSchema(TypedDict, total=False): + type: Required[Literal['callable']] + ref: str + metadata: Any + serialization: SerSchema + + +def callable_schema( + *, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None +) -> CallableSchema: + """ + Returns a schema that checks if a value is callable, equivalent to python's `callable` method, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.callable_schema() + v = SchemaValidator(schema) + v.validate_python(min) + ``` + + Args: + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none(type='callable', ref=ref, metadata=metadata, serialization=serialization) + + +class UuidSchema(TypedDict, total=False): + type: Required[Literal['uuid']] + version: Literal[1, 3, 4, 5] + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def uuid_schema( + *, + version: Literal[1, 3, 4, 5] | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> UuidSchema: + return _dict_not_none( + type='uuid', version=version, strict=strict, ref=ref, metadata=metadata, serialization=serialization + ) + + +class IncExSeqSerSchema(TypedDict, total=False): + type: Required[Literal['include-exclude-sequence']] + include: Set[int] + exclude: Set[int] + + +def filter_seq_schema(*, include: Set[int] | None = None, exclude: Set[int] | None = None) -> IncExSeqSerSchema: + return _dict_not_none(type='include-exclude-sequence', include=include, exclude=exclude) + + +IncExSeqOrElseSerSchema = Union[IncExSeqSerSchema, SerSchema] + + +class ListSchema(TypedDict, total=False): + type: Required[Literal['list']] + items_schema: CoreSchema + min_length: int + max_length: int + fail_fast: bool + strict: bool + ref: str + metadata: Any + serialization: IncExSeqOrElseSerSchema + + +def list_schema( + items_schema: CoreSchema | None = None, + *, + min_length: int | None = None, + max_length: int | None = None, + fail_fast: bool | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: IncExSeqOrElseSerSchema | None = None, +) -> ListSchema: + """ + Returns a schema that matches a list value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.list_schema(core_schema.int_schema(), min_length=0, max_length=10) + v = SchemaValidator(schema) + assert v.validate_python(['4']) == [4] + ``` + + Args: + items_schema: The value must be a list of items that match this schema + min_length: The value must be a list with at least this many items + max_length: The value must be a list with at most this many items + fail_fast: Stop validation on the first error + strict: The value must be a list with exactly this many items + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='list', + items_schema=items_schema, + min_length=min_length, + max_length=max_length, + fail_fast=fail_fast, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +# @deprecated('tuple_positional_schema is deprecated. Use pydantic_core.core_schema.tuple_schema instead.') +def tuple_positional_schema( + items_schema: list[CoreSchema], + *, + extras_schema: CoreSchema | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: IncExSeqOrElseSerSchema | None = None, +) -> TupleSchema: + """ + Returns a schema that matches a tuple of schemas, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.tuple_positional_schema( + [core_schema.int_schema(), core_schema.str_schema()] + ) + v = SchemaValidator(schema) + assert v.validate_python((1, 'hello')) == (1, 'hello') + ``` + + Args: + items_schema: The value must be a tuple with items that match these schemas + extras_schema: The value must be a tuple with items that match this schema + This was inspired by JSON schema's `prefixItems` and `items` fields. + In python's `typing.Tuple`, you can't specify a type for "extra" items -- they must all be the same type + if the length is variable. So this field won't be set from a `typing.Tuple` annotation on a pydantic model. + strict: The value must be a tuple with exactly this many items + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + if extras_schema is not None: + variadic_item_index = len(items_schema) + items_schema = items_schema + [extras_schema] + else: + variadic_item_index = None + return tuple_schema( + items_schema=items_schema, + variadic_item_index=variadic_item_index, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +# @deprecated('tuple_variable_schema is deprecated. Use pydantic_core.core_schema.tuple_schema instead.') +def tuple_variable_schema( + items_schema: CoreSchema | None = None, + *, + min_length: int | None = None, + max_length: int | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: IncExSeqOrElseSerSchema | None = None, +) -> TupleSchema: + """ + Returns a schema that matches a tuple of a given schema, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.tuple_variable_schema( + items_schema=core_schema.int_schema(), min_length=0, max_length=10 + ) + v = SchemaValidator(schema) + assert v.validate_python(('1', 2, 3)) == (1, 2, 3) + ``` + + Args: + items_schema: The value must be a tuple with items that match this schema + min_length: The value must be a tuple with at least this many items + max_length: The value must be a tuple with at most this many items + strict: The value must be a tuple with exactly this many items + ref: Optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return tuple_schema( + items_schema=[items_schema or any_schema()], + variadic_item_index=0, + min_length=min_length, + max_length=max_length, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class TupleSchema(TypedDict, total=False): + type: Required[Literal['tuple']] + items_schema: Required[List[CoreSchema]] + variadic_item_index: int + min_length: int + max_length: int + fail_fast: bool + strict: bool + ref: str + metadata: Any + serialization: IncExSeqOrElseSerSchema + + +def tuple_schema( + items_schema: list[CoreSchema], + *, + variadic_item_index: int | None = None, + min_length: int | None = None, + max_length: int | None = None, + fail_fast: bool | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: IncExSeqOrElseSerSchema | None = None, +) -> TupleSchema: + """ + Returns a schema that matches a tuple of schemas, with an optional variadic item, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.tuple_schema( + [core_schema.int_schema(), core_schema.str_schema(), core_schema.float_schema()], + variadic_item_index=1, + ) + v = SchemaValidator(schema) + assert v.validate_python((1, 'hello', 'world', 1.5)) == (1, 'hello', 'world', 1.5) + ``` + + Args: + items_schema: The value must be a tuple with items that match these schemas + variadic_item_index: The index of the schema in `items_schema` to be treated as variadic (following PEP 646) + min_length: The value must be a tuple with at least this many items + max_length: The value must be a tuple with at most this many items + fail_fast: Stop validation on the first error + strict: The value must be a tuple with exactly this many items + ref: Optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='tuple', + items_schema=items_schema, + variadic_item_index=variadic_item_index, + min_length=min_length, + max_length=max_length, + fail_fast=fail_fast, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class SetSchema(TypedDict, total=False): + type: Required[Literal['set']] + items_schema: CoreSchema + min_length: int + max_length: int + fail_fast: bool + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def set_schema( + items_schema: CoreSchema | None = None, + *, + min_length: int | None = None, + max_length: int | None = None, + fail_fast: bool | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> SetSchema: + """ + Returns a schema that matches a set of a given schema, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.set_schema( + items_schema=core_schema.int_schema(), min_length=0, max_length=10 + ) + v = SchemaValidator(schema) + assert v.validate_python({1, '2', 3}) == {1, 2, 3} + ``` + + Args: + items_schema: The value must be a set with items that match this schema + min_length: The value must be a set with at least this many items + max_length: The value must be a set with at most this many items + fail_fast: Stop validation on the first error + strict: The value must be a set with exactly this many items + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='set', + items_schema=items_schema, + min_length=min_length, + max_length=max_length, + fail_fast=fail_fast, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class FrozenSetSchema(TypedDict, total=False): + type: Required[Literal['frozenset']] + items_schema: CoreSchema + min_length: int + max_length: int + fail_fast: bool + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def frozenset_schema( + items_schema: CoreSchema | None = None, + *, + min_length: int | None = None, + max_length: int | None = None, + fail_fast: bool | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> FrozenSetSchema: + """ + Returns a schema that matches a frozenset of a given schema, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.frozenset_schema( + items_schema=core_schema.int_schema(), min_length=0, max_length=10 + ) + v = SchemaValidator(schema) + assert v.validate_python(frozenset(range(3))) == frozenset({0, 1, 2}) + ``` + + Args: + items_schema: The value must be a frozenset with items that match this schema + min_length: The value must be a frozenset with at least this many items + max_length: The value must be a frozenset with at most this many items + fail_fast: Stop validation on the first error + strict: The value must be a frozenset with exactly this many items + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='frozenset', + items_schema=items_schema, + min_length=min_length, + max_length=max_length, + fail_fast=fail_fast, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class GeneratorSchema(TypedDict, total=False): + type: Required[Literal['generator']] + items_schema: CoreSchema + min_length: int + max_length: int + ref: str + metadata: Any + serialization: IncExSeqOrElseSerSchema + + +def generator_schema( + items_schema: CoreSchema | None = None, + *, + min_length: int | None = None, + max_length: int | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: IncExSeqOrElseSerSchema | None = None, +) -> GeneratorSchema: + """ + Returns a schema that matches a generator value, e.g.: + + ```py + from typing import Iterator + from pydantic_core import SchemaValidator, core_schema + + def gen() -> Iterator[int]: + yield 1 + + schema = core_schema.generator_schema(items_schema=core_schema.int_schema()) + v = SchemaValidator(schema) + v.validate_python(gen()) + ``` + + Unlike other types, validated generators do not raise ValidationErrors eagerly, + but instead will raise a ValidationError when a violating value is actually read from the generator. + This is to ensure that "validated" generators retain the benefit of lazy evaluation. + + Args: + items_schema: The value must be a generator with items that match this schema + min_length: The value must be a generator that yields at least this many items + max_length: The value must be a generator that yields at most this many items + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='generator', + items_schema=items_schema, + min_length=min_length, + max_length=max_length, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +IncExDict = Set[Union[int, str]] + + +class IncExDictSerSchema(TypedDict, total=False): + type: Required[Literal['include-exclude-dict']] + include: IncExDict + exclude: IncExDict + + +def filter_dict_schema(*, include: IncExDict | None = None, exclude: IncExDict | None = None) -> IncExDictSerSchema: + return _dict_not_none(type='include-exclude-dict', include=include, exclude=exclude) + + +IncExDictOrElseSerSchema = Union[IncExDictSerSchema, SerSchema] + + +class DictSchema(TypedDict, total=False): + type: Required[Literal['dict']] + keys_schema: CoreSchema # default: AnySchema + values_schema: CoreSchema # default: AnySchema + min_length: int + max_length: int + strict: bool + ref: str + metadata: Any + serialization: IncExDictOrElseSerSchema + + +def dict_schema( + keys_schema: CoreSchema | None = None, + values_schema: CoreSchema | None = None, + *, + min_length: int | None = None, + max_length: int | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> DictSchema: + """ + Returns a schema that matches a dict value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.dict_schema( + keys_schema=core_schema.str_schema(), values_schema=core_schema.int_schema() + ) + v = SchemaValidator(schema) + assert v.validate_python({'a': '1', 'b': 2}) == {'a': 1, 'b': 2} + ``` + + Args: + keys_schema: The value must be a dict with keys that match this schema + values_schema: The value must be a dict with values that match this schema + min_length: The value must be a dict with at least this many items + max_length: The value must be a dict with at most this many items + strict: Whether the keys and values should be validated with strict mode + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='dict', + keys_schema=keys_schema, + values_schema=values_schema, + min_length=min_length, + max_length=max_length, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +# (input_value: Any, /) -> Any +NoInfoValidatorFunction = Callable[[Any], Any] + + +class NoInfoValidatorFunctionSchema(TypedDict): + type: Literal['no-info'] + function: NoInfoValidatorFunction + + +# (input_value: Any, info: ValidationInfo, /) -> Any +WithInfoValidatorFunction = Callable[[Any, ValidationInfo], Any] + + +class WithInfoValidatorFunctionSchema(TypedDict, total=False): + type: Required[Literal['with-info']] + function: Required[WithInfoValidatorFunction] + field_name: str + + +ValidationFunction = Union[NoInfoValidatorFunctionSchema, WithInfoValidatorFunctionSchema] + + +class _ValidatorFunctionSchema(TypedDict, total=False): + function: Required[ValidationFunction] + schema: Required[CoreSchema] + ref: str + metadata: Any + serialization: SerSchema + + +class BeforeValidatorFunctionSchema(_ValidatorFunctionSchema, total=False): + type: Required[Literal['function-before']] + + +def no_info_before_validator_function( + function: NoInfoValidatorFunction, + schema: CoreSchema, + *, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> BeforeValidatorFunctionSchema: + """ + Returns a schema that calls a validator function before validating, no `info` argument is provided, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn(v: bytes) -> str: + return v.decode() + 'world' + + func_schema = core_schema.no_info_before_validator_function( + function=fn, schema=core_schema.str_schema() + ) + schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) + + v = SchemaValidator(schema) + assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} + ``` + + Args: + function: The validator function to call + schema: The schema to validate the output of the validator function + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='function-before', + function={'type': 'no-info', 'function': function}, + schema=schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +def with_info_before_validator_function( + function: WithInfoValidatorFunction, + schema: CoreSchema, + *, + field_name: str | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> BeforeValidatorFunctionSchema: + """ + Returns a schema that calls a validator function before validation, the function is called with + an `info` argument, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn(v: bytes, info: core_schema.ValidationInfo) -> str: + assert info.data is not None + assert info.field_name is not None + return v.decode() + 'world' + + func_schema = core_schema.with_info_before_validator_function( + function=fn, schema=core_schema.str_schema(), field_name='a' + ) + schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) + + v = SchemaValidator(schema) + assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} + ``` + + Args: + function: The validator function to call + field_name: The name of the field + schema: The schema to validate the output of the validator function + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='function-before', + function=_dict_not_none(type='with-info', function=function, field_name=field_name), + schema=schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class AfterValidatorFunctionSchema(_ValidatorFunctionSchema, total=False): + type: Required[Literal['function-after']] + + +def no_info_after_validator_function( + function: NoInfoValidatorFunction, + schema: CoreSchema, + *, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> AfterValidatorFunctionSchema: + """ + Returns a schema that calls a validator function after validating, no `info` argument is provided, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn(v: str) -> str: + return v + 'world' + + func_schema = core_schema.no_info_after_validator_function(fn, core_schema.str_schema()) + schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) + + v = SchemaValidator(schema) + assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} + ``` + + Args: + function: The validator function to call after the schema is validated + schema: The schema to validate before the validator function + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='function-after', + function={'type': 'no-info', 'function': function}, + schema=schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +def with_info_after_validator_function( + function: WithInfoValidatorFunction, + schema: CoreSchema, + *, + field_name: str | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> AfterValidatorFunctionSchema: + """ + Returns a schema that calls a validator function after validation, the function is called with + an `info` argument, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn(v: str, info: core_schema.ValidationInfo) -> str: + assert info.data is not None + assert info.field_name is not None + return v + 'world' + + func_schema = core_schema.with_info_after_validator_function( + function=fn, schema=core_schema.str_schema(), field_name='a' + ) + schema = core_schema.typed_dict_schema({'a': core_schema.typed_dict_field(func_schema)}) + + v = SchemaValidator(schema) + assert v.validate_python({'a': b'hello '}) == {'a': 'hello world'} + ``` + + Args: + function: The validator function to call after the schema is validated + schema: The schema to validate before the validator function + field_name: The name of the field this validators is applied to, if any + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='function-after', + function=_dict_not_none(type='with-info', function=function, field_name=field_name), + schema=schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class ValidatorFunctionWrapHandler(Protocol): + def __call__(self, input_value: Any, outer_location: str | int | None = None, /) -> Any: # pragma: no cover + ... + + +# (input_value: Any, validator: ValidatorFunctionWrapHandler, /) -> Any +NoInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler], Any] + + +class NoInfoWrapValidatorFunctionSchema(TypedDict): + type: Literal['no-info'] + function: NoInfoWrapValidatorFunction + + +# (input_value: Any, validator: ValidatorFunctionWrapHandler, info: ValidationInfo, /) -> Any +WithInfoWrapValidatorFunction = Callable[[Any, ValidatorFunctionWrapHandler, ValidationInfo], Any] + + +class WithInfoWrapValidatorFunctionSchema(TypedDict, total=False): + type: Required[Literal['with-info']] + function: Required[WithInfoWrapValidatorFunction] + field_name: str + + +WrapValidatorFunction = Union[NoInfoWrapValidatorFunctionSchema, WithInfoWrapValidatorFunctionSchema] + + +class WrapValidatorFunctionSchema(TypedDict, total=False): + type: Required[Literal['function-wrap']] + function: Required[WrapValidatorFunction] + schema: Required[CoreSchema] + ref: str + metadata: Any + serialization: SerSchema + + +def no_info_wrap_validator_function( + function: NoInfoWrapValidatorFunction, + schema: CoreSchema, + *, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> WrapValidatorFunctionSchema: + """ + Returns a schema which calls a function with a `validator` callable argument which can + optionally be used to call inner validation with the function logic, this is much like the + "onion" implementation of middleware in many popular web frameworks, no `info` argument is passed, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn( + v: str, + validator: core_schema.ValidatorFunctionWrapHandler, + ) -> str: + return validator(input_value=v) + 'world' + + schema = core_schema.no_info_wrap_validator_function( + function=fn, schema=core_schema.str_schema() + ) + v = SchemaValidator(schema) + assert v.validate_python('hello ') == 'hello world' + ``` + + Args: + function: The validator function to call + schema: The schema to validate the output of the validator function + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='function-wrap', + function={'type': 'no-info', 'function': function}, + schema=schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +def with_info_wrap_validator_function( + function: WithInfoWrapValidatorFunction, + schema: CoreSchema, + *, + field_name: str | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> WrapValidatorFunctionSchema: + """ + Returns a schema which calls a function with a `validator` callable argument which can + optionally be used to call inner validation with the function logic, this is much like the + "onion" implementation of middleware in many popular web frameworks, an `info` argument is also passed, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn( + v: str, + validator: core_schema.ValidatorFunctionWrapHandler, + info: core_schema.ValidationInfo, + ) -> str: + return validator(input_value=v) + 'world' + + schema = core_schema.with_info_wrap_validator_function( + function=fn, schema=core_schema.str_schema() + ) + v = SchemaValidator(schema) + assert v.validate_python('hello ') == 'hello world' + ``` + + Args: + function: The validator function to call + schema: The schema to validate the output of the validator function + field_name: The name of the field this validators is applied to, if any + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='function-wrap', + function=_dict_not_none(type='with-info', function=function, field_name=field_name), + schema=schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class PlainValidatorFunctionSchema(TypedDict, total=False): + type: Required[Literal['function-plain']] + function: Required[ValidationFunction] + ref: str + metadata: Any + serialization: SerSchema + + +def no_info_plain_validator_function( + function: NoInfoValidatorFunction, + *, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> PlainValidatorFunctionSchema: + """ + Returns a schema that uses the provided function for validation, no `info` argument is passed, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn(v: str) -> str: + assert 'hello' in v + return v + 'world' + + schema = core_schema.no_info_plain_validator_function(function=fn) + v = SchemaValidator(schema) + assert v.validate_python('hello ') == 'hello world' + ``` + + Args: + function: The validator function to call + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='function-plain', + function={'type': 'no-info', 'function': function}, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +def with_info_plain_validator_function( + function: WithInfoValidatorFunction, + *, + field_name: str | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> PlainValidatorFunctionSchema: + """ + Returns a schema that uses the provided function for validation, an `info` argument is passed, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn(v: str, info: core_schema.ValidationInfo) -> str: + assert 'hello' in v + return v + 'world' + + schema = core_schema.with_info_plain_validator_function(function=fn) + v = SchemaValidator(schema) + assert v.validate_python('hello ') == 'hello world' + ``` + + Args: + function: The validator function to call + field_name: The name of the field this validators is applied to, if any + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='function-plain', + function=_dict_not_none(type='with-info', function=function, field_name=field_name), + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class WithDefaultSchema(TypedDict, total=False): + type: Required[Literal['default']] + schema: Required[CoreSchema] + default: Any + default_factory: Callable[[], Any] + on_error: Literal['raise', 'omit', 'default'] # default: 'raise' + validate_default: bool # default: False + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def with_default_schema( + schema: CoreSchema, + *, + default: Any = PydanticUndefined, + default_factory: Callable[[], Any] | None = None, + on_error: Literal['raise', 'omit', 'default'] | None = None, + validate_default: bool | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> WithDefaultSchema: + """ + Returns a schema that adds a default value to the given schema, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.with_default_schema(core_schema.str_schema(), default='hello') + wrapper_schema = core_schema.typed_dict_schema( + {'a': core_schema.typed_dict_field(schema)} + ) + v = SchemaValidator(wrapper_schema) + assert v.validate_python({}) == v.validate_python({'a': 'hello'}) + ``` + + Args: + schema: The schema to add a default value to + default: The default value to use + default_factory: A function that returns the default value to use + on_error: What to do if the schema validation fails. One of 'raise', 'omit', 'default' + validate_default: Whether the default value should be validated + strict: Whether the underlying schema should be validated with strict mode + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + s = _dict_not_none( + type='default', + schema=schema, + default_factory=default_factory, + on_error=on_error, + validate_default=validate_default, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + if default is not PydanticUndefined: + s['default'] = default + return s + + +class NullableSchema(TypedDict, total=False): + type: Required[Literal['nullable']] + schema: Required[CoreSchema] + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def nullable_schema( + schema: CoreSchema, + *, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> NullableSchema: + """ + Returns a schema that matches a nullable value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.nullable_schema(core_schema.str_schema()) + v = SchemaValidator(schema) + assert v.validate_python(None) is None + ``` + + Args: + schema: The schema to wrap + strict: Whether the underlying schema should be validated with strict mode + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='nullable', schema=schema, strict=strict, ref=ref, metadata=metadata, serialization=serialization + ) + + +class UnionSchema(TypedDict, total=False): + type: Required[Literal['union']] + choices: Required[List[Union[CoreSchema, Tuple[CoreSchema, str]]]] + # default true, whether to automatically collapse unions with one element to the inner validator + auto_collapse: bool + custom_error_type: str + custom_error_message: str + custom_error_context: Dict[str, Union[str, int, float]] + mode: Literal['smart', 'left_to_right'] # default: 'smart' + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def union_schema( + choices: list[CoreSchema | tuple[CoreSchema, str]], + *, + auto_collapse: bool | None = None, + custom_error_type: str | None = None, + custom_error_message: str | None = None, + custom_error_context: dict[str, str | int] | None = None, + mode: Literal['smart', 'left_to_right'] | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> UnionSchema: + """ + Returns a schema that matches a union value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.union_schema([core_schema.str_schema(), core_schema.int_schema()]) + v = SchemaValidator(schema) + assert v.validate_python('hello') == 'hello' + assert v.validate_python(1) == 1 + ``` + + Args: + choices: The schemas to match. If a tuple, the second item is used as the label for the case. + auto_collapse: whether to automatically collapse unions with one element to the inner validator, default true + custom_error_type: The custom error type to use if the validation fails + custom_error_message: The custom error message to use if the validation fails + custom_error_context: The custom error context to use if the validation fails + mode: How to select which choice to return + * `smart` (default) will try to return the choice which is the closest match to the input value + * `left_to_right` will return the first choice in `choices` which succeeds validation + strict: Whether the underlying schemas should be validated with strict mode + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='union', + choices=choices, + auto_collapse=auto_collapse, + custom_error_type=custom_error_type, + custom_error_message=custom_error_message, + custom_error_context=custom_error_context, + mode=mode, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class TaggedUnionSchema(TypedDict, total=False): + type: Required[Literal['tagged-union']] + choices: Required[Dict[Hashable, CoreSchema]] + discriminator: Required[Union[str, List[Union[str, int]], List[List[Union[str, int]]], Callable[[Any], Hashable]]] + custom_error_type: str + custom_error_message: str + custom_error_context: Dict[str, Union[str, int, float]] + strict: bool + from_attributes: bool # default: True + ref: str + metadata: Any + serialization: SerSchema + + +def tagged_union_schema( + choices: Dict[Any, CoreSchema], + discriminator: str | list[str | int] | list[list[str | int]] | Callable[[Any], Any], + *, + custom_error_type: str | None = None, + custom_error_message: str | None = None, + custom_error_context: dict[str, int | str | float] | None = None, + strict: bool | None = None, + from_attributes: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> TaggedUnionSchema: + """ + Returns a schema that matches a tagged union value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + apple_schema = core_schema.typed_dict_schema( + { + 'foo': core_schema.typed_dict_field(core_schema.str_schema()), + 'bar': core_schema.typed_dict_field(core_schema.int_schema()), + } + ) + banana_schema = core_schema.typed_dict_schema( + { + 'foo': core_schema.typed_dict_field(core_schema.str_schema()), + 'spam': core_schema.typed_dict_field( + core_schema.list_schema(items_schema=core_schema.int_schema()) + ), + } + ) + schema = core_schema.tagged_union_schema( + choices={ + 'apple': apple_schema, + 'banana': banana_schema, + }, + discriminator='foo', + ) + v = SchemaValidator(schema) + assert v.validate_python({'foo': 'apple', 'bar': '123'}) == {'foo': 'apple', 'bar': 123} + assert v.validate_python({'foo': 'banana', 'spam': [1, 2, 3]}) == { + 'foo': 'banana', + 'spam': [1, 2, 3], + } + ``` + + Args: + choices: The schemas to match + When retrieving a schema from `choices` using the discriminator value, if the value is a str, + it should be fed back into the `choices` map until a schema is obtained + (This approach is to prevent multiple ownership of a single schema in Rust) + discriminator: The discriminator to use to determine the schema to use + * If `discriminator` is a str, it is the name of the attribute to use as the discriminator + * If `discriminator` is a list of int/str, it should be used as a "path" to access the discriminator + * If `discriminator` is a list of lists, each inner list is a path, and the first path that exists is used + * If `discriminator` is a callable, it should return the discriminator when called on the value to validate; + the callable can return `None` to indicate that there is no matching discriminator present on the input + custom_error_type: The custom error type to use if the validation fails + custom_error_message: The custom error message to use if the validation fails + custom_error_context: The custom error context to use if the validation fails + strict: Whether the underlying schemas should be validated with strict mode + from_attributes: Whether to use the attributes of the object to retrieve the discriminator value + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='tagged-union', + choices=choices, + discriminator=discriminator, + custom_error_type=custom_error_type, + custom_error_message=custom_error_message, + custom_error_context=custom_error_context, + strict=strict, + from_attributes=from_attributes, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class ChainSchema(TypedDict, total=False): + type: Required[Literal['chain']] + steps: Required[List[CoreSchema]] + ref: str + metadata: Any + serialization: SerSchema + + +def chain_schema( + steps: list[CoreSchema], *, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None +) -> ChainSchema: + """ + Returns a schema that chains the provided validation schemas, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn(v: str, info: core_schema.ValidationInfo) -> str: + assert 'hello' in v + return v + ' world' + + fn_schema = core_schema.with_info_plain_validator_function(function=fn) + schema = core_schema.chain_schema( + [fn_schema, fn_schema, fn_schema, core_schema.str_schema()] + ) + v = SchemaValidator(schema) + assert v.validate_python('hello') == 'hello world world world' + ``` + + Args: + steps: The schemas to chain + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none(type='chain', steps=steps, ref=ref, metadata=metadata, serialization=serialization) + + +class LaxOrStrictSchema(TypedDict, total=False): + type: Required[Literal['lax-or-strict']] + lax_schema: Required[CoreSchema] + strict_schema: Required[CoreSchema] + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def lax_or_strict_schema( + lax_schema: CoreSchema, + strict_schema: CoreSchema, + *, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> LaxOrStrictSchema: + """ + Returns a schema that uses the lax or strict schema, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + def fn(v: str, info: core_schema.ValidationInfo) -> str: + assert 'hello' in v + return v + ' world' + + lax_schema = core_schema.int_schema(strict=False) + strict_schema = core_schema.int_schema(strict=True) + + schema = core_schema.lax_or_strict_schema( + lax_schema=lax_schema, strict_schema=strict_schema, strict=True + ) + v = SchemaValidator(schema) + assert v.validate_python(123) == 123 + + schema = core_schema.lax_or_strict_schema( + lax_schema=lax_schema, strict_schema=strict_schema, strict=False + ) + v = SchemaValidator(schema) + assert v.validate_python('123') == 123 + ``` + + Args: + lax_schema: The lax schema to use + strict_schema: The strict schema to use + strict: Whether the strict schema should be used + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='lax-or-strict', + lax_schema=lax_schema, + strict_schema=strict_schema, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class JsonOrPythonSchema(TypedDict, total=False): + type: Required[Literal['json-or-python']] + json_schema: Required[CoreSchema] + python_schema: Required[CoreSchema] + ref: str + metadata: Any + serialization: SerSchema + + +def json_or_python_schema( + json_schema: CoreSchema, + python_schema: CoreSchema, + *, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> JsonOrPythonSchema: + """ + Returns a schema that uses the Json or Python schema depending on the input: + + ```py + from pydantic_core import SchemaValidator, ValidationError, core_schema + + v = SchemaValidator( + core_schema.json_or_python_schema( + json_schema=core_schema.int_schema(), + python_schema=core_schema.int_schema(strict=True), + ) + ) + + assert v.validate_json('"123"') == 123 + + try: + v.validate_python('123') + except ValidationError: + pass + else: + raise AssertionError('Validation should have failed') + ``` + + Args: + json_schema: The schema to use for Json inputs + python_schema: The schema to use for Python inputs + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='json-or-python', + json_schema=json_schema, + python_schema=python_schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class TypedDictField(TypedDict, total=False): + type: Required[Literal['typed-dict-field']] + schema: Required[CoreSchema] + required: bool + validation_alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]] + serialization_alias: str + serialization_exclude: bool # default: False + metadata: Any + + +def typed_dict_field( + schema: CoreSchema, + *, + required: bool | None = None, + validation_alias: str | list[str | int] | list[list[str | int]] | None = None, + serialization_alias: str | None = None, + serialization_exclude: bool | None = None, + metadata: Any = None, +) -> TypedDictField: + """ + Returns a schema that matches a typed dict field, e.g.: + + ```py + from pydantic_core import core_schema + + field = core_schema.typed_dict_field(schema=core_schema.int_schema(), required=True) + ``` + + Args: + schema: The schema to use for the field + required: Whether the field is required + validation_alias: The alias(es) to use to find the field in the validation data + serialization_alias: The alias to use as a key when serializing + serialization_exclude: Whether to exclude the field when serializing + metadata: Any other information you want to include with the schema, not used by pydantic-core + """ + return _dict_not_none( + type='typed-dict-field', + schema=schema, + required=required, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + serialization_exclude=serialization_exclude, + metadata=metadata, + ) + + +class TypedDictSchema(TypedDict, total=False): + type: Required[Literal['typed-dict']] + fields: Required[Dict[str, TypedDictField]] + computed_fields: List[ComputedField] + strict: bool + extras_schema: CoreSchema + # all these values can be set via config, equivalent fields have `typed_dict_` prefix + extra_behavior: ExtraBehavior + total: bool # default: True + populate_by_name: bool # replaces `allow_population_by_field_name` in pydantic v1 + ref: str + metadata: Any + serialization: SerSchema + config: CoreConfig + + +def typed_dict_schema( + fields: Dict[str, TypedDictField], + *, + computed_fields: list[ComputedField] | None = None, + strict: bool | None = None, + extras_schema: CoreSchema | None = None, + extra_behavior: ExtraBehavior | None = None, + total: bool | None = None, + populate_by_name: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, + config: CoreConfig | None = None, +) -> TypedDictSchema: + """ + Returns a schema that matches a typed dict, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + wrapper_schema = core_schema.typed_dict_schema( + {'a': core_schema.typed_dict_field(core_schema.str_schema())} + ) + v = SchemaValidator(wrapper_schema) + assert v.validate_python({'a': 'hello'}) == {'a': 'hello'} + ``` + + Args: + fields: The fields to use for the typed dict + computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model + strict: Whether the typed dict is strict + extras_schema: The extra validator to use for the typed dict + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + extra_behavior: The extra behavior to use for the typed dict + total: Whether the typed dict is total + populate_by_name: Whether the typed dict should populate by name + serialization: Custom serialization schema + """ + return _dict_not_none( + type='typed-dict', + fields=fields, + computed_fields=computed_fields, + strict=strict, + extras_schema=extras_schema, + extra_behavior=extra_behavior, + total=total, + populate_by_name=populate_by_name, + ref=ref, + metadata=metadata, + serialization=serialization, + config=config, + ) + + +class ModelField(TypedDict, total=False): + type: Required[Literal['model-field']] + schema: Required[CoreSchema] + validation_alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]] + serialization_alias: str + serialization_exclude: bool # default: False + frozen: bool + metadata: Any + + +def model_field( + schema: CoreSchema, + *, + validation_alias: str | list[str | int] | list[list[str | int]] | None = None, + serialization_alias: str | None = None, + serialization_exclude: bool | None = None, + frozen: bool | None = None, + metadata: Any = None, +) -> ModelField: + """ + Returns a schema for a model field, e.g.: + + ```py + from pydantic_core import core_schema + + field = core_schema.model_field(schema=core_schema.int_schema()) + ``` + + Args: + schema: The schema to use for the field + validation_alias: The alias(es) to use to find the field in the validation data + serialization_alias: The alias to use as a key when serializing + serialization_exclude: Whether to exclude the field when serializing + frozen: Whether the field is frozen + metadata: Any other information you want to include with the schema, not used by pydantic-core + """ + return _dict_not_none( + type='model-field', + schema=schema, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + serialization_exclude=serialization_exclude, + frozen=frozen, + metadata=metadata, + ) + + +class ModelFieldsSchema(TypedDict, total=False): + type: Required[Literal['model-fields']] + fields: Required[Dict[str, ModelField]] + model_name: str + computed_fields: List[ComputedField] + strict: bool + extras_schema: CoreSchema + # all these values can be set via config, equivalent fields have `typed_dict_` prefix + extra_behavior: ExtraBehavior + populate_by_name: bool # replaces `allow_population_by_field_name` in pydantic v1 + from_attributes: bool + ref: str + metadata: Any + serialization: SerSchema + + +def model_fields_schema( + fields: Dict[str, ModelField], + *, + model_name: str | None = None, + computed_fields: list[ComputedField] | None = None, + strict: bool | None = None, + extras_schema: CoreSchema | None = None, + extra_behavior: ExtraBehavior | None = None, + populate_by_name: bool | None = None, + from_attributes: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> ModelFieldsSchema: + """ + Returns a schema that matches a typed dict, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + wrapper_schema = core_schema.model_fields_schema( + {'a': core_schema.model_field(core_schema.str_schema())} + ) + v = SchemaValidator(wrapper_schema) + print(v.validate_python({'a': 'hello'})) + #> ({'a': 'hello'}, None, {'a'}) + ``` + + Args: + fields: The fields to use for the typed dict + model_name: The name of the model, used for error messages, defaults to "Model" + computed_fields: Computed fields to use when serializing the model, only applies when directly inside a model + strict: Whether the typed dict is strict + extras_schema: The extra validator to use for the typed dict + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + extra_behavior: The extra behavior to use for the typed dict + populate_by_name: Whether the typed dict should populate by name + from_attributes: Whether the typed dict should be populated from attributes + serialization: Custom serialization schema + """ + return _dict_not_none( + type='model-fields', + fields=fields, + model_name=model_name, + computed_fields=computed_fields, + strict=strict, + extras_schema=extras_schema, + extra_behavior=extra_behavior, + populate_by_name=populate_by_name, + from_attributes=from_attributes, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class ModelSchema(TypedDict, total=False): + type: Required[Literal['model']] + cls: Required[Type[Any]] + schema: Required[CoreSchema] + custom_init: bool + root_model: bool + post_init: str + revalidate_instances: Literal['always', 'never', 'subclass-instances'] # default: 'never' + strict: bool + frozen: bool + extra_behavior: ExtraBehavior + config: CoreConfig + ref: str + metadata: Any + serialization: SerSchema + + +def model_schema( + cls: Type[Any], + schema: CoreSchema, + *, + custom_init: bool | None = None, + root_model: bool | None = None, + post_init: str | None = None, + revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None, + strict: bool | None = None, + frozen: bool | None = None, + extra_behavior: ExtraBehavior | None = None, + config: CoreConfig | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> ModelSchema: + """ + A model schema generally contains a typed-dict schema. + It will run the typed dict validator, then create a new class + and set the dict and fields set returned from the typed dict validator + to `__dict__` and `__pydantic_fields_set__` respectively. + + Example: + + ```py + from pydantic_core import CoreConfig, SchemaValidator, core_schema + + class MyModel: + __slots__ = ( + '__dict__', + '__pydantic_fields_set__', + '__pydantic_extra__', + '__pydantic_private__', + ) + + schema = core_schema.model_schema( + cls=MyModel, + config=CoreConfig(str_max_length=5), + schema=core_schema.model_fields_schema( + fields={'a': core_schema.model_field(core_schema.str_schema())}, + ), + ) + v = SchemaValidator(schema) + assert v.isinstance_python({'a': 'hello'}) is True + assert v.isinstance_python({'a': 'too long'}) is False + ``` + + Args: + cls: The class to use for the model + schema: The schema to use for the model + custom_init: Whether the model has a custom init method + root_model: Whether the model is a `RootModel` + post_init: The call after init to use for the model + revalidate_instances: whether instances of models and dataclasses (including subclass instances) + should re-validate defaults to config.revalidate_instances, else 'never' + strict: Whether the model is strict + frozen: Whether the model is frozen + extra_behavior: The extra behavior to use for the model, used in serialization + config: The config to use for the model + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='model', + cls=cls, + schema=schema, + custom_init=custom_init, + root_model=root_model, + post_init=post_init, + revalidate_instances=revalidate_instances, + strict=strict, + frozen=frozen, + extra_behavior=extra_behavior, + config=config, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class DataclassField(TypedDict, total=False): + type: Required[Literal['dataclass-field']] + name: Required[str] + schema: Required[CoreSchema] + kw_only: bool # default: True + init: bool # default: True + init_only: bool # default: False + frozen: bool # default: False + validation_alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]] + serialization_alias: str + serialization_exclude: bool # default: False + metadata: Any + + +def dataclass_field( + name: str, + schema: CoreSchema, + *, + kw_only: bool | None = None, + init: bool | None = None, + init_only: bool | None = None, + validation_alias: str | list[str | int] | list[list[str | int]] | None = None, + serialization_alias: str | None = None, + serialization_exclude: bool | None = None, + metadata: Any = None, + frozen: bool | None = None, +) -> DataclassField: + """ + Returns a schema for a dataclass field, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + field = core_schema.dataclass_field( + name='a', schema=core_schema.str_schema(), kw_only=False + ) + schema = core_schema.dataclass_args_schema('Foobar', [field]) + v = SchemaValidator(schema) + assert v.validate_python({'a': 'hello'}) == ({'a': 'hello'}, None) + ``` + + Args: + name: The name to use for the argument parameter + schema: The schema to use for the argument parameter + kw_only: Whether the field can be set with a positional argument as well as a keyword argument + init: Whether the field should be validated during initialization + init_only: Whether the field should be omitted from `__dict__` and passed to `__post_init__` + validation_alias: The alias(es) to use to find the field in the validation data + serialization_alias: The alias to use as a key when serializing + serialization_exclude: Whether to exclude the field when serializing + metadata: Any other information you want to include with the schema, not used by pydantic-core + frozen: Whether the field is frozen + """ + return _dict_not_none( + type='dataclass-field', + name=name, + schema=schema, + kw_only=kw_only, + init=init, + init_only=init_only, + validation_alias=validation_alias, + serialization_alias=serialization_alias, + serialization_exclude=serialization_exclude, + metadata=metadata, + frozen=frozen, + ) + + +class DataclassArgsSchema(TypedDict, total=False): + type: Required[Literal['dataclass-args']] + dataclass_name: Required[str] + fields: Required[List[DataclassField]] + computed_fields: List[ComputedField] + populate_by_name: bool # default: False + collect_init_only: bool # default: False + ref: str + metadata: Any + serialization: SerSchema + extra_behavior: ExtraBehavior + + +def dataclass_args_schema( + dataclass_name: str, + fields: list[DataclassField], + *, + computed_fields: List[ComputedField] | None = None, + populate_by_name: bool | None = None, + collect_init_only: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, + extra_behavior: ExtraBehavior | None = None, +) -> DataclassArgsSchema: + """ + Returns a schema for validating dataclass arguments, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + field_a = core_schema.dataclass_field( + name='a', schema=core_schema.str_schema(), kw_only=False + ) + field_b = core_schema.dataclass_field( + name='b', schema=core_schema.bool_schema(), kw_only=False + ) + schema = core_schema.dataclass_args_schema('Foobar', [field_a, field_b]) + v = SchemaValidator(schema) + assert v.validate_python({'a': 'hello', 'b': True}) == ({'a': 'hello', 'b': True}, None) + ``` + + Args: + dataclass_name: The name of the dataclass being validated + fields: The fields to use for the dataclass + computed_fields: Computed fields to use when serializing the dataclass + populate_by_name: Whether to populate by name + collect_init_only: Whether to collect init only fields into a dict to pass to `__post_init__` + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + extra_behavior: How to handle extra fields + """ + return _dict_not_none( + type='dataclass-args', + dataclass_name=dataclass_name, + fields=fields, + computed_fields=computed_fields, + populate_by_name=populate_by_name, + collect_init_only=collect_init_only, + ref=ref, + metadata=metadata, + serialization=serialization, + extra_behavior=extra_behavior, + ) + + +class DataclassSchema(TypedDict, total=False): + type: Required[Literal['dataclass']] + cls: Required[Type[Any]] + schema: Required[CoreSchema] + fields: Required[List[str]] + cls_name: str + post_init: bool # default: False + revalidate_instances: Literal['always', 'never', 'subclass-instances'] # default: 'never' + strict: bool # default: False + frozen: bool # default False + ref: str + metadata: Any + serialization: SerSchema + slots: bool + config: CoreConfig + + +def dataclass_schema( + cls: Type[Any], + schema: CoreSchema, + fields: List[str], + *, + cls_name: str | None = None, + post_init: bool | None = None, + revalidate_instances: Literal['always', 'never', 'subclass-instances'] | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, + frozen: bool | None = None, + slots: bool | None = None, + config: CoreConfig | None = None, +) -> DataclassSchema: + """ + Returns a schema for a dataclass. As with `ModelSchema`, this schema can only be used as a field within + another schema, not as the root type. + + Args: + cls: The dataclass type, used to perform subclass checks + schema: The schema to use for the dataclass fields + fields: Fields of the dataclass, this is used in serialization and in validation during re-validation + and while validating assignment + cls_name: The name to use in error locs, etc; this is useful for generics (default: `cls.__name__`) + post_init: Whether to call `__post_init__` after validation + revalidate_instances: whether instances of models and dataclasses (including subclass instances) + should re-validate defaults to config.revalidate_instances, else 'never' + strict: Whether to require an exact instance of `cls` + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + frozen: Whether the dataclass is frozen + slots: Whether `slots=True` on the dataclass, means each field is assigned independently, rather than + simply setting `__dict__`, default false + """ + return _dict_not_none( + type='dataclass', + cls=cls, + fields=fields, + cls_name=cls_name, + schema=schema, + post_init=post_init, + revalidate_instances=revalidate_instances, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + frozen=frozen, + slots=slots, + config=config, + ) + + +class ArgumentsParameter(TypedDict, total=False): + name: Required[str] + schema: Required[CoreSchema] + mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] # default positional_or_keyword + alias: Union[str, List[Union[str, int]], List[List[Union[str, int]]]] + + +def arguments_parameter( + name: str, + schema: CoreSchema, + *, + mode: Literal['positional_only', 'positional_or_keyword', 'keyword_only'] | None = None, + alias: str | list[str | int] | list[list[str | int]] | None = None, +) -> ArgumentsParameter: + """ + Returns a schema that matches an argument parameter, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + param = core_schema.arguments_parameter( + name='a', schema=core_schema.str_schema(), mode='positional_only' + ) + schema = core_schema.arguments_schema([param]) + v = SchemaValidator(schema) + assert v.validate_python(('hello',)) == (('hello',), {}) + ``` + + Args: + name: The name to use for the argument parameter + schema: The schema to use for the argument parameter + mode: The mode to use for the argument parameter + alias: The alias to use for the argument parameter + """ + return _dict_not_none(name=name, schema=schema, mode=mode, alias=alias) + + +class ArgumentsSchema(TypedDict, total=False): + type: Required[Literal['arguments']] + arguments_schema: Required[List[ArgumentsParameter]] + populate_by_name: bool + var_args_schema: CoreSchema + var_kwargs_schema: CoreSchema + ref: str + metadata: Any + serialization: SerSchema + + +def arguments_schema( + arguments: list[ArgumentsParameter], + *, + populate_by_name: bool | None = None, + var_args_schema: CoreSchema | None = None, + var_kwargs_schema: CoreSchema | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> ArgumentsSchema: + """ + Returns a schema that matches an arguments schema, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + param_a = core_schema.arguments_parameter( + name='a', schema=core_schema.str_schema(), mode='positional_only' + ) + param_b = core_schema.arguments_parameter( + name='b', schema=core_schema.bool_schema(), mode='positional_only' + ) + schema = core_schema.arguments_schema([param_a, param_b]) + v = SchemaValidator(schema) + assert v.validate_python(('hello', True)) == (('hello', True), {}) + ``` + + Args: + arguments: The arguments to use for the arguments schema + populate_by_name: Whether to populate by name + var_args_schema: The variable args schema to use for the arguments schema + var_kwargs_schema: The variable kwargs schema to use for the arguments schema + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='arguments', + arguments_schema=arguments, + populate_by_name=populate_by_name, + var_args_schema=var_args_schema, + var_kwargs_schema=var_kwargs_schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class CallSchema(TypedDict, total=False): + type: Required[Literal['call']] + arguments_schema: Required[CoreSchema] + function: Required[Callable[..., Any]] + function_name: str # default function.__name__ + return_schema: CoreSchema + ref: str + metadata: Any + serialization: SerSchema + + +def call_schema( + arguments: CoreSchema, + function: Callable[..., Any], + *, + function_name: str | None = None, + return_schema: CoreSchema | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> CallSchema: + """ + Returns a schema that matches an arguments schema, then calls a function, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + param_a = core_schema.arguments_parameter( + name='a', schema=core_schema.str_schema(), mode='positional_only' + ) + param_b = core_schema.arguments_parameter( + name='b', schema=core_schema.bool_schema(), mode='positional_only' + ) + args_schema = core_schema.arguments_schema([param_a, param_b]) + + schema = core_schema.call_schema( + arguments=args_schema, + function=lambda a, b: a + str(not b), + return_schema=core_schema.str_schema(), + ) + v = SchemaValidator(schema) + assert v.validate_python((('hello', True))) == 'helloFalse' + ``` + + Args: + arguments: The arguments to use for the arguments schema + function: The function to use for the call schema + function_name: The function name to use for the call schema, if not provided `function.__name__` is used + return_schema: The return schema to use for the call schema + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='call', + arguments_schema=arguments, + function=function, + function_name=function_name, + return_schema=return_schema, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class CustomErrorSchema(TypedDict, total=False): + type: Required[Literal['custom-error']] + schema: Required[CoreSchema] + custom_error_type: Required[str] + custom_error_message: str + custom_error_context: Dict[str, Union[str, int, float]] + ref: str + metadata: Any + serialization: SerSchema + + +def custom_error_schema( + schema: CoreSchema, + custom_error_type: str, + *, + custom_error_message: str | None = None, + custom_error_context: dict[str, Any] | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> CustomErrorSchema: + """ + Returns a schema that matches a custom error value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.custom_error_schema( + schema=core_schema.int_schema(), + custom_error_type='MyError', + custom_error_message='Error msg', + ) + v = SchemaValidator(schema) + v.validate_python(1) + ``` + + Args: + schema: The schema to use for the custom error schema + custom_error_type: The custom error type to use for the custom error schema + custom_error_message: The custom error message to use for the custom error schema + custom_error_context: The custom error context to use for the custom error schema + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='custom-error', + schema=schema, + custom_error_type=custom_error_type, + custom_error_message=custom_error_message, + custom_error_context=custom_error_context, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class JsonSchema(TypedDict, total=False): + type: Required[Literal['json']] + schema: CoreSchema + ref: str + metadata: Any + serialization: SerSchema + + +def json_schema( + schema: CoreSchema | None = None, + *, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> JsonSchema: + """ + Returns a schema that matches a JSON value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + dict_schema = core_schema.model_fields_schema( + { + 'field_a': core_schema.model_field(core_schema.str_schema()), + 'field_b': core_schema.model_field(core_schema.bool_schema()), + }, + ) + + class MyModel: + __slots__ = ( + '__dict__', + '__pydantic_fields_set__', + '__pydantic_extra__', + '__pydantic_private__', + ) + field_a: str + field_b: bool + + json_schema = core_schema.json_schema(schema=dict_schema) + schema = core_schema.model_schema(cls=MyModel, schema=json_schema) + v = SchemaValidator(schema) + m = v.validate_python('{"field_a": "hello", "field_b": true}') + assert isinstance(m, MyModel) + ``` + + Args: + schema: The schema to use for the JSON schema + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none(type='json', schema=schema, ref=ref, metadata=metadata, serialization=serialization) + + +class UrlSchema(TypedDict, total=False): + type: Required[Literal['url']] + max_length: int + allowed_schemes: List[str] + host_required: bool # default False + default_host: str + default_port: int + default_path: str + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def url_schema( + *, + max_length: int | None = None, + allowed_schemes: list[str] | None = None, + host_required: bool | None = None, + default_host: str | None = None, + default_port: int | None = None, + default_path: str | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> UrlSchema: + """ + Returns a schema that matches a URL value, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.url_schema() + v = SchemaValidator(schema) + print(v.validate_python('https://example.com')) + #> https://example.com/ + ``` + + Args: + max_length: The maximum length of the URL + allowed_schemes: The allowed URL schemes + host_required: Whether the URL must have a host + default_host: The default host to use if the URL does not have a host + default_port: The default port to use if the URL does not have a port + default_path: The default path to use if the URL does not have a path + strict: Whether to use strict URL parsing + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='url', + max_length=max_length, + allowed_schemes=allowed_schemes, + host_required=host_required, + default_host=default_host, + default_port=default_port, + default_path=default_path, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class MultiHostUrlSchema(TypedDict, total=False): + type: Required[Literal['multi-host-url']] + max_length: int + allowed_schemes: List[str] + host_required: bool # default False + default_host: str + default_port: int + default_path: str + strict: bool + ref: str + metadata: Any + serialization: SerSchema + + +def multi_host_url_schema( + *, + max_length: int | None = None, + allowed_schemes: list[str] | None = None, + host_required: bool | None = None, + default_host: str | None = None, + default_port: int | None = None, + default_path: str | None = None, + strict: bool | None = None, + ref: str | None = None, + metadata: Any = None, + serialization: SerSchema | None = None, +) -> MultiHostUrlSchema: + """ + Returns a schema that matches a URL value with possibly multiple hosts, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.multi_host_url_schema() + v = SchemaValidator(schema) + print(v.validate_python('redis://localhost,0.0.0.0,127.0.0.1')) + #> redis://localhost,0.0.0.0,127.0.0.1 + ``` + + Args: + max_length: The maximum length of the URL + allowed_schemes: The allowed URL schemes + host_required: Whether the URL must have a host + default_host: The default host to use if the URL does not have a host + default_port: The default port to use if the URL does not have a port + default_path: The default path to use if the URL does not have a path + strict: Whether to use strict URL parsing + ref: optional unique identifier of the schema, used to reference the schema in other places + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='multi-host-url', + max_length=max_length, + allowed_schemes=allowed_schemes, + host_required=host_required, + default_host=default_host, + default_port=default_port, + default_path=default_path, + strict=strict, + ref=ref, + metadata=metadata, + serialization=serialization, + ) + + +class DefinitionsSchema(TypedDict, total=False): + type: Required[Literal['definitions']] + schema: Required[CoreSchema] + definitions: Required[List[CoreSchema]] + metadata: Any + serialization: SerSchema + + +def definitions_schema(schema: CoreSchema, definitions: list[CoreSchema]) -> DefinitionsSchema: + """ + Build a schema that contains both an inner schema and a list of definitions which can be used + within the inner schema. + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema = core_schema.definitions_schema( + core_schema.list_schema(core_schema.definition_reference_schema('foobar')), + [core_schema.int_schema(ref='foobar')], + ) + v = SchemaValidator(schema) + assert v.validate_python([1, 2, '3']) == [1, 2, 3] + ``` + + Args: + schema: The inner schema + definitions: List of definitions which can be referenced within inner schema + """ + return DefinitionsSchema(type='definitions', schema=schema, definitions=definitions) + + +class DefinitionReferenceSchema(TypedDict, total=False): + type: Required[Literal['definition-ref']] + schema_ref: Required[str] + ref: str + metadata: Any + serialization: SerSchema + + +def definition_reference_schema( + schema_ref: str, ref: str | None = None, metadata: Any = None, serialization: SerSchema | None = None +) -> DefinitionReferenceSchema: + """ + Returns a schema that points to a schema stored in "definitions", this is useful for nested recursive + models and also when you want to define validators separately from the main schema, e.g.: + + ```py + from pydantic_core import SchemaValidator, core_schema + + schema_definition = core_schema.definition_reference_schema('list-schema') + schema = core_schema.definitions_schema( + schema=schema_definition, + definitions=[ + core_schema.list_schema(items_schema=schema_definition, ref='list-schema'), + ], + ) + v = SchemaValidator(schema) + assert v.validate_python([()]) == [[]] + ``` + + Args: + schema_ref: The schema ref to use for the definition reference schema + metadata: Any other information you want to include with the schema, not used by pydantic-core + serialization: Custom serialization schema + """ + return _dict_not_none( + type='definition-ref', schema_ref=schema_ref, ref=ref, metadata=metadata, serialization=serialization + ) + + +MYPY = False +# See https://github.com/python/mypy/issues/14034 for details, in summary mypy is extremely slow to process this +# union which kills performance not just for pydantic, but even for code using pydantic +if not MYPY: + CoreSchema = Union[ + AnySchema, + NoneSchema, + BoolSchema, + IntSchema, + FloatSchema, + DecimalSchema, + StringSchema, + BytesSchema, + DateSchema, + TimeSchema, + DatetimeSchema, + TimedeltaSchema, + LiteralSchema, + EnumSchema, + IsInstanceSchema, + IsSubclassSchema, + CallableSchema, + ListSchema, + TupleSchema, + SetSchema, + FrozenSetSchema, + GeneratorSchema, + DictSchema, + AfterValidatorFunctionSchema, + BeforeValidatorFunctionSchema, + WrapValidatorFunctionSchema, + PlainValidatorFunctionSchema, + WithDefaultSchema, + NullableSchema, + UnionSchema, + TaggedUnionSchema, + ChainSchema, + LaxOrStrictSchema, + JsonOrPythonSchema, + TypedDictSchema, + ModelFieldsSchema, + ModelSchema, + DataclassArgsSchema, + DataclassSchema, + ArgumentsSchema, + CallSchema, + CustomErrorSchema, + JsonSchema, + UrlSchema, + MultiHostUrlSchema, + DefinitionsSchema, + DefinitionReferenceSchema, + UuidSchema, + ] +elif False: + CoreSchema: TypeAlias = Mapping[str, Any] + + +# to update this, call `pytest -k test_core_schema_type_literal` and copy the output +CoreSchemaType = Literal[ + 'any', + 'none', + 'bool', + 'int', + 'float', + 'decimal', + 'str', + 'bytes', + 'date', + 'time', + 'datetime', + 'timedelta', + 'literal', + 'enum', + 'is-instance', + 'is-subclass', + 'callable', + 'list', + 'tuple', + 'set', + 'frozenset', + 'generator', + 'dict', + 'function-after', + 'function-before', + 'function-wrap', + 'function-plain', + 'default', + 'nullable', + 'union', + 'tagged-union', + 'chain', + 'lax-or-strict', + 'json-or-python', + 'typed-dict', + 'model-fields', + 'model', + 'dataclass-args', + 'dataclass', + 'arguments', + 'call', + 'custom-error', + 'json', + 'url', + 'multi-host-url', + 'definitions', + 'definition-ref', + 'uuid', +] + +CoreSchemaFieldType = Literal['model-field', 'dataclass-field', 'typed-dict-field', 'computed-field'] + + +# used in _pydantic_core.pyi::PydanticKnownError +# to update this, call `pytest -k test_all_errors` and copy the output +ErrorType = Literal[ + 'no_such_attribute', + 'json_invalid', + 'json_type', + 'recursion_loop', + 'missing', + 'frozen_field', + 'frozen_instance', + 'extra_forbidden', + 'invalid_key', + 'get_attribute_error', + 'model_type', + 'model_attributes_type', + 'dataclass_type', + 'dataclass_exact_type', + 'none_required', + 'greater_than', + 'greater_than_equal', + 'less_than', + 'less_than_equal', + 'multiple_of', + 'finite_number', + 'too_short', + 'too_long', + 'iterable_type', + 'iteration_error', + 'string_type', + 'string_sub_type', + 'string_unicode', + 'string_too_short', + 'string_too_long', + 'string_pattern_mismatch', + 'enum', + 'dict_type', + 'mapping_type', + 'list_type', + 'tuple_type', + 'set_type', + 'bool_type', + 'bool_parsing', + 'int_type', + 'int_parsing', + 'int_parsing_size', + 'int_from_float', + 'float_type', + 'float_parsing', + 'bytes_type', + 'bytes_too_short', + 'bytes_too_long', + 'value_error', + 'assertion_error', + 'literal_error', + 'date_type', + 'date_parsing', + 'date_from_datetime_parsing', + 'date_from_datetime_inexact', + 'date_past', + 'date_future', + 'time_type', + 'time_parsing', + 'datetime_type', + 'datetime_parsing', + 'datetime_object_invalid', + 'datetime_from_date_parsing', + 'datetime_past', + 'datetime_future', + 'timezone_naive', + 'timezone_aware', + 'timezone_offset', + 'time_delta_type', + 'time_delta_parsing', + 'frozen_set_type', + 'is_instance_of', + 'is_subclass_of', + 'callable_type', + 'union_tag_invalid', + 'union_tag_not_found', + 'arguments_type', + 'missing_argument', + 'unexpected_keyword_argument', + 'missing_keyword_only_argument', + 'unexpected_positional_argument', + 'missing_positional_only_argument', + 'multiple_argument_values', + 'url_type', + 'url_parsing', + 'url_syntax_violation', + 'url_too_long', + 'url_scheme', + 'uuid_type', + 'uuid_parsing', + 'uuid_version', + 'decimal_type', + 'decimal_parsing', + 'decimal_max_digits', + 'decimal_max_places', + 'decimal_whole_digits', +] + + +def _dict_not_none(**kwargs: Any) -> Any: + return {k: v for k, v in kwargs.items() if v is not None} + + +############################################################################### +# All this stuff is deprecated by #980 and will be removed eventually +# They're kept because some code external code will be using them + + +@deprecated('`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.') +def field_before_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs): + warnings.warn( + '`field_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.', + DeprecationWarning, + ) + return with_info_before_validator_function(function, schema, field_name=field_name, **kwargs) + + +@deprecated('`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.') +def general_before_validator_function(*args, **kwargs): + warnings.warn( + '`general_before_validator_function` is deprecated, use `with_info_before_validator_function` instead.', + DeprecationWarning, + ) + return with_info_before_validator_function(*args, **kwargs) + + +@deprecated('`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.') +def field_after_validator_function(function: WithInfoValidatorFunction, field_name: str, schema: CoreSchema, **kwargs): + warnings.warn( + '`field_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.', + DeprecationWarning, + ) + return with_info_after_validator_function(function, schema, field_name=field_name, **kwargs) + + +@deprecated('`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.') +def general_after_validator_function(*args, **kwargs): + warnings.warn( + '`general_after_validator_function` is deprecated, use `with_info_after_validator_function` instead.', + DeprecationWarning, + ) + return with_info_after_validator_function(*args, **kwargs) + + +@deprecated('`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.') +def field_wrap_validator_function( + function: WithInfoWrapValidatorFunction, field_name: str, schema: CoreSchema, **kwargs +): + warnings.warn( + '`field_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.', + DeprecationWarning, + ) + return with_info_wrap_validator_function(function, schema, field_name=field_name, **kwargs) + + +@deprecated('`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.') +def general_wrap_validator_function(*args, **kwargs): + warnings.warn( + '`general_wrap_validator_function` is deprecated, use `with_info_wrap_validator_function` instead.', + DeprecationWarning, + ) + return with_info_wrap_validator_function(*args, **kwargs) + + +@deprecated('`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.') +def field_plain_validator_function(function: WithInfoValidatorFunction, field_name: str, **kwargs): + warnings.warn( + '`field_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.', + DeprecationWarning, + ) + return with_info_plain_validator_function(function, field_name=field_name, **kwargs) + + +@deprecated('`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.') +def general_plain_validator_function(*args, **kwargs): + warnings.warn( + '`general_plain_validator_function` is deprecated, use `with_info_plain_validator_function` instead.', + DeprecationWarning, + ) + return with_info_plain_validator_function(*args, **kwargs) + + +_deprecated_import_lookup = { + 'FieldValidationInfo': ValidationInfo, + 'FieldValidatorFunction': WithInfoValidatorFunction, + 'GeneralValidatorFunction': WithInfoValidatorFunction, + 'FieldWrapValidatorFunction': WithInfoWrapValidatorFunction, +} + +if TYPE_CHECKING: + FieldValidationInfo = ValidationInfo + + +def __getattr__(attr_name: str) -> object: + new_attr = _deprecated_import_lookup.get(attr_name) + if new_attr is None: + raise AttributeError(f"module 'pydantic_core' has no attribute '{attr_name}'") + else: + import warnings + + msg = f'`{attr_name}` is deprecated, use `{new_attr.__name__}` instead.' + warnings.warn(msg, DeprecationWarning, stacklevel=1) + return new_attr diff --git a/env/Lib/site-packages/pydantic_core/py.typed b/env/Lib/site-packages/pydantic_core/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/INSTALLER b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/LICENSE b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/LICENSE new file mode 100644 index 0000000..f26bcf4 --- /dev/null +++ b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/LICENSE @@ -0,0 +1,279 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/METADATA b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/METADATA new file mode 100644 index 0000000..f15e2b3 --- /dev/null +++ b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/METADATA @@ -0,0 +1,67 @@ +Metadata-Version: 2.1 +Name: typing_extensions +Version: 4.12.2 +Summary: Backported and Experimental Type Hints for Python 3.8+ +Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing +Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" +Requires-Python: >=3.8 +Description-Content-Type: text/markdown +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Python Software Foundation License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Software Development +Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues +Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md +Project-URL: Documentation, https://typing-extensions.readthedocs.io/ +Project-URL: Home, https://github.com/python/typing_extensions +Project-URL: Q & A, https://github.com/python/typing/discussions +Project-URL: Repository, https://github.com/python/typing_extensions + +# Typing Extensions + +[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing) + +[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) – +[PyPI](https://pypi.org/project/typing-extensions/) + +## Overview + +The `typing_extensions` module serves two related purposes: + +- Enable use of new type system features on older Python versions. For example, + `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows + users on previous Python versions to use it too. +- Enable experimentation with new type system PEPs before they are accepted and + added to the `typing` module. + +`typing_extensions` is treated specially by static type checkers such as +mypy and pyright. Objects defined in `typing_extensions` are treated the same +way as equivalent forms in `typing`. + +`typing_extensions` uses +[Semantic Versioning](https://semver.org/). The +major version will be incremented only for backwards-incompatible changes. +Therefore, it's safe to depend +on `typing_extensions` like this: `typing_extensions >=x.y, <(x+1)`, +where `x.y` is the first version that includes all features you need. + +## Included items + +See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for a +complete listing of module contents. + +## Contributing + +See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md) +for how to contribute to `typing_extensions`. + diff --git a/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/RECORD b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/RECORD new file mode 100644 index 0000000..c4f0038 --- /dev/null +++ b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/RECORD @@ -0,0 +1,7 @@ +__pycache__/typing_extensions.cpython-311.pyc,, +typing_extensions-4.12.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +typing_extensions-4.12.2.dist-info/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936 +typing_extensions-4.12.2.dist-info/METADATA,sha256=BeUQIa8cnYbrjWx-N8TOznM9UGW5Gm2DicVpDtRA8W0,3018 +typing_extensions-4.12.2.dist-info/RECORD,, +typing_extensions-4.12.2.dist-info/WHEEL,sha256=EZbGkh7Ie4PoZfRQ8I0ZuP9VklN_TvcZ6DSE5Uar4z4,81 +typing_extensions.py,sha256=gwekpyG9DVG3lxWKX4ni8u7nk3We5slG98mA9F3DJQw,134451 diff --git a/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/WHEEL b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/WHEEL new file mode 100644 index 0000000..3b5e64b --- /dev/null +++ b/env/Lib/site-packages/typing_extensions-4.12.2.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.9.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/env/Lib/site-packages/typing_extensions.py b/env/Lib/site-packages/typing_extensions.py new file mode 100644 index 0000000..dec429c --- /dev/null +++ b/env/Lib/site-packages/typing_extensions.py @@ -0,0 +1,3641 @@ +import abc +import collections +import collections.abc +import contextlib +import functools +import inspect +import operator +import sys +import types as _types +import typing +import warnings + +__all__ = [ + # Super-special typing primitives. + 'Any', + 'ClassVar', + 'Concatenate', + 'Final', + 'LiteralString', + 'ParamSpec', + 'ParamSpecArgs', + 'ParamSpecKwargs', + 'Self', + 'Type', + 'TypeVar', + 'TypeVarTuple', + 'Unpack', + + # ABCs (from collections.abc). + 'Awaitable', + 'AsyncIterator', + 'AsyncIterable', + 'Coroutine', + 'AsyncGenerator', + 'AsyncContextManager', + 'Buffer', + 'ChainMap', + + # Concrete collection types. + 'ContextManager', + 'Counter', + 'Deque', + 'DefaultDict', + 'NamedTuple', + 'OrderedDict', + 'TypedDict', + + # Structural checks, a.k.a. protocols. + 'SupportsAbs', + 'SupportsBytes', + 'SupportsComplex', + 'SupportsFloat', + 'SupportsIndex', + 'SupportsInt', + 'SupportsRound', + + # One-off things. + 'Annotated', + 'assert_never', + 'assert_type', + 'clear_overloads', + 'dataclass_transform', + 'deprecated', + 'Doc', + 'get_overloads', + 'final', + 'get_args', + 'get_origin', + 'get_original_bases', + 'get_protocol_members', + 'get_type_hints', + 'IntVar', + 'is_protocol', + 'is_typeddict', + 'Literal', + 'NewType', + 'overload', + 'override', + 'Protocol', + 'reveal_type', + 'runtime', + 'runtime_checkable', + 'Text', + 'TypeAlias', + 'TypeAliasType', + 'TypeGuard', + 'TypeIs', + 'TYPE_CHECKING', + 'Never', + 'NoReturn', + 'ReadOnly', + 'Required', + 'NotRequired', + + # Pure aliases, have always been in typing + 'AbstractSet', + 'AnyStr', + 'BinaryIO', + 'Callable', + 'Collection', + 'Container', + 'Dict', + 'ForwardRef', + 'FrozenSet', + 'Generator', + 'Generic', + 'Hashable', + 'IO', + 'ItemsView', + 'Iterable', + 'Iterator', + 'KeysView', + 'List', + 'Mapping', + 'MappingView', + 'Match', + 'MutableMapping', + 'MutableSequence', + 'MutableSet', + 'NoDefault', + 'Optional', + 'Pattern', + 'Reversible', + 'Sequence', + 'Set', + 'Sized', + 'TextIO', + 'Tuple', + 'Union', + 'ValuesView', + 'cast', + 'no_type_check', + 'no_type_check_decorator', +] + +# for backward compatibility +PEP_560 = True +GenericMeta = type +_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta") + +# The functions below are modified copies of typing internal helpers. +# They are needed by _ProtocolMeta and they provide support for PEP 646. + + +class _Sentinel: + def __repr__(self): + return "" + + +_marker = _Sentinel() + + +if sys.version_info >= (3, 10): + def _should_collect_from_parameters(t): + return isinstance( + t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) + ) +elif sys.version_info >= (3, 9): + def _should_collect_from_parameters(t): + return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) +else: + def _should_collect_from_parameters(t): + return isinstance(t, typing._GenericAlias) and not t._special + + +NoReturn = typing.NoReturn + +# Some unconstrained type variables. These are used by the container types. +# (These are not for export.) +T = typing.TypeVar('T') # Any type. +KT = typing.TypeVar('KT') # Key type. +VT = typing.TypeVar('VT') # Value type. +T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. +T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. + + +if sys.version_info >= (3, 11): + from typing import Any +else: + + class _AnyMeta(type): + def __instancecheck__(self, obj): + if self is Any: + raise TypeError("typing_extensions.Any cannot be used with isinstance()") + return super().__instancecheck__(obj) + + def __repr__(self): + if self is Any: + return "typing_extensions.Any" + return super().__repr__() + + class Any(metaclass=_AnyMeta): + """Special type indicating an unconstrained type. + - Any is compatible with every type. + - Any assumed to have all methods. + - All values assumed to be instances of Any. + Note that all the above statements are true from the point of view of + static type checkers. At runtime, Any should not be used with instance + checks. + """ + def __new__(cls, *args, **kwargs): + if cls is Any: + raise TypeError("Any cannot be instantiated") + return super().__new__(cls, *args, **kwargs) + + +ClassVar = typing.ClassVar + + +class _ExtensionsSpecialForm(typing._SpecialForm, _root=True): + def __repr__(self): + return 'typing_extensions.' + self._name + + +Final = typing.Final + +if sys.version_info >= (3, 11): + final = typing.final +else: + # @final exists in 3.8+, but we backport it for all versions + # before 3.11 to keep support for the __final__ attribute. + # See https://bugs.python.org/issue46342 + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + sets the ``__final__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + +def IntVar(name): + return typing.TypeVar(name) + + +# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8 +if sys.version_info >= (3, 10, 1): + Literal = typing.Literal +else: + def _flatten_literal_params(parameters): + """An internal helper for Literal creation: flatten Literals among parameters""" + params = [] + for p in parameters: + if isinstance(p, _LiteralGenericAlias): + params.extend(p.__args__) + else: + params.append(p) + return tuple(params) + + def _value_and_type_iter(params): + for p in params: + yield p, type(p) + + class _LiteralGenericAlias(typing._GenericAlias, _root=True): + def __eq__(self, other): + if not isinstance(other, _LiteralGenericAlias): + return NotImplemented + these_args_deduped = set(_value_and_type_iter(self.__args__)) + other_args_deduped = set(_value_and_type_iter(other.__args__)) + return these_args_deduped == other_args_deduped + + def __hash__(self): + return hash(frozenset(_value_and_type_iter(self.__args__))) + + class _LiteralForm(_ExtensionsSpecialForm, _root=True): + def __init__(self, doc: str): + self._name = 'Literal' + self._doc = self.__doc__ = doc + + def __getitem__(self, parameters): + if not isinstance(parameters, tuple): + parameters = (parameters,) + + parameters = _flatten_literal_params(parameters) + + val_type_pairs = list(_value_and_type_iter(parameters)) + try: + deduped_pairs = set(val_type_pairs) + except TypeError: + # unhashable parameters + pass + else: + # similar logic to typing._deduplicate on Python 3.9+ + if len(deduped_pairs) < len(val_type_pairs): + new_parameters = [] + for pair in val_type_pairs: + if pair in deduped_pairs: + new_parameters.append(pair[0]) + deduped_pairs.remove(pair) + assert not deduped_pairs, deduped_pairs + parameters = tuple(new_parameters) + + return _LiteralGenericAlias(self, parameters) + + Literal = _LiteralForm(doc="""\ + A type that can be used to indicate to type checkers + that the corresponding value has a value literally equivalent + to the provided parameter. For example: + + var: Literal[4] = 4 + + The type checker understands that 'var' is literally equal to + the value 4 and no other value. + + Literal[...] cannot be subclassed. There is no runtime + checking verifying that the parameter is actually a value + instead of a type.""") + + +_overload_dummy = typing._overload_dummy + + +if hasattr(typing, "get_overloads"): # 3.11+ + overload = typing.overload + get_overloads = typing.get_overloads + clear_overloads = typing.clear_overloads +else: + # {module: {qualname: {firstlineno: func}}} + _overload_registry = collections.defaultdict( + functools.partial(collections.defaultdict, dict) + ) + + def overload(func): + """Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + # implementation goes here + + The overloads for a function can be retrieved at runtime using the + get_overloads() function. + """ + # classmethod and staticmethod + f = getattr(func, "__func__", func) + try: + _overload_registry[f.__module__][f.__qualname__][ + f.__code__.co_firstlineno + ] = func + except AttributeError: + # Not a normal function; ignore. + pass + return _overload_dummy + + def get_overloads(func): + """Return all defined overloads for *func* as a sequence.""" + # classmethod and staticmethod + f = getattr(func, "__func__", func) + if f.__module__ not in _overload_registry: + return [] + mod_dict = _overload_registry[f.__module__] + if f.__qualname__ not in mod_dict: + return [] + return list(mod_dict[f.__qualname__].values()) + + def clear_overloads(): + """Clear all overloads in the registry.""" + _overload_registry.clear() + + +# This is not a real generic class. Don't use outside annotations. +Type = typing.Type + +# Various ABCs mimicking those in collections.abc. +# A few are simply re-exported for completeness. +Awaitable = typing.Awaitable +Coroutine = typing.Coroutine +AsyncIterable = typing.AsyncIterable +AsyncIterator = typing.AsyncIterator +Deque = typing.Deque +DefaultDict = typing.DefaultDict +OrderedDict = typing.OrderedDict +Counter = typing.Counter +ChainMap = typing.ChainMap +Text = typing.Text +TYPE_CHECKING = typing.TYPE_CHECKING + + +if sys.version_info >= (3, 13, 0, "beta"): + from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator +else: + def _is_dunder(attr): + return attr.startswith('__') and attr.endswith('__') + + # Python <3.9 doesn't have typing._SpecialGenericAlias + _special_generic_alias_base = getattr( + typing, "_SpecialGenericAlias", typing._GenericAlias + ) + + class _SpecialGenericAlias(_special_generic_alias_base, _root=True): + def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()): + if _special_generic_alias_base is typing._GenericAlias: + # Python <3.9 + self.__origin__ = origin + self._nparams = nparams + super().__init__(origin, nparams, special=True, inst=inst, name=name) + else: + # Python >= 3.9 + super().__init__(origin, nparams, inst=inst, name=name) + self._defaults = defaults + + def __setattr__(self, attr, val): + allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'} + if _special_generic_alias_base is typing._GenericAlias: + # Python <3.9 + allowed_attrs.add("__origin__") + if _is_dunder(attr) or attr in allowed_attrs: + object.__setattr__(self, attr, val) + else: + setattr(self.__origin__, attr, val) + + @typing._tp_cache + def __getitem__(self, params): + if not isinstance(params, tuple): + params = (params,) + msg = "Parameters to generic types must be types." + params = tuple(typing._type_check(p, msg) for p in params) + if ( + self._defaults + and len(params) < self._nparams + and len(params) + len(self._defaults) >= self._nparams + ): + params = (*params, *self._defaults[len(params) - self._nparams:]) + actual_len = len(params) + + if actual_len != self._nparams: + if self._defaults: + expected = f"at least {self._nparams - len(self._defaults)}" + else: + expected = str(self._nparams) + if not self._nparams: + raise TypeError(f"{self} is not a generic class") + raise TypeError( + f"Too {'many' if actual_len > self._nparams else 'few'}" + f" arguments for {self};" + f" actual {actual_len}, expected {expected}" + ) + return self.copy_with(params) + + _NoneType = type(None) + Generator = _SpecialGenericAlias( + collections.abc.Generator, 3, defaults=(_NoneType, _NoneType) + ) + AsyncGenerator = _SpecialGenericAlias( + collections.abc.AsyncGenerator, 2, defaults=(_NoneType,) + ) + ContextManager = _SpecialGenericAlias( + contextlib.AbstractContextManager, + 2, + name="ContextManager", + defaults=(typing.Optional[bool],) + ) + AsyncContextManager = _SpecialGenericAlias( + contextlib.AbstractAsyncContextManager, + 2, + name="AsyncContextManager", + defaults=(typing.Optional[bool],) + ) + + +_PROTO_ALLOWLIST = { + 'collections.abc': [ + 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', + 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer', + ], + 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], + 'typing_extensions': ['Buffer'], +} + + +_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | { + "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__", + "__final__", +} + + +def _get_protocol_attrs(cls): + attrs = set() + for base in cls.__mro__[:-1]: # without object + if base.__name__ in {'Protocol', 'Generic'}: + continue + annotations = getattr(base, '__annotations__', {}) + for attr in (*base.__dict__, *annotations): + if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS): + attrs.add(attr) + return attrs + + +def _caller(depth=2): + try: + return sys._getframe(depth).f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): # For platforms without _getframe() + return None + + +# `__match_args__` attribute was removed from protocol members in 3.13, +# we want to backport this change to older Python versions. +if sys.version_info >= (3, 13): + Protocol = typing.Protocol +else: + def _allow_reckless_class_checks(depth=3): + """Allow instance and class checks for special stdlib modules. + The abc and functools modules indiscriminately call isinstance() and + issubclass() on the whole MRO of a user class, which may contain protocols. + """ + return _caller(depth) in {'abc', 'functools', None} + + def _no_init(self, *args, **kwargs): + if type(self)._is_protocol: + raise TypeError('Protocols cannot be instantiated') + + def _type_check_issubclass_arg_1(arg): + """Raise TypeError if `arg` is not an instance of `type` + in `issubclass(arg, )`. + + In most cases, this is verified by type.__subclasscheck__. + Checking it again unnecessarily would slow down issubclass() checks, + so, we don't perform this check unless we absolutely have to. + + For various error paths, however, + we want to ensure that *this* error message is shown to the user + where relevant, rather than a typing.py-specific error message. + """ + if not isinstance(arg, type): + # Same error message as for issubclass(1, int). + raise TypeError('issubclass() arg 1 must be a class') + + # Inheriting from typing._ProtocolMeta isn't actually desirable, + # but is necessary to allow typing.Protocol and typing_extensions.Protocol + # to mix without getting TypeErrors about "metaclass conflict" + class _ProtocolMeta(type(typing.Protocol)): + # This metaclass is somewhat unfortunate, + # but is necessary for several reasons... + # + # NOTE: DO NOT call super() in any methods in this class + # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11 + # and those are slow + def __new__(mcls, name, bases, namespace, **kwargs): + if name == "Protocol" and len(bases) < 2: + pass + elif {Protocol, typing.Protocol} & set(bases): + for base in bases: + if not ( + base in {object, typing.Generic, Protocol, typing.Protocol} + or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, []) + or is_protocol(base) + ): + raise TypeError( + f"Protocols can only inherit from other protocols, " + f"got {base!r}" + ) + return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs) + + def __init__(cls, *args, **kwargs): + abc.ABCMeta.__init__(cls, *args, **kwargs) + if getattr(cls, "_is_protocol", False): + cls.__protocol_attrs__ = _get_protocol_attrs(cls) + + def __subclasscheck__(cls, other): + if cls is Protocol: + return type.__subclasscheck__(cls, other) + if ( + getattr(cls, '_is_protocol', False) + and not _allow_reckless_class_checks() + ): + if not getattr(cls, '_is_runtime_protocol', False): + _type_check_issubclass_arg_1(other) + raise TypeError( + "Instance and class checks can only be used with " + "@runtime_checkable protocols" + ) + if ( + # this attribute is set by @runtime_checkable: + cls.__non_callable_proto_members__ + and cls.__dict__.get("__subclasshook__") is _proto_hook + ): + _type_check_issubclass_arg_1(other) + non_method_attrs = sorted(cls.__non_callable_proto_members__) + raise TypeError( + "Protocols with non-method members don't support issubclass()." + f" Non-method members: {str(non_method_attrs)[1:-1]}." + ) + return abc.ABCMeta.__subclasscheck__(cls, other) + + def __instancecheck__(cls, instance): + # We need this method for situations where attributes are + # assigned in __init__. + if cls is Protocol: + return type.__instancecheck__(cls, instance) + if not getattr(cls, "_is_protocol", False): + # i.e., it's a concrete subclass of a protocol + return abc.ABCMeta.__instancecheck__(cls, instance) + + if ( + not getattr(cls, '_is_runtime_protocol', False) and + not _allow_reckless_class_checks() + ): + raise TypeError("Instance and class checks can only be used with" + " @runtime_checkable protocols") + + if abc.ABCMeta.__instancecheck__(cls, instance): + return True + + for attr in cls.__protocol_attrs__: + try: + val = inspect.getattr_static(instance, attr) + except AttributeError: + break + # this attribute is set by @runtime_checkable: + if val is None and attr not in cls.__non_callable_proto_members__: + break + else: + return True + + return False + + def __eq__(cls, other): + # Hack so that typing.Generic.__class_getitem__ + # treats typing_extensions.Protocol + # as equivalent to typing.Protocol + if abc.ABCMeta.__eq__(cls, other) is True: + return True + return cls is Protocol and other is typing.Protocol + + # This has to be defined, or the abc-module cache + # complains about classes with this metaclass being unhashable, + # if we define only __eq__! + def __hash__(cls) -> int: + return type.__hash__(cls) + + @classmethod + def _proto_hook(cls, other): + if not cls.__dict__.get('_is_protocol', False): + return NotImplemented + + for attr in cls.__protocol_attrs__: + for base in other.__mro__: + # Check if the members appears in the class dictionary... + if attr in base.__dict__: + if base.__dict__[attr] is None: + return NotImplemented + break + + # ...or in annotations, if it is a sub-protocol. + annotations = getattr(base, '__annotations__', {}) + if ( + isinstance(annotations, collections.abc.Mapping) + and attr in annotations + and is_protocol(other) + ): + break + else: + return NotImplemented + return True + + class Protocol(typing.Generic, metaclass=_ProtocolMeta): + __doc__ = typing.Protocol.__doc__ + __slots__ = () + _is_protocol = True + _is_runtime_protocol = False + + def __init_subclass__(cls, *args, **kwargs): + super().__init_subclass__(*args, **kwargs) + + # Determine if this is a protocol or a concrete subclass. + if not cls.__dict__.get('_is_protocol', False): + cls._is_protocol = any(b is Protocol for b in cls.__bases__) + + # Set (or override) the protocol subclass hook. + if '__subclasshook__' not in cls.__dict__: + cls.__subclasshook__ = _proto_hook + + # Prohibit instantiation for protocol classes + if cls._is_protocol and cls.__init__ is Protocol.__init__: + cls.__init__ = _no_init + + +if sys.version_info >= (3, 13): + runtime_checkable = typing.runtime_checkable +else: + def runtime_checkable(cls): + """Mark a protocol class as a runtime protocol. + + Such protocol can be used with isinstance() and issubclass(). + Raise TypeError if applied to a non-protocol class. + This allows a simple-minded structural check very similar to + one trick ponies in collections.abc such as Iterable. + + For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + Warning: this will check only the presence of the required methods, + not their type signatures! + """ + if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False): + raise TypeError(f'@runtime_checkable can be only applied to protocol classes,' + f' got {cls!r}') + cls._is_runtime_protocol = True + + # typing.Protocol classes on <=3.11 break if we execute this block, + # because typing.Protocol classes on <=3.11 don't have a + # `__protocol_attrs__` attribute, and this block relies on the + # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+ + # break if we *don't* execute this block, because *they* assume that all + # protocol classes have a `__non_callable_proto_members__` attribute + # (which this block sets) + if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2): + # PEP 544 prohibits using issubclass() + # with protocols that have non-method members. + # See gh-113320 for why we compute this attribute here, + # rather than in `_ProtocolMeta.__init__` + cls.__non_callable_proto_members__ = set() + for attr in cls.__protocol_attrs__: + try: + is_callable = callable(getattr(cls, attr, None)) + except Exception as e: + raise TypeError( + f"Failed to determine whether protocol member {attr!r} " + "is a method member" + ) from e + else: + if not is_callable: + cls.__non_callable_proto_members__.add(attr) + + return cls + + +# The "runtime" alias exists for backwards compatibility. +runtime = runtime_checkable + + +# Our version of runtime-checkable protocols is faster on Python 3.8-3.11 +if sys.version_info >= (3, 12): + SupportsInt = typing.SupportsInt + SupportsFloat = typing.SupportsFloat + SupportsComplex = typing.SupportsComplex + SupportsBytes = typing.SupportsBytes + SupportsIndex = typing.SupportsIndex + SupportsAbs = typing.SupportsAbs + SupportsRound = typing.SupportsRound +else: + @runtime_checkable + class SupportsInt(Protocol): + """An ABC with one abstract method __int__.""" + __slots__ = () + + @abc.abstractmethod + def __int__(self) -> int: + pass + + @runtime_checkable + class SupportsFloat(Protocol): + """An ABC with one abstract method __float__.""" + __slots__ = () + + @abc.abstractmethod + def __float__(self) -> float: + pass + + @runtime_checkable + class SupportsComplex(Protocol): + """An ABC with one abstract method __complex__.""" + __slots__ = () + + @abc.abstractmethod + def __complex__(self) -> complex: + pass + + @runtime_checkable + class SupportsBytes(Protocol): + """An ABC with one abstract method __bytes__.""" + __slots__ = () + + @abc.abstractmethod + def __bytes__(self) -> bytes: + pass + + @runtime_checkable + class SupportsIndex(Protocol): + __slots__ = () + + @abc.abstractmethod + def __index__(self) -> int: + pass + + @runtime_checkable + class SupportsAbs(Protocol[T_co]): + """ + An ABC with one abstract method __abs__ that is covariant in its return type. + """ + __slots__ = () + + @abc.abstractmethod + def __abs__(self) -> T_co: + pass + + @runtime_checkable + class SupportsRound(Protocol[T_co]): + """ + An ABC with one abstract method __round__ that is covariant in its return type. + """ + __slots__ = () + + @abc.abstractmethod + def __round__(self, ndigits: int = 0) -> T_co: + pass + + +def _ensure_subclassable(mro_entries): + def inner(func): + if sys.implementation.name == "pypy" and sys.version_info < (3, 9): + cls_dict = { + "__call__": staticmethod(func), + "__mro_entries__": staticmethod(mro_entries) + } + t = type(func.__name__, (), cls_dict) + return functools.update_wrapper(t(), func) + else: + func.__mro_entries__ = mro_entries + return func + return inner + + +# Update this to something like >=3.13.0b1 if and when +# PEP 728 is implemented in CPython +_PEP_728_IMPLEMENTED = False + +if _PEP_728_IMPLEMENTED: + # The standard library TypedDict in Python 3.8 does not store runtime information + # about which (if any) keys are optional. See https://bugs.python.org/issue38834 + # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" + # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 + # The standard library TypedDict below Python 3.11 does not store runtime + # information about optional and required keys when using Required or NotRequired. + # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. + # Aaaand on 3.12 we add __orig_bases__ to TypedDict + # to enable better runtime introspection. + # On 3.13 we deprecate some odd ways of creating TypedDicts. + # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier. + # PEP 728 (still pending) makes more changes. + TypedDict = typing.TypedDict + _TypedDictMeta = typing._TypedDictMeta + is_typeddict = typing.is_typeddict +else: + # 3.10.0 and later + _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters + + def _get_typeddict_qualifiers(annotation_type): + while True: + annotation_origin = get_origin(annotation_type) + if annotation_origin is Annotated: + annotation_args = get_args(annotation_type) + if annotation_args: + annotation_type = annotation_args[0] + else: + break + elif annotation_origin is Required: + yield Required + annotation_type, = get_args(annotation_type) + elif annotation_origin is NotRequired: + yield NotRequired + annotation_type, = get_args(annotation_type) + elif annotation_origin is ReadOnly: + yield ReadOnly + annotation_type, = get_args(annotation_type) + else: + break + + class _TypedDictMeta(type): + def __new__(cls, name, bases, ns, *, total=True, closed=False): + """Create new typed dict class object. + + This method is called when TypedDict is subclassed, + or when TypedDict is instantiated. This way + TypedDict supports all three syntax forms described in its docstring. + Subclasses and instances of TypedDict return actual dictionaries. + """ + for base in bases: + if type(base) is not _TypedDictMeta and base is not typing.Generic: + raise TypeError('cannot inherit from both a TypedDict type ' + 'and a non-TypedDict base class') + + if any(issubclass(b, typing.Generic) for b in bases): + generic_base = (typing.Generic,) + else: + generic_base = () + + # typing.py generally doesn't let you inherit from plain Generic, unless + # the name of the class happens to be "Protocol" + tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns) + tp_dict.__name__ = name + if tp_dict.__qualname__ == "Protocol": + tp_dict.__qualname__ = name + + if not hasattr(tp_dict, '__orig_bases__'): + tp_dict.__orig_bases__ = bases + + annotations = {} + if "__annotations__" in ns: + own_annotations = ns["__annotations__"] + elif "__annotate__" in ns: + # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated + own_annotations = ns["__annotate__"](1) + else: + own_annotations = {} + msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" + if _TAKES_MODULE: + own_annotations = { + n: typing._type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own_annotations.items() + } + else: + own_annotations = { + n: typing._type_check(tp, msg) + for n, tp in own_annotations.items() + } + required_keys = set() + optional_keys = set() + readonly_keys = set() + mutable_keys = set() + extra_items_type = None + + for base in bases: + base_dict = base.__dict__ + + annotations.update(base_dict.get('__annotations__', {})) + required_keys.update(base_dict.get('__required_keys__', ())) + optional_keys.update(base_dict.get('__optional_keys__', ())) + readonly_keys.update(base_dict.get('__readonly_keys__', ())) + mutable_keys.update(base_dict.get('__mutable_keys__', ())) + base_extra_items_type = base_dict.get('__extra_items__', None) + if base_extra_items_type is not None: + extra_items_type = base_extra_items_type + + if closed and extra_items_type is None: + extra_items_type = Never + if closed and "__extra_items__" in own_annotations: + annotation_type = own_annotations.pop("__extra_items__") + qualifiers = set(_get_typeddict_qualifiers(annotation_type)) + if Required in qualifiers: + raise TypeError( + "Special key __extra_items__ does not support " + "Required" + ) + if NotRequired in qualifiers: + raise TypeError( + "Special key __extra_items__ does not support " + "NotRequired" + ) + extra_items_type = annotation_type + + annotations.update(own_annotations) + for annotation_key, annotation_type in own_annotations.items(): + qualifiers = set(_get_typeddict_qualifiers(annotation_type)) + + if Required in qualifiers: + required_keys.add(annotation_key) + elif NotRequired in qualifiers: + optional_keys.add(annotation_key) + elif total: + required_keys.add(annotation_key) + else: + optional_keys.add(annotation_key) + if ReadOnly in qualifiers: + mutable_keys.discard(annotation_key) + readonly_keys.add(annotation_key) + else: + mutable_keys.add(annotation_key) + readonly_keys.discard(annotation_key) + + tp_dict.__annotations__ = annotations + tp_dict.__required_keys__ = frozenset(required_keys) + tp_dict.__optional_keys__ = frozenset(optional_keys) + tp_dict.__readonly_keys__ = frozenset(readonly_keys) + tp_dict.__mutable_keys__ = frozenset(mutable_keys) + if not hasattr(tp_dict, '__total__'): + tp_dict.__total__ = total + tp_dict.__closed__ = closed + tp_dict.__extra_items__ = extra_items_type + return tp_dict + + __call__ = dict # static method + + def __subclasscheck__(cls, other): + # Typed dicts are only for static structural subtyping. + raise TypeError('TypedDict does not support instance and class checks') + + __instancecheck__ = __subclasscheck__ + + _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) + + @_ensure_subclassable(lambda bases: (_TypedDict,)) + def TypedDict(typename, fields=_marker, /, *, total=True, closed=False, **kwargs): + """A simple typed namespace. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type such that a type checker will expect all + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime. + + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info can be accessed via the Point2D.__annotations__ dict, and + the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. + TypedDict supports an additional equivalent form:: + + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality:: + + class Point2D(TypedDict, total=False): + x: int + y: int + + This means that a Point2D TypedDict can have any of the keys omitted. A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + The Required and NotRequired special forms can also be used to mark + individual keys as being required or not required:: + + class Point2D(TypedDict): + x: int # the "x" key must always be present (Required is the default) + y: NotRequired[int] # the "y" key can be omitted + + See PEP 655 for more details on Required and NotRequired. + """ + if fields is _marker or fields is None: + if fields is _marker: + deprecated_thing = "Failing to pass a value for the 'fields' parameter" + else: + deprecated_thing = "Passing `None` as the 'fields' parameter" + + example = f"`{typename} = TypedDict({typename!r}, {{}})`" + deprecation_msg = ( + f"{deprecated_thing} is deprecated and will be disallowed in " + "Python 3.15. To create a TypedDict class with 0 fields " + "using the functional syntax, pass an empty dictionary, e.g. " + ) + example + "." + warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) + if closed is not False and closed is not True: + kwargs["closed"] = closed + closed = False + fields = kwargs + elif kwargs: + raise TypeError("TypedDict takes either a dict or keyword arguments," + " but not both") + if kwargs: + if sys.version_info >= (3, 13): + raise TypeError("TypedDict takes no keyword arguments") + warnings.warn( + "The kwargs-based syntax for TypedDict definitions is deprecated " + "in Python 3.11, will be removed in Python 3.13, and may not be " + "understood by third-party type checkers.", + DeprecationWarning, + stacklevel=2, + ) + + ns = {'__annotations__': dict(fields)} + module = _caller() + if module is not None: + # Setting correct module is necessary to make typed dict classes pickleable. + ns['__module__'] = module + + td = _TypedDictMeta(typename, (), ns, total=total, closed=closed) + td.__orig_bases__ = (TypedDict,) + return td + + if hasattr(typing, "_TypedDictMeta"): + _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) + else: + _TYPEDDICT_TYPES = (_TypedDictMeta,) + + def is_typeddict(tp): + """Check if an annotation is a TypedDict class + + For example:: + class Film(TypedDict): + title: str + year: int + + is_typeddict(Film) # => True + is_typeddict(Union[list, str]) # => False + """ + # On 3.8, this would otherwise return True + if hasattr(typing, "TypedDict") and tp is typing.TypedDict: + return False + return isinstance(tp, _TYPEDDICT_TYPES) + + +if hasattr(typing, "assert_type"): + assert_type = typing.assert_type + +else: + def assert_type(val, typ, /): + """Assert (to the type checker) that the value is of the given type. + + When the type checker encounters a call to assert_type(), it + emits an error if the value is not of the specified type:: + + def greet(name: str) -> None: + assert_type(name, str) # ok + assert_type(name, int) # type checker error + + At runtime this returns the first argument unchanged and otherwise + does nothing. + """ + return val + + +if hasattr(typing, "ReadOnly"): # 3.13+ + get_type_hints = typing.get_type_hints +else: # <=3.13 + # replaces _strip_annotations() + def _strip_extras(t): + """Strips Annotated, Required and NotRequired from a given type.""" + if isinstance(t, _AnnotatedAlias): + return _strip_extras(t.__origin__) + if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly): + return _strip_extras(t.__args__[0]) + if isinstance(t, typing._GenericAlias): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return t.copy_with(stripped_args) + if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return _types.GenericAlias(t.__origin__, stripped_args) + if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return functools.reduce(operator.or_, stripped_args) + + return t + + def get_type_hints(obj, globalns=None, localns=None, include_extras=False): + """Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, adds Optional[t] if a + default value equal to None is set and recursively replaces all + 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' + (unless 'include_extras=True'). + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + """ + if hasattr(typing, "Annotated"): # 3.9+ + hint = typing.get_type_hints( + obj, globalns=globalns, localns=localns, include_extras=True + ) + else: # 3.8 + hint = typing.get_type_hints(obj, globalns=globalns, localns=localns) + if include_extras: + return hint + return {k: _strip_extras(t) for k, t in hint.items()} + + +# Python 3.9+ has PEP 593 (Annotated) +if hasattr(typing, 'Annotated'): + Annotated = typing.Annotated + # Not exported and not a public API, but needed for get_origin() and get_args() + # to work. + _AnnotatedAlias = typing._AnnotatedAlias +# 3.8 +else: + class _AnnotatedAlias(typing._GenericAlias, _root=True): + """Runtime representation of an annotated type. + + At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' + with extra annotations. The alias behaves like a normal typing alias, + instantiating is the same as instantiating the underlying type, binding + it to types is also the same. + """ + def __init__(self, origin, metadata): + if isinstance(origin, _AnnotatedAlias): + metadata = origin.__metadata__ + metadata + origin = origin.__origin__ + super().__init__(origin, origin) + self.__metadata__ = metadata + + def copy_with(self, params): + assert len(params) == 1 + new_type = params[0] + return _AnnotatedAlias(new_type, self.__metadata__) + + def __repr__(self): + return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, " + f"{', '.join(repr(a) for a in self.__metadata__)}]") + + def __reduce__(self): + return operator.getitem, ( + Annotated, (self.__origin__, *self.__metadata__) + ) + + def __eq__(self, other): + if not isinstance(other, _AnnotatedAlias): + return NotImplemented + if self.__origin__ != other.__origin__: + return False + return self.__metadata__ == other.__metadata__ + + def __hash__(self): + return hash((self.__origin__, self.__metadata__)) + + class Annotated: + """Add context specific metadata to a type. + + Example: Annotated[int, runtime_check.Unsigned] indicates to the + hypothetical runtime_check module that this type is an unsigned int. + Every other consumer of this type can ignore this metadata and treat + this type as int. + + The first argument to Annotated must be a valid type (and will be in + the __origin__ field), the remaining arguments are kept as a tuple in + the __extra__ field. + + Details: + + - It's an error to call `Annotated` with less than two arguments. + - Nested Annotated are flattened:: + + Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] + + - Instantiating an annotated type is equivalent to instantiating the + underlying type:: + + Annotated[C, Ann1](5) == C(5) + + - Annotated can be used as a generic type alias:: + + Optimized = Annotated[T, runtime.Optimize()] + Optimized[int] == Annotated[int, runtime.Optimize()] + + OptimizedList = Annotated[List[T], runtime.Optimize()] + OptimizedList[int] == Annotated[List[int], runtime.Optimize()] + """ + + __slots__ = () + + def __new__(cls, *args, **kwargs): + raise TypeError("Type Annotated cannot be instantiated.") + + @typing._tp_cache + def __class_getitem__(cls, params): + if not isinstance(params, tuple) or len(params) < 2: + raise TypeError("Annotated[...] should be used " + "with at least two arguments (a type and an " + "annotation).") + allowed_special_forms = (ClassVar, Final) + if get_origin(params[0]) in allowed_special_forms: + origin = params[0] + else: + msg = "Annotated[t, ...]: t must be a type." + origin = typing._type_check(params[0], msg) + metadata = tuple(params[1:]) + return _AnnotatedAlias(origin, metadata) + + def __init_subclass__(cls, *args, **kwargs): + raise TypeError( + f"Cannot subclass {cls.__module__}.Annotated" + ) + +# Python 3.8 has get_origin() and get_args() but those implementations aren't +# Annotated-aware, so we can't use those. Python 3.9's versions don't support +# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do. +if sys.version_info[:2] >= (3, 10): + get_origin = typing.get_origin + get_args = typing.get_args +# 3.8-3.9 +else: + try: + # 3.9+ + from typing import _BaseGenericAlias + except ImportError: + _BaseGenericAlias = typing._GenericAlias + try: + # 3.9+ + from typing import GenericAlias as _typing_GenericAlias + except ImportError: + _typing_GenericAlias = typing._GenericAlias + + def get_origin(tp): + """Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar + and Annotated. Return None for unsupported types. Examples:: + + get_origin(Literal[42]) is Literal + get_origin(int) is None + get_origin(ClassVar[int]) is ClassVar + get_origin(Generic) is Generic + get_origin(Generic[T]) is Generic + get_origin(Union[T, int]) is Union + get_origin(List[Tuple[T, T]][int]) == list + get_origin(P.args) is P + """ + if isinstance(tp, _AnnotatedAlias): + return Annotated + if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias, + ParamSpecArgs, ParamSpecKwargs)): + return tp.__origin__ + if tp is typing.Generic: + return typing.Generic + return None + + def get_args(tp): + """Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + """ + if isinstance(tp, _AnnotatedAlias): + return (tp.__origin__, *tp.__metadata__) + if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)): + if getattr(tp, "_special", False): + return () + res = tp.__args__ + if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: + res = (list(res[:-1]), res[-1]) + return res + return () + + +# 3.10+ +if hasattr(typing, 'TypeAlias'): + TypeAlias = typing.TypeAlias +# 3.9 +elif sys.version_info[:2] >= (3, 9): + @_ExtensionsSpecialForm + def TypeAlias(self, parameters): + """Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example above. + """ + raise TypeError(f"{self} is not subscriptable") +# 3.8 +else: + TypeAlias = _ExtensionsSpecialForm( + 'TypeAlias', + doc="""Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example + above.""" + ) + + +if hasattr(typing, "NoDefault"): + NoDefault = typing.NoDefault +else: + class NoDefaultTypeMeta(type): + def __setattr__(cls, attr, value): + # TypeError is consistent with the behavior of NoneType + raise TypeError( + f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}" + ) + + class NoDefaultType(metaclass=NoDefaultTypeMeta): + """The type of the NoDefault singleton.""" + + __slots__ = () + + def __new__(cls): + return globals().get("NoDefault") or object.__new__(cls) + + def __repr__(self): + return "typing_extensions.NoDefault" + + def __reduce__(self): + return "NoDefault" + + NoDefault = NoDefaultType() + del NoDefaultType, NoDefaultTypeMeta + + +def _set_default(type_param, default): + type_param.has_default = lambda: default is not NoDefault + type_param.__default__ = default + + +def _set_module(typevarlike): + # for pickling: + def_mod = _caller(depth=3) + if def_mod != 'typing_extensions': + typevarlike.__module__ = def_mod + + +class _DefaultMixin: + """Mixin for TypeVarLike defaults.""" + + __slots__ = () + __init__ = _set_default + + +# Classes using this metaclass must provide a _backported_typevarlike ClassVar +class _TypeVarLikeMeta(type): + def __instancecheck__(cls, __instance: Any) -> bool: + return isinstance(__instance, cls._backported_typevarlike) + + +if _PEP_696_IMPLEMENTED: + from typing import TypeVar +else: + # Add default and infer_variance parameters from PEP 696 and 695 + class TypeVar(metaclass=_TypeVarLikeMeta): + """Type variable.""" + + _backported_typevarlike = typing.TypeVar + + def __new__(cls, name, *constraints, bound=None, + covariant=False, contravariant=False, + default=NoDefault, infer_variance=False): + if hasattr(typing, "TypeAliasType"): + # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar + typevar = typing.TypeVar(name, *constraints, bound=bound, + covariant=covariant, contravariant=contravariant, + infer_variance=infer_variance) + else: + typevar = typing.TypeVar(name, *constraints, bound=bound, + covariant=covariant, contravariant=contravariant) + if infer_variance and (covariant or contravariant): + raise ValueError("Variance cannot be specified with infer_variance.") + typevar.__infer_variance__ = infer_variance + + _set_default(typevar, default) + _set_module(typevar) + + def _tvar_prepare_subst(alias, args): + if ( + typevar.has_default() + and alias.__parameters__.index(typevar) == len(args) + ): + args += (typevar.__default__,) + return args + + typevar.__typing_prepare_subst__ = _tvar_prepare_subst + return typevar + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type") + + +# Python 3.10+ has PEP 612 +if hasattr(typing, 'ParamSpecArgs'): + ParamSpecArgs = typing.ParamSpecArgs + ParamSpecKwargs = typing.ParamSpecKwargs +# 3.8-3.9 +else: + class _Immutable: + """Mixin to indicate that object should not be copied.""" + __slots__ = () + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + class ParamSpecArgs(_Immutable): + """The args for a ParamSpec object. + + Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. + + ParamSpecArgs objects have a reference back to their ParamSpec: + + P.args.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.args" + + def __eq__(self, other): + if not isinstance(other, ParamSpecArgs): + return NotImplemented + return self.__origin__ == other.__origin__ + + class ParamSpecKwargs(_Immutable): + """The kwargs for a ParamSpec object. + + Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. + + ParamSpecKwargs objects have a reference back to their ParamSpec: + + P.kwargs.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.kwargs" + + def __eq__(self, other): + if not isinstance(other, ParamSpecKwargs): + return NotImplemented + return self.__origin__ == other.__origin__ + + +if _PEP_696_IMPLEMENTED: + from typing import ParamSpec + +# 3.10+ +elif hasattr(typing, 'ParamSpec'): + + # Add default parameter - PEP 696 + class ParamSpec(metaclass=_TypeVarLikeMeta): + """Parameter specification.""" + + _backported_typevarlike = typing.ParamSpec + + def __new__(cls, name, *, bound=None, + covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + if hasattr(typing, "TypeAliasType"): + # PEP 695 implemented, can pass infer_variance to typing.TypeVar + paramspec = typing.ParamSpec(name, bound=bound, + covariant=covariant, + contravariant=contravariant, + infer_variance=infer_variance) + else: + paramspec = typing.ParamSpec(name, bound=bound, + covariant=covariant, + contravariant=contravariant) + paramspec.__infer_variance__ = infer_variance + + _set_default(paramspec, default) + _set_module(paramspec) + + def _paramspec_prepare_subst(alias, args): + params = alias.__parameters__ + i = params.index(paramspec) + if i == len(args) and paramspec.has_default(): + args = [*args, paramspec.__default__] + if i >= len(args): + raise TypeError(f"Too few arguments for {alias}") + # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. + if len(params) == 1 and not typing._is_param_expr(args[0]): + assert i == 0 + args = (args,) + # Convert lists to tuples to help other libraries cache the results. + elif isinstance(args[i], list): + args = (*args[:i], tuple(args[i]), *args[i + 1:]) + return args + + paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst + return paramspec + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") + +# 3.8-3.9 +else: + + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + class ParamSpec(list, _DefaultMixin): + """Parameter specification variable. + + Usage:: + + P = ParamSpec('P') + + Parameter specification variables exist primarily for the benefit of static + type checkers. They are used to forward the parameter types of one + callable to another callable, a pattern commonly found in higher order + functions and decorators. They are only valid when used in ``Concatenate``, + or s the first argument to ``Callable``. In Python 3.10 and higher, + they are also supported in user-defined Generics at runtime. + See class Generic for more information on generic types. An + example for annotating a decorator:: + + T = TypeVar('T') + P = ParamSpec('P') + + def add_logging(f: Callable[P, T]) -> Callable[P, T]: + '''A type-safe decorator to add logging to a function.''' + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + logging.info(f'{f.__name__} was called') + return f(*args, **kwargs) + return inner + + @add_logging + def add_two(x: float, y: float) -> float: + '''Add two numbers together.''' + return x + y + + Parameter specification variables defined with covariant=True or + contravariant=True can be used to declare covariant or contravariant + generic types. These keyword arguments are valid, but their actual semantics + are yet to be decided. See PEP 612 for details. + + Parameter specification variables can be introspected. e.g.: + + P.__name__ == 'T' + P.__bound__ == None + P.__covariant__ == False + P.__contravariant__ == False + + Note that only parameter specification variables defined in global scope can + be pickled. + """ + + # Trick Generic __parameters__. + __class__ = typing.TypeVar + + @property + def args(self): + return ParamSpecArgs(self) + + @property + def kwargs(self): + return ParamSpecKwargs(self) + + def __init__(self, name, *, bound=None, covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + list.__init__(self, [self]) + self.__name__ = name + self.__covariant__ = bool(covariant) + self.__contravariant__ = bool(contravariant) + self.__infer_variance__ = bool(infer_variance) + if bound: + self.__bound__ = typing._type_check(bound, 'Bound must be a type.') + else: + self.__bound__ = None + _DefaultMixin.__init__(self, default) + + # for pickling: + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __repr__(self): + if self.__infer_variance__: + prefix = '' + elif self.__covariant__: + prefix = '+' + elif self.__contravariant__: + prefix = '-' + else: + prefix = '~' + return prefix + self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + # Hack to get typing._type_check to pass. + def __call__(self, *args, **kwargs): + pass + + +# 3.8-3.9 +if not hasattr(typing, 'Concatenate'): + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + class _ConcatenateGenericAlias(list): + + # Trick Generic into looking into this for __parameters__. + __class__ = typing._GenericAlias + + # Flag in 3.8. + _special = False + + def __init__(self, origin, args): + super().__init__(args) + self.__origin__ = origin + self.__args__ = args + + def __repr__(self): + _type_repr = typing._type_repr + return (f'{_type_repr(self.__origin__)}' + f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]') + + def __hash__(self): + return hash((self.__origin__, self.__args__)) + + # Hack to get typing._type_check to pass in Generic. + def __call__(self, *args, **kwargs): + pass + + @property + def __parameters__(self): + return tuple( + tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec)) + ) + + +# 3.8-3.9 +@typing._tp_cache +def _concatenate_getitem(self, parameters): + if parameters == (): + raise TypeError("Cannot take a Concatenate of no types.") + if not isinstance(parameters, tuple): + parameters = (parameters,) + if not isinstance(parameters[-1], ParamSpec): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable.") + msg = "Concatenate[arg, ...]: each arg must be a type." + parameters = tuple(typing._type_check(p, msg) for p in parameters) + return _ConcatenateGenericAlias(self, parameters) + + +# 3.10+ +if hasattr(typing, 'Concatenate'): + Concatenate = typing.Concatenate + _ConcatenateGenericAlias = typing._ConcatenateGenericAlias +# 3.9 +elif sys.version_info[:2] >= (3, 9): + @_ExtensionsSpecialForm + def Concatenate(self, parameters): + """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """ + return _concatenate_getitem(self, parameters) +# 3.8 +else: + class _ConcatenateForm(_ExtensionsSpecialForm, _root=True): + def __getitem__(self, parameters): + return _concatenate_getitem(self, parameters) + + Concatenate = _ConcatenateForm( + 'Concatenate', + doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """) + +# 3.10+ +if hasattr(typing, 'TypeGuard'): + TypeGuard = typing.TypeGuard +# 3.9 +elif sys.version_info[:2] >= (3, 9): + @_ExtensionsSpecialForm + def TypeGuard(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) +# 3.8 +else: + class _TypeGuardForm(_ExtensionsSpecialForm, _root=True): + def __getitem__(self, parameters): + item = typing._type_check(parameters, + f'{self._name} accepts only a single type') + return typing._GenericAlias(self, (item,)) + + TypeGuard = _TypeGuardForm( + 'TypeGuard', + doc="""Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """) + +# 3.13+ +if hasattr(typing, 'TypeIs'): + TypeIs = typing.TypeIs +# 3.9 +elif sys.version_info[:2] >= (3, 9): + @_ExtensionsSpecialForm + def TypeIs(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type narrower function. ``TypeIs`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeIs[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeIs`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the intersection of the type inside ``TypeGuard`` and the argument's + previously known type. + + For example:: + + def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]: + return hasattr(val, '__await__') + + def f(val: Union[int, Awaitable[int]]) -> int: + if is_awaitable(val): + assert_type(val, Awaitable[int]) + else: + assert_type(val, int) + + ``TypeIs`` also works with type variables. For more information, see + PEP 742 (Narrowing types with TypeIs). + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) +# 3.8 +else: + class _TypeIsForm(_ExtensionsSpecialForm, _root=True): + def __getitem__(self, parameters): + item = typing._type_check(parameters, + f'{self._name} accepts only a single type') + return typing._GenericAlias(self, (item,)) + + TypeIs = _TypeIsForm( + 'TypeIs', + doc="""Special typing form used to annotate the return type of a user-defined + type narrower function. ``TypeIs`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeIs[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeIs`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the intersection of the type inside ``TypeGuard`` and the argument's + previously known type. + + For example:: + + def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]: + return hasattr(val, '__await__') + + def f(val: Union[int, Awaitable[int]]) -> int: + if is_awaitable(val): + assert_type(val, Awaitable[int]) + else: + assert_type(val, int) + + ``TypeIs`` also works with type variables. For more information, see + PEP 742 (Narrowing types with TypeIs). + """) + + +# Vendored from cpython typing._SpecialFrom +class _SpecialForm(typing._Final, _root=True): + __slots__ = ('_name', '__doc__', '_getitem') + + def __init__(self, getitem): + self._getitem = getitem + self._name = getitem.__name__ + self.__doc__ = getitem.__doc__ + + def __getattr__(self, item): + if item in {'__name__', '__qualname__'}: + return self._name + + raise AttributeError(item) + + def __mro_entries__(self, bases): + raise TypeError(f"Cannot subclass {self!r}") + + def __repr__(self): + return f'typing_extensions.{self._name}' + + def __reduce__(self): + return self._name + + def __call__(self, *args, **kwds): + raise TypeError(f"Cannot instantiate {self!r}") + + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + def __instancecheck__(self, obj): + raise TypeError(f"{self} cannot be used with isinstance()") + + def __subclasscheck__(self, cls): + raise TypeError(f"{self} cannot be used with issubclass()") + + @typing._tp_cache + def __getitem__(self, parameters): + return self._getitem(self, parameters) + + +if hasattr(typing, "LiteralString"): # 3.11+ + LiteralString = typing.LiteralString +else: + @_SpecialForm + def LiteralString(self, params): + """Represents an arbitrary literal string. + + Example:: + + from typing_extensions import LiteralString + + def query(sql: LiteralString) -> ...: + ... + + query("SELECT * FROM table") # ok + query(f"SELECT * FROM {input()}") # not ok + + See PEP 675 for details. + + """ + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, "Self"): # 3.11+ + Self = typing.Self +else: + @_SpecialForm + def Self(self, params): + """Used to spell the type of "self" in classes. + + Example:: + + from typing import Self + + class ReturnsSelf: + def parse(self, data: bytes) -> Self: + ... + return self + + """ + + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, "Never"): # 3.11+ + Never = typing.Never +else: + @_SpecialForm + def Never(self, params): + """The bottom type, a type that has no members. + + This can be used to define a function that should never be + called, or a function that never returns:: + + from typing_extensions import Never + + def never_call_me(arg: Never) -> None: + pass + + def int_or_str(arg: int | str) -> None: + never_call_me(arg) # type checker error + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + never_call_me(arg) # ok, arg is of type Never + + """ + + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, 'Required'): # 3.11+ + Required = typing.Required + NotRequired = typing.NotRequired +elif sys.version_info[:2] >= (3, 9): # 3.9-3.10 + @_ExtensionsSpecialForm + def Required(self, parameters): + """A special typing construct to mark a key of a total=False TypedDict + as required. For example: + + class Movie(TypedDict, total=False): + title: Required[str] + year: int + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + + There is no runtime checking that a required key is actually provided + when instantiating a related TypedDict. + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + @_ExtensionsSpecialForm + def NotRequired(self, parameters): + """A special typing construct to mark a key of a TypedDict as + potentially missing. For example: + + class Movie(TypedDict): + title: str + year: NotRequired[int] + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + +else: # 3.8 + class _RequiredForm(_ExtensionsSpecialForm, _root=True): + def __getitem__(self, parameters): + item = typing._type_check(parameters, + f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + Required = _RequiredForm( + 'Required', + doc="""A special typing construct to mark a key of a total=False TypedDict + as required. For example: + + class Movie(TypedDict, total=False): + title: Required[str] + year: int + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + + There is no runtime checking that a required key is actually provided + when instantiating a related TypedDict. + """) + NotRequired = _RequiredForm( + 'NotRequired', + doc="""A special typing construct to mark a key of a TypedDict as + potentially missing. For example: + + class Movie(TypedDict): + title: str + year: NotRequired[int] + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + """) + + +if hasattr(typing, 'ReadOnly'): + ReadOnly = typing.ReadOnly +elif sys.version_info[:2] >= (3, 9): # 3.9-3.12 + @_ExtensionsSpecialForm + def ReadOnly(self, parameters): + """A special typing construct to mark an item of a TypedDict as read-only. + + For example: + + class Movie(TypedDict): + title: ReadOnly[str] + year: int + + def mutate_movie(m: Movie) -> None: + m["year"] = 1992 # allowed + m["title"] = "The Matrix" # typechecker error + + There is no runtime checking for this property. + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + +else: # 3.8 + class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True): + def __getitem__(self, parameters): + item = typing._type_check(parameters, + f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + ReadOnly = _ReadOnlyForm( + 'ReadOnly', + doc="""A special typing construct to mark a key of a TypedDict as read-only. + + For example: + + class Movie(TypedDict): + title: ReadOnly[str] + year: int + + def mutate_movie(m: Movie) -> None: + m["year"] = 1992 # allowed + m["title"] = "The Matrix" # typechecker error + + There is no runtime checking for this propery. + """) + + +_UNPACK_DOC = """\ +Type unpack operator. + +The type unpack operator takes the child types from some container type, +such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For +example: + + # For some generic class `Foo`: + Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] + + Ts = TypeVarTuple('Ts') + # Specifies that `Bar` is generic in an arbitrary number of types. + # (Think of `Ts` as a tuple of an arbitrary number of individual + # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the + # `Generic[]`.) + class Bar(Generic[Unpack[Ts]]): ... + Bar[int] # Valid + Bar[int, str] # Also valid + +From Python 3.11, this can also be done using the `*` operator: + + Foo[*tuple[int, str]] + class Bar(Generic[*Ts]): ... + +The operator can also be used along with a `TypedDict` to annotate +`**kwargs` in a function signature. For instance: + + class Movie(TypedDict): + name: str + year: int + + # This function expects two keyword arguments - *name* of type `str` and + # *year* of type `int`. + def foo(**kwargs: Unpack[Movie]): ... + +Note that there is only some runtime checking of this operator. Not +everything the runtime allows may be accepted by static type checkers. + +For more information, see PEP 646 and PEP 692. +""" + + +if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[] + Unpack = typing.Unpack + + def _is_unpack(obj): + return get_origin(obj) is Unpack + +elif sys.version_info[:2] >= (3, 9): # 3.9+ + class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True): + def __init__(self, getitem): + super().__init__(getitem) + self.__doc__ = _UNPACK_DOC + + class _UnpackAlias(typing._GenericAlias, _root=True): + __class__ = typing.TypeVar + + @property + def __typing_unpacked_tuple_args__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + arg, = self.__args__ + if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)): + if arg.__origin__ is not tuple: + raise TypeError("Unpack[...] must be used with a tuple type") + return arg.__args__ + return None + + @_UnpackSpecialForm + def Unpack(self, parameters): + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return _UnpackAlias(self, (item,)) + + def _is_unpack(obj): + return isinstance(obj, _UnpackAlias) + +else: # 3.8 + class _UnpackAlias(typing._GenericAlias, _root=True): + __class__ = typing.TypeVar + + class _UnpackForm(_ExtensionsSpecialForm, _root=True): + def __getitem__(self, parameters): + item = typing._type_check(parameters, + f'{self._name} accepts only a single type.') + return _UnpackAlias(self, (item,)) + + Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC) + + def _is_unpack(obj): + return isinstance(obj, _UnpackAlias) + + +if _PEP_696_IMPLEMENTED: + from typing import TypeVarTuple + +elif hasattr(typing, "TypeVarTuple"): # 3.11+ + + def _unpack_args(*args): + newargs = [] + for arg in args: + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs is not None and not (subargs and subargs[-1] is ...): + newargs.extend(subargs) + else: + newargs.append(arg) + return newargs + + # Add default parameter - PEP 696 + class TypeVarTuple(metaclass=_TypeVarLikeMeta): + """Type variable tuple.""" + + _backported_typevarlike = typing.TypeVarTuple + + def __new__(cls, name, *, default=NoDefault): + tvt = typing.TypeVarTuple(name) + _set_default(tvt, default) + _set_module(tvt) + + def _typevartuple_prepare_subst(alias, args): + params = alias.__parameters__ + typevartuple_index = params.index(tvt) + for param in params[typevartuple_index + 1:]: + if isinstance(param, TypeVarTuple): + raise TypeError( + f"More than one TypeVarTuple parameter in {alias}" + ) + + alen = len(args) + plen = len(params) + left = typevartuple_index + right = plen - typevartuple_index - 1 + var_tuple_index = None + fillarg = None + for k, arg in enumerate(args): + if not isinstance(arg, type): + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs and len(subargs) == 2 and subargs[-1] is ...: + if var_tuple_index is not None: + raise TypeError( + "More than one unpacked " + "arbitrary-length tuple argument" + ) + var_tuple_index = k + fillarg = subargs[0] + if var_tuple_index is not None: + left = min(left, var_tuple_index) + right = min(right, alen - var_tuple_index - 1) + elif left + right > alen: + raise TypeError(f"Too few arguments for {alias};" + f" actual {alen}, expected at least {plen - 1}") + if left == alen - right and tvt.has_default(): + replacement = _unpack_args(tvt.__default__) + else: + replacement = args[left: alen - right] + + return ( + *args[:left], + *([fillarg] * (typevartuple_index - left)), + replacement, + *([fillarg] * (plen - right - left - typevartuple_index - 1)), + *args[alen - right:], + ) + + tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst + return tvt + + def __init_subclass__(self, *args, **kwds): + raise TypeError("Cannot subclass special typing classes") + +else: # <=3.10 + class TypeVarTuple(_DefaultMixin): + """Type variable tuple. + + Usage:: + + Ts = TypeVarTuple('Ts') + + In the same way that a normal type variable is a stand-in for a single + type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* + type such as ``Tuple[int, str]``. + + Type variable tuples can be used in ``Generic`` declarations. + Consider the following example:: + + class Array(Generic[*Ts]): ... + + The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``, + where ``T1`` and ``T2`` are type variables. To use these type variables + as type parameters of ``Array``, we must *unpack* the type variable tuple using + the star operator: ``*Ts``. The signature of ``Array`` then behaves + as if we had simply written ``class Array(Generic[T1, T2]): ...``. + In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows + us to parameterise the class with an *arbitrary* number of type parameters. + + Type variable tuples can be used anywhere a normal ``TypeVar`` can. + This includes class definitions, as shown above, as well as function + signatures and variable annotations:: + + class Array(Generic[*Ts]): + + def __init__(self, shape: Tuple[*Ts]): + self._shape: Tuple[*Ts] = shape + + def get_shape(self) -> Tuple[*Ts]: + return self._shape + + shape = (Height(480), Width(640)) + x: Array[Height, Width] = Array(shape) + y = abs(x) # Inferred type is Array[Height, Width] + z = x + x # ... is Array[Height, Width] + x.get_shape() # ... is tuple[Height, Width] + + """ + + # Trick Generic __parameters__. + __class__ = typing.TypeVar + + def __iter__(self): + yield self.__unpacked__ + + def __init__(self, name, *, default=NoDefault): + self.__name__ = name + _DefaultMixin.__init__(self, default) + + # for pickling: + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + self.__unpacked__ = Unpack[self] + + def __repr__(self): + return self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + def __init_subclass__(self, *args, **kwds): + if '_root' not in kwds: + raise TypeError("Cannot subclass special typing classes") + + +if hasattr(typing, "reveal_type"): # 3.11+ + reveal_type = typing.reveal_type +else: # <=3.10 + def reveal_type(obj: T, /) -> T: + """Reveal the inferred type of a variable. + + When a static type checker encounters a call to ``reveal_type()``, + it will emit the inferred type of the argument:: + + x: int = 1 + reveal_type(x) + + Running a static type checker (e.g., ``mypy``) on this example + will produce output similar to 'Revealed type is "builtins.int"'. + + At runtime, the function prints the runtime type of the + argument and returns it unchanged. + + """ + print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr) + return obj + + +if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+ + _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH +else: # <=3.10 + _ASSERT_NEVER_REPR_MAX_LENGTH = 100 + + +if hasattr(typing, "assert_never"): # 3.11+ + assert_never = typing.assert_never +else: # <=3.10 + def assert_never(arg: Never, /) -> Never: + """Assert to the type checker that a line of code is unreachable. + + Example:: + + def int_or_str(arg: int | str) -> None: + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + assert_never(arg) + + If a type checker finds that a call to assert_never() is + reachable, it will emit an error. + + At runtime, this throws an exception when called. + + """ + value = repr(arg) + if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: + value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...' + raise AssertionError(f"Expected code to be unreachable, but got: {value}") + + +if sys.version_info >= (3, 12): # 3.12+ + # dataclass_transform exists in 3.11 but lacks the frozen_default parameter + dataclass_transform = typing.dataclass_transform +else: # <=3.11 + def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + frozen_default: bool = False, + field_specifiers: typing.Tuple[ + typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]], + ... + ] = (), + **kwargs: typing.Any, + ) -> typing.Callable[[T], T]: + """Decorator that marks a function, class, or metaclass as providing + dataclass-like behavior. + + Example: + + from typing_extensions import dataclass_transform + + _T = TypeVar("_T") + + # Used on a decorator function + @dataclass_transform() + def create_model(cls: type[_T]) -> type[_T]: + ... + return cls + + @create_model + class CustomerModel: + id: int + name: str + + # Used on a base class + @dataclass_transform() + class ModelBase: ... + + class CustomerModel(ModelBase): + id: int + name: str + + # Used on a metaclass + @dataclass_transform() + class ModelMeta(type): ... + + class ModelBase(metaclass=ModelMeta): ... + + class CustomerModel(ModelBase): + id: int + name: str + + Each of the ``CustomerModel`` classes defined in this example will now + behave similarly to a dataclass created with the ``@dataclasses.dataclass`` + decorator. For example, the type checker will synthesize an ``__init__`` + method. + + The arguments to this decorator can be used to customize this behavior: + - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be + True or False if it is omitted by the caller. + - ``order_default`` indicates whether the ``order`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``kw_only_default`` indicates whether the ``kw_only`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``frozen_default`` indicates whether the ``frozen`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``field_specifiers`` specifies a static list of supported classes + or functions that describe fields, similar to ``dataclasses.field()``. + + At runtime, this decorator records its arguments in the + ``__dataclass_transform__`` attribute on the decorated object. + + See PEP 681 for details. + + """ + def decorator(cls_or_fn): + cls_or_fn.__dataclass_transform__ = { + "eq_default": eq_default, + "order_default": order_default, + "kw_only_default": kw_only_default, + "frozen_default": frozen_default, + "field_specifiers": field_specifiers, + "kwargs": kwargs, + } + return cls_or_fn + return decorator + + +if hasattr(typing, "override"): # 3.12+ + override = typing.override +else: # <=3.11 + _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any]) + + def override(arg: _F, /) -> _F: + """Indicate that a method is intended to override a method in a base class. + + Usage: + + class Base: + def method(self) -> None: + pass + + class Child(Base): + @override + def method(self) -> None: + super().method() + + When this decorator is applied to a method, the type checker will + validate that it overrides a method with the same name on a base class. + This helps prevent bugs that may occur when a base class is changed + without an equivalent change to a child class. + + There is no runtime checking of these properties. The decorator + sets the ``__override__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + + See PEP 698 for details. + + """ + try: + arg.__override__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return arg + + +if hasattr(warnings, "deprecated"): + deprecated = warnings.deprecated +else: + _T = typing.TypeVar("_T") + + class deprecated: + """Indicate that a class, function or overload is deprecated. + + When this decorator is applied to an object, the type checker + will generate a diagnostic on usage of the deprecated object. + + Usage: + + @deprecated("Use B instead") + class A: + pass + + @deprecated("Use g instead") + def f(): + pass + + @overload + @deprecated("int support is deprecated") + def g(x: int) -> int: ... + @overload + def g(x: str) -> int: ... + + The warning specified by *category* will be emitted at runtime + on use of deprecated objects. For functions, that happens on calls; + for classes, on instantiation and on creation of subclasses. + If the *category* is ``None``, no warning is emitted at runtime. + The *stacklevel* determines where the + warning is emitted. If it is ``1`` (the default), the warning + is emitted at the direct caller of the deprecated object; if it + is higher, it is emitted further up the stack. + Static type checker behavior is not affected by the *category* + and *stacklevel* arguments. + + The deprecation message passed to the decorator is saved in the + ``__deprecated__`` attribute on the decorated object. + If applied to an overload, the decorator + must be after the ``@overload`` decorator for the attribute to + exist on the overload as returned by ``get_overloads()``. + + See PEP 702 for details. + + """ + def __init__( + self, + message: str, + /, + *, + category: typing.Optional[typing.Type[Warning]] = DeprecationWarning, + stacklevel: int = 1, + ) -> None: + if not isinstance(message, str): + raise TypeError( + "Expected an object of type str for 'message', not " + f"{type(message).__name__!r}" + ) + self.message = message + self.category = category + self.stacklevel = stacklevel + + def __call__(self, arg: _T, /) -> _T: + # Make sure the inner functions created below don't + # retain a reference to self. + msg = self.message + category = self.category + stacklevel = self.stacklevel + if category is None: + arg.__deprecated__ = msg + return arg + elif isinstance(arg, type): + import functools + from types import MethodType + + original_new = arg.__new__ + + @functools.wraps(original_new) + def __new__(cls, *args, **kwargs): + if cls is arg: + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + if original_new is not object.__new__: + return original_new(cls, *args, **kwargs) + # Mirrors a similar check in object.__new__. + elif cls.__init__ is object.__init__ and (args or kwargs): + raise TypeError(f"{cls.__name__}() takes no arguments") + else: + return original_new(cls) + + arg.__new__ = staticmethod(__new__) + + original_init_subclass = arg.__init_subclass__ + # We need slightly different behavior if __init_subclass__ + # is a bound method (likely if it was implemented in Python) + if isinstance(original_init_subclass, MethodType): + original_init_subclass = original_init_subclass.__func__ + + @functools.wraps(original_init_subclass) + def __init_subclass__(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return original_init_subclass(*args, **kwargs) + + arg.__init_subclass__ = classmethod(__init_subclass__) + # Or otherwise, which likely means it's a builtin such as + # object's implementation of __init_subclass__. + else: + @functools.wraps(original_init_subclass) + def __init_subclass__(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return original_init_subclass(*args, **kwargs) + + arg.__init_subclass__ = __init_subclass__ + + arg.__deprecated__ = __new__.__deprecated__ = msg + __init_subclass__.__deprecated__ = msg + return arg + elif callable(arg): + import functools + + @functools.wraps(arg) + def wrapper(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return arg(*args, **kwargs) + + arg.__deprecated__ = wrapper.__deprecated__ = msg + return wrapper + else: + raise TypeError( + "@deprecated decorator with non-None category must be applied to " + f"a class or callable, not {arg!r}" + ) + + +# We have to do some monkey patching to deal with the dual nature of +# Unpack/TypeVarTuple: +# - We want Unpack to be a kind of TypeVar so it gets accepted in +# Generic[Unpack[Ts]] +# - We want it to *not* be treated as a TypeVar for the purposes of +# counting generic parameters, so that when we subscript a generic, +# the runtime doesn't try to substitute the Unpack with the subscripted type. +if not hasattr(typing, "TypeVarTuple"): + def _check_generic(cls, parameters, elen=_marker): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + if not elen: + raise TypeError(f"{cls} is not a generic class") + if elen is _marker: + if not hasattr(cls, "__parameters__") or not cls.__parameters__: + raise TypeError(f"{cls} is not a generic class") + elen = len(cls.__parameters__) + alen = len(parameters) + if alen != elen: + expect_val = elen + if hasattr(cls, "__parameters__"): + parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] + num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) + if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): + return + + # deal with TypeVarLike defaults + # required TypeVarLikes cannot appear after a defaulted one. + if alen < elen: + # since we validate TypeVarLike default in _collect_type_vars + # or _collect_parameters we can safely check parameters[alen] + if ( + getattr(parameters[alen], '__default__', NoDefault) + is not NoDefault + ): + return + + num_default_tv = sum(getattr(p, '__default__', NoDefault) + is not NoDefault for p in parameters) + + elen -= num_default_tv + + expect_val = f"at least {elen}" + + things = "arguments" if sys.version_info >= (3, 10) else "parameters" + raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}" + f" for {cls}; actual {alen}, expected {expect_val}") +else: + # Python 3.11+ + + def _check_generic(cls, parameters, elen): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + if not elen: + raise TypeError(f"{cls} is not a generic class") + alen = len(parameters) + if alen != elen: + expect_val = elen + if hasattr(cls, "__parameters__"): + parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] + + # deal with TypeVarLike defaults + # required TypeVarLikes cannot appear after a defaulted one. + if alen < elen: + # since we validate TypeVarLike default in _collect_type_vars + # or _collect_parameters we can safely check parameters[alen] + if ( + getattr(parameters[alen], '__default__', NoDefault) + is not NoDefault + ): + return + + num_default_tv = sum(getattr(p, '__default__', NoDefault) + is not NoDefault for p in parameters) + + elen -= num_default_tv + + expect_val = f"at least {elen}" + + raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" + f" for {cls}; actual {alen}, expected {expect_val}") + +if not _PEP_696_IMPLEMENTED: + typing._check_generic = _check_generic + + +def _has_generic_or_protocol_as_origin() -> bool: + try: + frame = sys._getframe(2) + # - Catch AttributeError: not all Python implementations have sys._getframe() + # - Catch ValueError: maybe we're called from an unexpected module + # and the call stack isn't deep enough + except (AttributeError, ValueError): + return False # err on the side of leniency + else: + # If we somehow get invoked from outside typing.py, + # also err on the side of leniency + if frame.f_globals.get("__name__") != "typing": + return False + origin = frame.f_locals.get("origin") + # Cannot use "in" because origin may be an object with a buggy __eq__ that + # throws an error. + return origin is typing.Generic or origin is Protocol or origin is typing.Protocol + + +_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)} + + +def _is_unpacked_typevartuple(x) -> bool: + if get_origin(x) is not Unpack: + return False + args = get_args(x) + return ( + bool(args) + and len(args) == 1 + and type(args[0]) in _TYPEVARTUPLE_TYPES + ) + + +# Python 3.11+ _collect_type_vars was renamed to _collect_parameters +if hasattr(typing, '_collect_type_vars'): + def _collect_type_vars(types, typevar_types=None): + """Collect all type variable contained in types in order of + first appearance (lexicographic order). For example:: + + _collect_type_vars((T, List[S, T])) == (T, S) + """ + if typevar_types is None: + typevar_types = typing.TypeVar + tvars = [] + + # A required TypeVarLike cannot appear after a TypeVarLike with a default + # if it was a direct call to `Generic[]` or `Protocol[]` + enforce_default_ordering = _has_generic_or_protocol_as_origin() + default_encountered = False + + # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple + type_var_tuple_encountered = False + + for t in types: + if _is_unpacked_typevartuple(t): + type_var_tuple_encountered = True + elif isinstance(t, typevar_types) and t not in tvars: + if enforce_default_ordering: + has_default = getattr(t, '__default__', NoDefault) is not NoDefault + if has_default: + if type_var_tuple_encountered: + raise TypeError('Type parameter with a default' + ' follows TypeVarTuple') + default_encountered = True + elif default_encountered: + raise TypeError(f'Type parameter {t!r} without a default' + ' follows type parameter with a default') + + tvars.append(t) + if _should_collect_from_parameters(t): + tvars.extend([t for t in t.__parameters__ if t not in tvars]) + return tuple(tvars) + + typing._collect_type_vars = _collect_type_vars +else: + def _collect_parameters(args): + """Collect all type variables and parameter specifications in args + in order of first appearance (lexicographic order). + + For example:: + + assert _collect_parameters((T, Callable[P, T])) == (T, P) + """ + parameters = [] + + # A required TypeVarLike cannot appear after a TypeVarLike with default + # if it was a direct call to `Generic[]` or `Protocol[]` + enforce_default_ordering = _has_generic_or_protocol_as_origin() + default_encountered = False + + # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple + type_var_tuple_encountered = False + + for t in args: + if isinstance(t, type): + # We don't want __parameters__ descriptor of a bare Python class. + pass + elif isinstance(t, tuple): + # `t` might be a tuple, when `ParamSpec` is substituted with + # `[T, int]`, or `[int, *Ts]`, etc. + for x in t: + for collected in _collect_parameters([x]): + if collected not in parameters: + parameters.append(collected) + elif hasattr(t, '__typing_subst__'): + if t not in parameters: + if enforce_default_ordering: + has_default = ( + getattr(t, '__default__', NoDefault) is not NoDefault + ) + + if type_var_tuple_encountered and has_default: + raise TypeError('Type parameter with a default' + ' follows TypeVarTuple') + + if has_default: + default_encountered = True + elif default_encountered: + raise TypeError(f'Type parameter {t!r} without a default' + ' follows type parameter with a default') + + parameters.append(t) + else: + if _is_unpacked_typevartuple(t): + type_var_tuple_encountered = True + for x in getattr(t, '__parameters__', ()): + if x not in parameters: + parameters.append(x) + + return tuple(parameters) + + if not _PEP_696_IMPLEMENTED: + typing._collect_parameters = _collect_parameters + +# Backport typing.NamedTuple as it exists in Python 3.13. +# In 3.11, the ability to define generic `NamedTuple`s was supported. +# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8. +# On 3.12, we added __orig_bases__ to call-based NamedTuples +# On 3.13, we deprecated kwargs-based NamedTuples +if sys.version_info >= (3, 13): + NamedTuple = typing.NamedTuple +else: + def _make_nmtuple(name, types, module, defaults=()): + fields = [n for n, t in types] + annotations = {n: typing._type_check(t, f"field {n} annotation must be a type") + for n, t in types} + nm_tpl = collections.namedtuple(name, fields, + defaults=defaults, module=module) + nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations + # The `_field_types` attribute was removed in 3.9; + # in earlier versions, it is the same as the `__annotations__` attribute + if sys.version_info < (3, 9): + nm_tpl._field_types = annotations + return nm_tpl + + _prohibited_namedtuple_fields = typing._prohibited + _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'}) + + class _NamedTupleMeta(type): + def __new__(cls, typename, bases, ns): + assert _NamedTuple in bases + for base in bases: + if base is not _NamedTuple and base is not typing.Generic: + raise TypeError( + 'can only inherit from a NamedTuple type and Generic') + bases = tuple(tuple if base is _NamedTuple else base for base in bases) + if "__annotations__" in ns: + types = ns["__annotations__"] + elif "__annotate__" in ns: + # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated + types = ns["__annotate__"](1) + else: + types = {} + default_names = [] + for field_name in types: + if field_name in ns: + default_names.append(field_name) + elif default_names: + raise TypeError(f"Non-default namedtuple field {field_name} " + f"cannot follow default field" + f"{'s' if len(default_names) > 1 else ''} " + f"{', '.join(default_names)}") + nm_tpl = _make_nmtuple( + typename, types.items(), + defaults=[ns[n] for n in default_names], + module=ns['__module__'] + ) + nm_tpl.__bases__ = bases + if typing.Generic in bases: + if hasattr(typing, '_generic_class_getitem'): # 3.12+ + nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem) + else: + class_getitem = typing.Generic.__class_getitem__.__func__ + nm_tpl.__class_getitem__ = classmethod(class_getitem) + # update from user namespace without overriding special namedtuple attributes + for key, val in ns.items(): + if key in _prohibited_namedtuple_fields: + raise AttributeError("Cannot overwrite NamedTuple attribute " + key) + elif key not in _special_namedtuple_fields: + if key not in nm_tpl._fields: + setattr(nm_tpl, key, ns[key]) + try: + set_name = type(val).__set_name__ + except AttributeError: + pass + else: + try: + set_name(val, nm_tpl, key) + except BaseException as e: + msg = ( + f"Error calling __set_name__ on {type(val).__name__!r} " + f"instance {key!r} in {typename!r}" + ) + # BaseException.add_note() existed on py311, + # but the __set_name__ machinery didn't start + # using add_note() until py312. + # Making sure exceptions are raised in the same way + # as in "normal" classes seems most important here. + if sys.version_info >= (3, 12): + e.add_note(msg) + raise + else: + raise RuntimeError(msg) from e + + if typing.Generic in bases: + nm_tpl.__init_subclass__() + return nm_tpl + + _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {}) + + def _namedtuple_mro_entries(bases): + assert NamedTuple in bases + return (_NamedTuple,) + + @_ensure_subclassable(_namedtuple_mro_entries) + def NamedTuple(typename, fields=_marker, /, **kwargs): + """Typed version of namedtuple. + + Usage:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + The resulting class has an extra __annotations__ attribute, giving a + dict that maps field names to types. (The field names are also in + the _fields attribute, which is part of the namedtuple API.) + An alternative equivalent functional syntax is also accepted:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + """ + if fields is _marker: + if kwargs: + deprecated_thing = "Creating NamedTuple classes using keyword arguments" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "Use the class-based or functional syntax instead." + ) + else: + deprecated_thing = "Failing to pass a value for the 'fields' parameter" + example = f"`{typename} = NamedTuple({typename!r}, [])`" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "To create a NamedTuple class with 0 fields " + "using the functional syntax, " + "pass an empty list, e.g. " + ) + example + "." + elif fields is None: + if kwargs: + raise TypeError( + "Cannot pass `None` as the 'fields' parameter " + "and also specify fields using keyword arguments" + ) + else: + deprecated_thing = "Passing `None` as the 'fields' parameter" + example = f"`{typename} = NamedTuple({typename!r}, [])`" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "To create a NamedTuple class with 0 fields " + "using the functional syntax, " + "pass an empty list, e.g. " + ) + example + "." + elif kwargs: + raise TypeError("Either list of fields or keywords" + " can be provided to NamedTuple, not both") + if fields is _marker or fields is None: + warnings.warn( + deprecation_msg.format(name=deprecated_thing, remove="3.15"), + DeprecationWarning, + stacklevel=2, + ) + fields = kwargs.items() + nt = _make_nmtuple(typename, fields, module=_caller()) + nt.__orig_bases__ = (NamedTuple,) + return nt + + +if hasattr(collections.abc, "Buffer"): + Buffer = collections.abc.Buffer +else: + class Buffer(abc.ABC): # noqa: B024 + """Base class for classes that implement the buffer protocol. + + The buffer protocol allows Python objects to expose a low-level + memory buffer interface. Before Python 3.12, it is not possible + to implement the buffer protocol in pure Python code, or even + to check whether a class implements the buffer protocol. In + Python 3.12 and higher, the ``__buffer__`` method allows access + to the buffer protocol from Python code, and the + ``collections.abc.Buffer`` ABC allows checking whether a class + implements the buffer protocol. + + To indicate support for the buffer protocol in earlier versions, + inherit from this ABC, either in a stub file or at runtime, + or use ABC registration. This ABC provides no methods, because + there is no Python-accessible methods shared by pre-3.12 buffer + classes. It is useful primarily for static checks. + + """ + + # As a courtesy, register the most common stdlib buffer classes. + Buffer.register(memoryview) + Buffer.register(bytearray) + Buffer.register(bytes) + + +# Backport of types.get_original_bases, available on 3.12+ in CPython +if hasattr(_types, "get_original_bases"): + get_original_bases = _types.get_original_bases +else: + def get_original_bases(cls, /): + """Return the class's "original" bases prior to modification by `__mro_entries__`. + + Examples:: + + from typing import TypeVar, Generic + from typing_extensions import NamedTuple, TypedDict + + T = TypeVar("T") + class Foo(Generic[T]): ... + class Bar(Foo[int], float): ... + class Baz(list[str]): ... + Eggs = NamedTuple("Eggs", [("a", int), ("b", str)]) + Spam = TypedDict("Spam", {"a": int, "b": str}) + + assert get_original_bases(Bar) == (Foo[int], float) + assert get_original_bases(Baz) == (list[str],) + assert get_original_bases(Eggs) == (NamedTuple,) + assert get_original_bases(Spam) == (TypedDict,) + assert get_original_bases(int) == (object,) + """ + try: + return cls.__dict__.get("__orig_bases__", cls.__bases__) + except AttributeError: + raise TypeError( + f'Expected an instance of type, not {type(cls).__name__!r}' + ) from None + + +# NewType is a class on Python 3.10+, making it pickleable +# The error message for subclassing instances of NewType was improved on 3.11+ +if sys.version_info >= (3, 11): + NewType = typing.NewType +else: + class NewType: + """NewType creates simple unique types with almost zero + runtime overhead. NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy callable that simply returns its argument. Usage:: + UserId = NewType('UserId', int) + def name_by_id(user_id: UserId) -> str: + ... + UserId('user') # Fails type check + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + num = UserId(5) + 1 # type: int + """ + + def __call__(self, obj, /): + return obj + + def __init__(self, name, tp): + self.__qualname__ = name + if '.' in name: + name = name.rpartition('.')[-1] + self.__name__ = name + self.__supertype__ = tp + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __mro_entries__(self, bases): + # We defined __mro_entries__ to get a better error message + # if a user attempts to subclass a NewType instance. bpo-46170 + supercls_name = self.__name__ + + class Dummy: + def __init_subclass__(cls): + subcls_name = cls.__name__ + raise TypeError( + f"Cannot subclass an instance of NewType. " + f"Perhaps you were looking for: " + f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`" + ) + + return (Dummy,) + + def __repr__(self): + return f'{self.__module__}.{self.__qualname__}' + + def __reduce__(self): + return self.__qualname__ + + if sys.version_info >= (3, 10): + # PEP 604 methods + # It doesn't make sense to have these methods on Python <3.10 + + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + +if hasattr(typing, "TypeAliasType"): + TypeAliasType = typing.TypeAliasType +else: + def _is_unionable(obj): + """Corresponds to is_unionable() in unionobject.c in CPython.""" + return obj is None or isinstance(obj, ( + type, + _types.GenericAlias, + _types.UnionType, + TypeAliasType, + )) + + class TypeAliasType: + """Create named, parameterized type aliases. + + This provides a backport of the new `type` statement in Python 3.12: + + type ListOrSet[T] = list[T] | set[T] + + is equivalent to: + + T = TypeVar("T") + ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,)) + + The name ListOrSet can then be used as an alias for the type it refers to. + + The type_params argument should contain all the type parameters used + in the value of the type alias. If the alias is not generic, this + argument is omitted. + + Static type checkers should only support type aliases declared using + TypeAliasType that follow these rules: + + - The first argument (the name) must be a string literal. + - The TypeAliasType instance must be immediately assigned to a variable + of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid, + as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)'). + + """ + + def __init__(self, name: str, value, *, type_params=()): + if not isinstance(name, str): + raise TypeError("TypeAliasType name must be a string") + self.__value__ = value + self.__type_params__ = type_params + + parameters = [] + for type_param in type_params: + if isinstance(type_param, TypeVarTuple): + parameters.extend(type_param) + else: + parameters.append(type_param) + self.__parameters__ = tuple(parameters) + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + # Setting this attribute closes the TypeAliasType from further modification + self.__name__ = name + + def __setattr__(self, name: str, value: object, /) -> None: + if hasattr(self, "__name__"): + self._raise_attribute_error(name) + super().__setattr__(name, value) + + def __delattr__(self, name: str, /) -> Never: + self._raise_attribute_error(name) + + def _raise_attribute_error(self, name: str) -> Never: + # Match the Python 3.12 error messages exactly + if name == "__name__": + raise AttributeError("readonly attribute") + elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}: + raise AttributeError( + f"attribute '{name}' of 'typing.TypeAliasType' objects " + "is not writable" + ) + else: + raise AttributeError( + f"'typing.TypeAliasType' object has no attribute '{name}'" + ) + + def __repr__(self) -> str: + return self.__name__ + + def __getitem__(self, parameters): + if not isinstance(parameters, tuple): + parameters = (parameters,) + parameters = [ + typing._type_check( + item, f'Subscripting {self.__name__} requires a type.' + ) + for item in parameters + ] + return typing._GenericAlias(self, tuple(parameters)) + + def __reduce__(self): + return self.__name__ + + def __init_subclass__(cls, *args, **kwargs): + raise TypeError( + "type 'typing_extensions.TypeAliasType' is not an acceptable base type" + ) + + # The presence of this method convinces typing._type_check + # that TypeAliasTypes are types. + def __call__(self): + raise TypeError("Type alias is not callable") + + if sys.version_info >= (3, 10): + def __or__(self, right): + # For forward compatibility with 3.12, reject Unions + # that are not accepted by the built-in Union. + if not _is_unionable(right): + return NotImplemented + return typing.Union[self, right] + + def __ror__(self, left): + if not _is_unionable(left): + return NotImplemented + return typing.Union[left, self] + + +if hasattr(typing, "is_protocol"): + is_protocol = typing.is_protocol + get_protocol_members = typing.get_protocol_members +else: + def is_protocol(tp: type, /) -> bool: + """Return True if the given type is a Protocol. + + Example:: + + >>> from typing_extensions import Protocol, is_protocol + >>> class P(Protocol): + ... def a(self) -> str: ... + ... b: int + >>> is_protocol(P) + True + >>> is_protocol(int) + False + """ + return ( + isinstance(tp, type) + and getattr(tp, '_is_protocol', False) + and tp is not Protocol + and tp is not typing.Protocol + ) + + def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]: + """Return the set of members defined in a Protocol. + + Example:: + + >>> from typing_extensions import Protocol, get_protocol_members + >>> class P(Protocol): + ... def a(self) -> str: ... + ... b: int + >>> get_protocol_members(P) + frozenset({'a', 'b'}) + + Raise a TypeError for arguments that are not Protocols. + """ + if not is_protocol(tp): + raise TypeError(f'{tp!r} is not a Protocol') + if hasattr(tp, '__protocol_attrs__'): + return frozenset(tp.__protocol_attrs__) + return frozenset(_get_protocol_attrs(tp)) + + +if hasattr(typing, "Doc"): + Doc = typing.Doc +else: + class Doc: + """Define the documentation of a type annotation using ``Annotated``, to be + used in class attributes, function and method parameters, return values, + and variables. + + The value should be a positional-only string literal to allow static tools + like editors and documentation generators to use it. + + This complements docstrings. + + The string value passed is available in the attribute ``documentation``. + + Example:: + + >>> from typing_extensions import Annotated, Doc + >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ... + """ + def __init__(self, documentation: str, /) -> None: + self.documentation = documentation + + def __repr__(self) -> str: + return f"Doc({self.documentation!r})" + + def __hash__(self) -> int: + return hash(self.documentation) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Doc): + return NotImplemented + return self.documentation == other.documentation + + +_CapsuleType = getattr(_types, "CapsuleType", None) + +if _CapsuleType is None: + try: + import _socket + except ImportError: + pass + else: + _CAPI = getattr(_socket, "CAPI", None) + if _CAPI is not None: + _CapsuleType = type(_CAPI) + +if _CapsuleType is not None: + CapsuleType = _CapsuleType + __all__.append("CapsuleType") + + +# Aliases for items that have always been in typing. +# Explicitly assign these (rather than using `from typing import *` at the top), +# so that we get a CI error if one of these is deleted from typing.py +# in a future version of Python +AbstractSet = typing.AbstractSet +AnyStr = typing.AnyStr +BinaryIO = typing.BinaryIO +Callable = typing.Callable +Collection = typing.Collection +Container = typing.Container +Dict = typing.Dict +ForwardRef = typing.ForwardRef +FrozenSet = typing.FrozenSet +Generic = typing.Generic +Hashable = typing.Hashable +IO = typing.IO +ItemsView = typing.ItemsView +Iterable = typing.Iterable +Iterator = typing.Iterator +KeysView = typing.KeysView +List = typing.List +Mapping = typing.Mapping +MappingView = typing.MappingView +Match = typing.Match +MutableMapping = typing.MutableMapping +MutableSequence = typing.MutableSequence +MutableSet = typing.MutableSet +Optional = typing.Optional +Pattern = typing.Pattern +Reversible = typing.Reversible +Sequence = typing.Sequence +Set = typing.Set +Sized = typing.Sized +TextIO = typing.TextIO +Tuple = typing.Tuple +Union = typing.Union +ValuesView = typing.ValuesView +cast = typing.cast +no_type_check = typing.no_type_check +no_type_check_decorator = typing.no_type_check_decorator diff --git a/env/Lib/site-packages/yarl-1.9.4.dist-info/INSTALLER b/env/Lib/site-packages/yarl-1.9.4.dist-info/INSTALLER new file mode 100644 index 0000000..a1b589e --- /dev/null +++ b/env/Lib/site-packages/yarl-1.9.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/env/Lib/site-packages/yarl-1.9.4.dist-info/LICENSE b/env/Lib/site-packages/yarl-1.9.4.dist-info/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/env/Lib/site-packages/yarl-1.9.4.dist-info/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/env/Lib/site-packages/yarl-1.9.4.dist-info/METADATA b/env/Lib/site-packages/yarl-1.9.4.dist-info/METADATA new file mode 100644 index 0000000..548567b --- /dev/null +++ b/env/Lib/site-packages/yarl-1.9.4.dist-info/METADATA @@ -0,0 +1,1086 @@ +Metadata-Version: 2.1 +Name: yarl +Version: 1.9.4 +Summary: Yet another URL library +Home-page: https://github.com/aio-libs/yarl +Author: Andrew Svetlov +Author-email: andrew.svetlov@gmail.com +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache-2.0 +Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org +Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org +Project-URL: CI: GitHub Workflows, https://github.com/aio-libs/yarl/actions?query=branch:master +Project-URL: Code of Conduct, https://github.com/aio-libs/.github/blob/master/CODE_OF_CONDUCT.md +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/yarl +Project-URL: Docs: Changelog, https://yarl.aio-libs.org/en/latest/changes/ +Project-URL: Docs: RTD, https://yarl.aio-libs.org +Project-URL: GitHub: issues, https://github.com/aio-libs/yarl/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/yarl +Keywords: cython,cext,yarl +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: NOTICE +Requires-Dist: idna >=2.0 +Requires-Dist: multidict >=4.0 +Requires-Dist: typing-extensions >=3.7.4 ; python_version < "3.8" + +yarl +==== + +The module provides handy URL class for URL parsing and changing. + +.. image:: https://github.com/aio-libs/yarl/workflows/CI/badge.svg + :target: https://github.com/aio-libs/yarl/actions?query=workflow%3ACI + :align: right + +.. image:: https://codecov.io/gh/aio-libs/yarl/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/yarl + +.. image:: https://badge.fury.io/py/yarl.svg + :target: https://badge.fury.io/py/yarl + + +.. image:: https://readthedocs.org/projects/yarl/badge/?version=latest + :target: https://yarl.aio-libs.org + + +.. image:: https://img.shields.io/pypi/pyversions/yarl.svg + :target: https://pypi.python.org/pypi/yarl + +.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs:matrix.org + :alt: Matrix Room — #aio-libs:matrix.org + +.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs-space:matrix.org + :alt: Matrix Space — #aio-libs-space:matrix.org + +Introduction +------------ + +Url is constructed from ``str``: + +.. code-block:: pycon + + >>> from yarl import URL + >>> url = URL('https://www.python.org/~guido?arg=1#frag') + >>> url + URL('https://www.python.org/~guido?arg=1#frag') + +All url parts: *scheme*, *user*, *password*, *host*, *port*, *path*, +*query* and *fragment* are accessible by properties: + +.. code-block:: pycon + + >>> url.scheme + 'https' + >>> url.host + 'www.python.org' + >>> url.path + '/~guido' + >>> url.query_string + 'arg=1' + >>> url.query + + >>> url.fragment + 'frag' + +All url manipulations produce a new url object: + +.. code-block:: pycon + + >>> url = URL('https://www.python.org') + >>> url / 'foo' / 'bar' + URL('https://www.python.org/foo/bar') + >>> url / 'foo' % {'bar': 'baz'} + URL('https://www.python.org/foo?bar=baz') + +Strings passed to constructor and modification methods are +automatically encoded giving canonical representation as result: + +.. code-block:: pycon + + >>> url = URL('https://www.python.org/шлях') + >>> url + URL('https://www.python.org/%D1%88%D0%BB%D1%8F%D1%85') + +Regular properties are *percent-decoded*, use ``raw_`` versions for +getting *encoded* strings: + +.. code-block:: pycon + + >>> url.path + '/шлях' + + >>> url.raw_path + '/%D1%88%D0%BB%D1%8F%D1%85' + +Human readable representation of URL is available as ``.human_repr()``: + +.. code-block:: pycon + + >>> url.human_repr() + 'https://www.python.org/шлях' + +For full documentation please read https://yarl.aio-libs.org. + + +Installation +------------ + +:: + + $ pip install yarl + +The library is Python 3 only! + +PyPI contains binary wheels for Linux, Windows and MacOS. If you want to install +``yarl`` on another operating system (like *Alpine Linux*, which is not +manylinux-compliant because of the missing glibc and therefore, cannot be +used with our wheels) the the tarball will be used to compile the library from +the source code. It requires a C compiler and and Python headers installed. + +To skip the compilation you must explicitly opt-in by using a PEP 517 +configuration setting ``pure-python``, or setting the ``YARL_NO_EXTENSIONS`` +environment variable to a non-empty value, e.g.: + +.. code-block:: console + + $ pip install yarl --config-settings=pure-python=false + +Please note that the pure-Python (uncompiled) version is much slower. However, +PyPy always uses a pure-Python implementation, and, as such, it is unaffected +by this variable. + +Dependencies +------------ + +YARL requires multidict_ library. + + +API documentation +------------------ + +The documentation is located at https://yarl.aio-libs.org. + + +Why isn't boolean supported by the URL query API? +------------------------------------------------- + +There is no standard for boolean representation of boolean values. + +Some systems prefer ``true``/``false``, others like ``yes``/``no``, ``on``/``off``, +``Y``/``N``, ``1``/``0``, etc. + +``yarl`` cannot make an unambiguous decision on how to serialize ``bool`` values because +it is specific to how the end-user's application is built and would be different for +different apps. The library doesn't accept booleans in the API; a user should convert +bools into strings using own preferred translation protocol. + + +Comparison with other URL libraries +------------------------------------ + +* furl (https://pypi.python.org/pypi/furl) + + The library has rich functionality but the ``furl`` object is mutable. + + I'm afraid to pass this object into foreign code: who knows if the + code will modify my url in a terrible way while I just want to send URL + with handy helpers for accessing URL properties. + + ``furl`` has other non-obvious tricky things but the main objection + is mutability. + +* URLObject (https://pypi.python.org/pypi/URLObject) + + URLObject is immutable, that's pretty good. + + Every URL change generates a new URL object. + + But the library doesn't do any decode/encode transformations leaving the + end user to cope with these gory details. + + +Source code +----------- + +The project is hosted on GitHub_ + +Please file an issue on the `bug tracker +`_ if you have found a bug +or have some suggestion in order to improve the library. + +The library uses `Azure Pipelines `_ for +Continuous Integration. + +Discussion list +--------------- + +*aio-libs* google group: https://groups.google.com/forum/#!forum/aio-libs + +Feel free to post your questions and ideas here. + + +Authors and License +------------------- + +The ``yarl`` package is written by Andrew Svetlov. + +It's *Apache 2* licensed and freely available. + + +.. _GitHub: https://github.com/aio-libs/yarl + +.. _multidict: https://github.com/aio-libs/multidict + +.. + You should *NOT* be adding new change log entries to this file, this + file is managed by towncrier. You *may* edit previous change logs to + fix problems like typo corrections or such. + To add a new change log entry, please see + https://pip.pypa.io/en/latest/development/#adding-a-news-entry + we named the news folder "changes". + + WARNING: Don't drop the next directive! + +.. towncrier release notes start + +1.9.4 (2023-12-06) +================== + +Bug fixes +--------- + +- Started raising ``TypeError`` when a string value is passed into + ``yarl.URL.build()`` as the ``port`` argument -- by `@commonism `__. + + Previously the empty string as port would create malformed URLs when rendered as string representations. (`#883 `__) + + +Packaging updates and notes for downstreams +------------------------------------------- + +- The leading ``--`` has been dropped from the `PEP 517 `__ in-tree build + backend config setting names. ``--pure-python`` is now just ``pure-python`` + -- by `@webknjaz `__. + + The usage now looks as follows: + + .. code-block:: console + + $ python -m build \ + --config-setting=pure-python=true \ + --config-setting=with-cython-tracing=true + + (`#963 `__) + + +Contributor-facing changes +-------------------------- + +- A step-by-step ``Release Guide`` guide has + been added, describing how to release *yarl* -- by `@webknjaz `__. + + This is primarily targeting maintainers. (`#960 `__) +- Coverage collection has been implemented for the Cython modules + -- by `@webknjaz `__. + + It will also be reported to Codecov from any non-release CI jobs. + + To measure coverage in a development environment, *yarl* can be + installed in editable mode, which requires an environment variable + ``YARL_CYTHON_TRACING=1`` to be set: + + .. code-block:: console + + $ YARL_CYTHON_TRACING=1 python -Im pip install -e . + + Editable install produces C-files required for the Cython coverage + plugin to map the measurements back to the PYX-files. (`#961 `__) +- It is now possible to request line tracing in Cython builds using the + ``with-cython-tracing`` `PEP 517 `__ config setting + -- `@webknjaz `__. + + This can be used in CI and development environment to measure coverage + on Cython modules, but is not normally useful to the end-users or + downstream packagers. + + Here's a usage example: + + .. code-block:: console + + $ python -Im pip install . --config-settings=with-cython-tracing=true + + For editable installs, this setting is on by default. Otherwise, it's + off unless requested explicitly. (`#962 `__) + + +1.9.3 (2023-11-20) +================== + +Bug fixes +--------- + +- Stopped dropping trailing slashes in ``yarl.URL.joinpath()`` -- by `@gmacon `__. (`#862 `__, `#866 `__) +- Started accepting string subclasses in ``__truediv__()`` operations (``URL / segment``) -- by `@mjpieters `__. (`#871 `__, `#884 `__) +- Fixed the human representation of URLs with square brackets in usernames and passwords -- by `@mjpieters `__. (`#876 `__, `#882 `__) +- Updated type hints to include ``URL.missing_port()``, ``URL.__bytes__()`` + and the ``encoding`` argument to ``yarl.URL.joinpath()`` + -- by `@mjpieters `__. (`#891 `__) + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Integrated Cython 3 to enable building *yarl* under Python 3.12 -- by `@mjpieters `__. (`#829 `__, `#881 `__) +- Declared modern ``setuptools.build_meta`` as the `PEP 517 `__ build + backend in ``pyproject.toml`` explicitly -- by `@webknjaz `__. (`#886 `__) +- Converted most of the packaging setup into a declarative ``setup.cfg`` + config -- by `@webknjaz `__. (`#890 `__) +- The packaging is replaced from an old-fashioned ``setup.py`` to an + in-tree `PEP 517 `__ build backend -- by `@webknjaz `__. + + Whenever the end-users or downstream packagers need to build ``yarl`` from + source (a Git checkout or an sdist), they may pass a ``config_settings`` + flag ``--pure-python``. If this flag is not set, a C-extension will be built + and included into the distribution. + + Here is how this can be done with ``pip``: + + .. code-block:: console + + $ python -m pip install . --config-settings=--pure-python=false + + This will also work with ``-e | --editable``. + + The same can be achieved via ``pypa/build``: + + .. code-block:: console + + $ python -m build --config-setting=--pure-python=false + + Adding ``-w | --wheel`` can force ``pypa/build`` produce a wheel from source + directly, as opposed to building an ``sdist`` and then building from it. (`#893 `__) + + .. attention:: + + v1.9.3 was the only version using the ``--pure-python`` setting name. + Later versions dropped the ``--`` prefix, making it just ``pure-python``. + +- Declared Python 3.12 supported officially in the distribution package metadata + -- by `@edgarrmondragon `__. (`#942 `__) + + +Contributor-facing changes +-------------------------- + +- A regression test for no-host URLs was added per `#821 `__ + and ``3986`` -- by `@kenballus `__. (`#821 `__, `#822 `__) +- Started testing *yarl* against Python 3.12 in CI -- by `@mjpieters `__. (`#881 `__) +- All Python 3.12 jobs are now marked as required to pass in CI + -- by `@edgarrmondragon `__. (`#942 `__) +- MyST is now integrated in Sphinx -- by `@webknjaz `__. + + This allows the contributors to author new documents in Markdown + when they have difficulties with going straight RST. (`#953 `__) + + +1.9.2 (2023-04-25) +================== + +Bugfixes +-------- + +- Fix regression with ``__truediv__`` and absolute URLs with empty paths causing the raw path to lack the leading ``/``. + (`#854 `_) + + +1.9.1 (2023-04-21) +================== + +Bugfixes +-------- + +- Marked tests that fail on older Python patch releases (< 3.7.10, < 3.8.8 and < 3.9.2) as expected to fail due to missing a security fix for CVE-2021-23336. (`#850 `_) + + +1.9.0 (2023-04-19) +================== + +This release was never published to PyPI, due to issues with the build process. + +Features +-------- + +- Added ``URL.joinpath(*elements)``, to create a new URL appending multiple path elements. (`#704 `_) +- Made ``URL.__truediv__()`` return ``NotImplemented`` if called with an + unsupported type — by `@michaeljpeters `__. + (`#832 `_) + + +Bugfixes +-------- + +- Path normalization for absolute URLs no longer raises a ValueError exception + when ``..`` segments would otherwise go beyond the URL path root. + (`#536 `_) +- Fixed an issue with update_query() not getting rid of the query when argument is None. (`#792 `_) +- Added some input restrictions on with_port() function to prevent invalid boolean inputs or out of valid port inputs; handled incorrect 0 port representation. (`#793 `_) +- Made ``yarl.URL.build()`` raise a ``TypeError`` if the ``host`` argument is ``None`` — by `@paulpapacz `__. (`#808 `_) +- Fixed an issue with ``update_query()`` getting rid of the query when the argument + is empty but not ``None``. (`#845 `_) + + +Misc +---- + +- `#220 `_ + + +1.8.2 (2022-12-03) +================== + +This is the first release that started shipping wheels for Python 3.11. + + +1.8.1 (2022-08-01) +================== + +Misc +---- + +- `#694 `_, `#699 `_, `#700 `_, `#701 `_, `#702 `_, `#703 `_, `#739 `_ + + +1.8.0 (2022-08-01) +================== + +Features +-------- + +- Added ``URL.raw_suffix``, ``URL.suffix``, ``URL.raw_suffixes``, ``URL.suffixes``, ``URL.with_suffix``. (`#613 `_) + + +Improved Documentation +---------------------- + +- Fixed broken internal references to ``yarl.URL.human_repr()``. + (`#665 `_) +- Fixed broken external references to ``multidict:index`` docs. (`#665 `_) + + +Deprecations and Removals +------------------------- + +- Dropped Python 3.6 support. (`#672 `_) + + +Misc +---- + +- `#646 `_, `#699 `_, `#701 `_ + + +1.7.2 (2021-11-01) +================== + +Bugfixes +-------- + +- Changed call in ``with_port()`` to stop reencoding parts of the URL that were already encoded. (`#623 `_) + + +1.7.1 (2021-10-07) +================== + +Bugfixes +-------- + +- Fix 1.7.0 build error + +1.7.0 (2021-10-06) +================== + +Features +-------- + +- Add ``__bytes__()`` magic method so that ``bytes(url)`` will work and use optimal ASCII encoding. + (`#582 `_) +- Started shipping platform-specific arm64 wheels for Apple Silicon. (`#622 `_) +- Started shipping platform-specific wheels with the ``musl`` tag targeting typical Alpine Linux runtimes. (`#622 `_) +- Added support for Python 3.10. (`#622 `_) + + +1.6.3 (2020-11-14) +================== + +Bugfixes +-------- + +- No longer loose characters when decoding incorrect percent-sequences (like ``%e2%82%f8``). All non-decodable percent-sequences are now preserved. + `#517 `_ +- Provide x86 Windows wheels. + `#535 `_ + + +---- + + +1.6.2 (2020-10-12) +================== + + +Bugfixes +-------- + +- Provide generated ``.c`` files in TarBall distribution. + `#530 `_ + +1.6.1 (2020-10-12) +================== + +Features +-------- + +- Provide wheels for ``aarch64``, ``i686``, ``ppc64le``, ``s390x`` architectures on + Linux as well as ``x86_64``. + `#507 `_ +- Provide wheels for Python 3.9. + `#526 `_ + +Bugfixes +-------- + +- ``human_repr()`` now always produces valid representation equivalent to the original URL (if the original URL is valid). + `#511 `_ +- Fixed requoting a single percent followed by a percent-encoded character in the Cython implementation. + `#514 `_ +- Fix ValueError when decoding ``%`` which is not followed by two hexadecimal digits. + `#516 `_ +- Fix decoding ``%`` followed by a space and hexadecimal digit. + `#520 `_ +- Fix annotation of ``with_query()``/``update_query()`` methods for ``key=[val1, val2]`` case. + `#528 `_ + +Removal +------- + +- Drop Python 3.5 support; Python 3.6 is the minimal supported Python version. + + +---- + + +1.6.0 (2020-09-23) +================== + +Features +-------- + +- Allow for int and float subclasses in query, while still denying bool. + `#492 `_ + + +Bugfixes +-------- + +- Do not requote arguments in ``URL.build()``, ``with_xxx()`` and in ``/`` operator. + `#502 `_ +- Keep IPv6 brackets in ``origin()``. + `#504 `_ + + +---- + + +1.5.1 (2020-08-01) +================== + +Bugfixes +-------- + +- Fix including relocated internal ``yarl._quoting_c`` C-extension into published PyPI dists. + `#485 `_ + + +Misc +---- + +- `#484 `_ + + +---- + + +1.5.0 (2020-07-26) +================== + +Features +-------- + +- Convert host to lowercase on URL building. + `#386 `_ +- Allow using ``mod`` operator (``%``) for updating query string (an alias for ``update_query()`` method). + `#435 `_ +- Allow use of sequences such as ``list`` and ``tuple`` in the values + of a mapping such as ``dict`` to represent that a key has many values:: + + url = URL("http://example.com") + assert url.with_query({"a": [1, 2]}) == URL("http://example.com/?a=1&a=2") + + `#443 `_ +- Support ``URL.build()`` with scheme and path (creates a relative URL). + `#464 `_ +- Cache slow IDNA encode/decode calls. + `#476 `_ +- Add ``@final`` / ``Final`` type hints + `#477 `_ +- Support URL authority/raw_authority properties and authority argument of ``URL.build()`` method. + `#478 `_ +- Hide the library implementation details, make the exposed public list very clean. + `#483 `_ + + +Bugfixes +-------- + +- Fix tests with newer Python (3.7.6, 3.8.1 and 3.9.0+). + `#409 `_ +- Fix a bug where query component, passed in a form of mapping or sequence, is unquoted in unexpected way. + `#426 `_ +- Hide ``Query`` and ``QueryVariable`` type aliases in ``__init__.pyi``, now they are prefixed with underscore. + `#431 `_ +- Keep IPv6 brackets after updating port/user/password. + `#451 `_ + + +---- + + +1.4.2 (2019-12-05) +================== + +Features +-------- + +- Workaround for missing ``str.isascii()`` in Python 3.6 + `#389 `_ + + +---- + + +1.4.1 (2019-11-29) +================== + +* Fix regression, make the library work on Python 3.5 and 3.6 again. + +1.4.0 (2019-11-29) +================== + +* Distinguish an empty password in URL from a password not provided at all (#262) + +* Fixed annotations for optional parameters of ``URL.build`` (#309) + +* Use None as default value of ``user`` parameter of ``URL.build`` (#309) + +* Enforce building C Accelerated modules when installing from source tarball, use + ``YARL_NO_EXTENSIONS`` environment variable for falling back to (slower) Pure Python + implementation (#329) + +* Drop Python 3.5 support + +* Fix quoting of plus in path by pure python version (#339) + +* Don't create a new URL if fragment is unchanged (#292) + +* Included in error message the path that produces starting slash forbidden error (#376) + +* Skip slow IDNA encoding for ASCII-only strings (#387) + + +1.3.0 (2018-12-11) +================== + +* Fix annotations for ``query`` parameter (#207) + +* An incoming query sequence can have int variables (the same as for + Mapping type) (#208) + +* Add ``URL.explicit_port`` property (#218) + +* Give a friendlier error when port can't be converted to int (#168) + +* ``bool(URL())`` now returns ``False`` (#272) + +1.2.6 (2018-06-14) +================== + +* Drop Python 3.4 trove classifier (#205) + +1.2.5 (2018-05-23) +================== + +* Fix annotations for ``build`` (#199) + +1.2.4 (2018-05-08) +================== + +* Fix annotations for ``cached_property`` (#195) + +1.2.3 (2018-05-03) +================== + +* Accept ``str`` subclasses in ``URL`` constructor (#190) + +1.2.2 (2018-05-01) +================== + +* Fix build + +1.2.1 (2018-04-30) +================== + +* Pin minimal required Python to 3.5.3 (#189) + +1.2.0 (2018-04-30) +================== + +* Forbid inheritance, replace ``__init__`` with ``__new__`` (#171) + +* Support PEP-561 (provide type hinting marker) (#182) + +1.1.1 (2018-02-17) +================== + +* Fix performance regression: don't encode empty ``netloc`` (#170) + +1.1.0 (2018-01-21) +================== + +* Make pure Python quoter consistent with Cython version (#162) + +1.0.0 (2018-01-15) +================== + +* Use fast path if quoted string does not need requoting (#154) + +* Speed up quoting/unquoting by ``_Quoter`` and ``_Unquoter`` classes (#155) + +* Drop ``yarl.quote`` and ``yarl.unquote`` public functions (#155) + +* Add custom string writer, reuse static buffer if available (#157) + Code is 50-80 times faster than Pure Python version (was 4-5 times faster) + +* Don't recode IP zone (#144) + +* Support ``encoded=True`` in ``yarl.URL.build()`` (#158) + +* Fix updating query with multiple keys (#160) + +0.18.0 (2018-01-10) +=================== + +* Fallback to IDNA 2003 if domain name is not IDNA 2008 compatible (#152) + +0.17.0 (2017-12-30) +=================== + +* Use IDNA 2008 for domain name processing (#149) + +0.16.0 (2017-12-07) +=================== + +* Fix raising ``TypeError`` by ``url.query_string()`` after + ``url.with_query({})`` (empty mapping) (#141) + +0.15.0 (2017-11-23) +=================== + +* Add ``raw_path_qs`` attribute (#137) + +0.14.2 (2017-11-14) +=================== + +* Restore ``strict`` parameter as no-op in ``quote`` / ``unquote`` + +0.14.1 (2017-11-13) +=================== + +* Restore ``strict`` parameter as no-op for sake of compatibility with + aiohttp 2.2 + +0.14.0 (2017-11-11) +=================== + +* Drop strict mode (#123) + +* Fix ``"ValueError: Unallowed PCT %"`` when there's a ``"%"`` in the URL (#124) + +0.13.0 (2017-10-01) +=================== + +* Document ``encoded`` parameter (#102) + +* Support relative URLs like ``'?key=value'`` (#100) + +* Unsafe encoding for QS fixed. Encode ``;`` character in value parameter (#104) + +* Process passwords without user names (#95) + +0.12.0 (2017-06-26) +=================== + +* Properly support paths without leading slash in ``URL.with_path()`` (#90) + +* Enable type annotation checks + +0.11.0 (2017-06-26) +=================== + +* Normalize path (#86) + +* Clear query and fragment parts in ``.with_path()`` (#85) + +0.10.3 (2017-06-13) +=================== + +* Prevent double URL arguments unquoting (#83) + +0.10.2 (2017-05-05) +=================== + +* Unexpected hash behavior (#75) + + +0.10.1 (2017-05-03) +=================== + +* Unexpected compare behavior (#73) + +* Do not quote or unquote + if not a query string. (#74) + + +0.10.0 (2017-03-14) +=================== + +* Added ``URL.build`` class method (#58) + +* Added ``path_qs`` attribute (#42) + + +0.9.8 (2017-02-16) +================== + +* Do not quote ``:`` in path + + +0.9.7 (2017-02-16) +================== + +* Load from pickle without _cache (#56) + +* Percent-encoded pluses in path variables become spaces (#59) + + +0.9.6 (2017-02-15) +================== + +* Revert backward incompatible change (BaseURL) + + +0.9.5 (2017-02-14) +================== + +* Fix BaseURL rich comparison support + + +0.9.4 (2017-02-14) +================== + +* Use BaseURL + + +0.9.3 (2017-02-14) +================== + +* Added BaseURL + + +0.9.2 (2017-02-08) +================== + +* Remove debug print + + +0.9.1 (2017-02-07) +================== + +* Do not lose tail chars (#45) + + +0.9.0 (2017-02-07) +================== + +* Allow to quote ``%`` in non strict mode (#21) + +* Incorrect parsing of query parameters with %3B (;) inside (#34) + +* Fix core dumps (#41) + +* ``tmpbuf`` - compiling error (#43) + +* Added ``URL.update_path()`` method + +* Added ``URL.update_query()`` method (#47) + + +0.8.1 (2016-12-03) +================== + +* Fix broken aiohttp: revert back ``quote`` / ``unquote``. + + +0.8.0 (2016-12-03) +================== + +* Support more verbose error messages in ``.with_query()`` (#24) + +* Don't percent-encode ``@`` and ``:`` in path (#32) + +* Don't expose ``yarl.quote`` and ``yarl.unquote``, these functions are + part of private API + +0.7.1 (2016-11-18) +================== + +* Accept not only ``str`` but all classes inherited from ``str`` also (#25) + +0.7.0 (2016-11-07) +================== + +* Accept ``int`` as value for ``.with_query()`` + +0.6.0 (2016-11-07) +================== + +* Explicitly use UTF8 encoding in ``setup.py`` (#20) +* Properly unquote non-UTF8 strings (#19) + +0.5.3 (2016-11-02) +================== + +* Don't use ``typing.NamedTuple`` fields but indexes on URL construction + +0.5.2 (2016-11-02) +================== + +* Inline ``_encode`` class method + +0.5.1 (2016-11-02) +================== + +* Make URL construction faster by removing extra classmethod calls + +0.5.0 (2016-11-02) +================== + +* Add Cython optimization for quoting/unquoting +* Provide binary wheels + +0.4.3 (2016-09-29) +================== + +* Fix typing stubs + +0.4.2 (2016-09-29) +================== + +* Expose ``quote()`` and ``unquote()`` as public API + +0.4.1 (2016-09-28) +================== + +* Support empty values in query (``'/path?arg'``) + +0.4.0 (2016-09-27) +================== + +* Introduce ``relative()`` (#16) + +0.3.2 (2016-09-27) +================== + +* Typo fixes #15 + +0.3.1 (2016-09-26) +================== + +* Support sequence of pairs as ``with_query()`` parameter + +0.3.0 (2016-09-26) +================== + +* Introduce ``is_default_port()`` + +0.2.1 (2016-09-26) +================== + +* Raise ValueError for URLs like 'http://:8080/' + +0.2.0 (2016-09-18) +================== + +* Avoid doubling slashes when joining paths (#13) + +* Appending path starting from slash is forbidden (#12) + +0.1.4 (2016-09-09) +================== + +* Add ``kwargs`` support for ``with_query()`` (#10) + +0.1.3 (2016-09-07) +================== + +* Document ``with_query()``, ``with_fragment()`` and ``origin()`` + +* Allow ``None`` for ``with_query()`` and ``with_fragment()`` + +0.1.2 (2016-09-07) +================== + +* Fix links, tune docs theme. + +0.1.1 (2016-09-06) +================== + +* Update README, old version used obsolete API + +0.1.0 (2016-09-06) +================== + +* The library was deeply refactored, bytes are gone away but all + accepted strings are encoded if needed. + +0.0.1 (2016-08-30) +================== + +* The first release. diff --git a/env/Lib/site-packages/yarl-1.9.4.dist-info/NOTICE b/env/Lib/site-packages/yarl-1.9.4.dist-info/NOTICE new file mode 100644 index 0000000..fa53b2b --- /dev/null +++ b/env/Lib/site-packages/yarl-1.9.4.dist-info/NOTICE @@ -0,0 +1,13 @@ + Copyright 2016-2021, Andrew Svetlov and aio-libs team + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/env/Lib/site-packages/yarl-1.9.4.dist-info/RECORD b/env/Lib/site-packages/yarl-1.9.4.dist-info/RECORD new file mode 100644 index 0000000..37fb1ab --- /dev/null +++ b/env/Lib/site-packages/yarl-1.9.4.dist-info/RECORD @@ -0,0 +1,20 @@ +yarl-1.9.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +yarl-1.9.4.dist-info/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +yarl-1.9.4.dist-info/METADATA,sha256=nl70RbkV_cMgB7D_nR9wKf7UBU4qp-NYD-tm3lOzse0,32934 +yarl-1.9.4.dist-info/NOTICE,sha256=VtasbIEFwKUTBMIdsGDjYa-ajqCvmnXCOcKLXRNpODg,609 +yarl-1.9.4.dist-info/RECORD,, +yarl-1.9.4.dist-info/WHEEL,sha256=badvNS-y9fEq0X-qzdZYvql_JFjI7Xfw-wR8FsjoK0I,102 +yarl-1.9.4.dist-info/top_level.txt,sha256=vf3SJuQh-k7YtvsUrV_OPOrT9Kqn0COlk7IPYyhtGkQ,5 +yarl/__init__.py,sha256=1UvmVvUEXYJa-vxxO1hn6PRhiUdtedOaH457UamY3qE,154 +yarl/__init__.pyi,sha256=7YGQVdTkGeYMt1ICjIGITqnKWCgexbZiTkR0HYY6c_o,4028 +yarl/__pycache__/__init__.cpython-311.pyc,, +yarl/__pycache__/_quoting.cpython-311.pyc,, +yarl/__pycache__/_quoting_py.cpython-311.pyc,, +yarl/__pycache__/_url.cpython-311.pyc,, +yarl/_quoting.py,sha256=VwNdxLvb8CjZUjSEfWOOnWx7jPQdr8oXT_QWa_bhcvs,537 +yarl/_quoting_c.cp311-win_amd64.pyd,sha256=QOkaqjaaXBccDTBjBweum7ZEEv7fFJruz6VweiMk93A,95744 +yarl/_quoting_c.pyi,sha256=plPeUkIbXp4Hzi0AbYII4JA0H9tCjtjw-UUPU5Na1s0,447 +yarl/_quoting_c.pyx,sha256=L1-WLIZp0e_khrXD0V79CnZkETRxuzPOw1hD0IZDWlQ,11496 +yarl/_quoting_py.py,sha256=K419wlfyIlGM7-UbxobWv8lOkger8Ut7rrgoJ4xDgAU,6370 +yarl/_url.py,sha256=JavPyzjmEDeRL0_sNJb-FUHRLphXlnE7MUTdR7BsE0c,38182 +yarl/py.typed,sha256=ay5OMO475PlcZ_Fbun9maHW7Y6MBTk0UXL4ztHx3Iug,14 diff --git a/env/Lib/site-packages/yarl-1.9.4.dist-info/WHEEL b/env/Lib/site-packages/yarl-1.9.4.dist-info/WHEEL new file mode 100644 index 0000000..6d16045 --- /dev/null +++ b/env/Lib/site-packages/yarl-1.9.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: false +Tag: cp311-cp311-win_amd64 + diff --git a/env/Lib/site-packages/yarl-1.9.4.dist-info/top_level.txt b/env/Lib/site-packages/yarl-1.9.4.dist-info/top_level.txt new file mode 100644 index 0000000..e93e8bd --- /dev/null +++ b/env/Lib/site-packages/yarl-1.9.4.dist-info/top_level.txt @@ -0,0 +1 @@ +yarl diff --git a/env/Lib/site-packages/yarl/__init__.py b/env/Lib/site-packages/yarl/__init__.py new file mode 100644 index 0000000..127721a --- /dev/null +++ b/env/Lib/site-packages/yarl/__init__.py @@ -0,0 +1,5 @@ +from ._url import URL, cache_clear, cache_configure, cache_info + +__version__ = "1.9.4" + +__all__ = ("URL", "cache_clear", "cache_configure", "cache_info") diff --git a/env/Lib/site-packages/yarl/__init__.pyi b/env/Lib/site-packages/yarl/__init__.pyi new file mode 100644 index 0000000..5fd4bd0 --- /dev/null +++ b/env/Lib/site-packages/yarl/__init__.pyi @@ -0,0 +1,121 @@ +import sys +from functools import _CacheInfo +from typing import Any, Mapping, Optional, Sequence, Tuple, Type, Union, overload + +import multidict + +if sys.version_info >= (3, 8): + from typing import Final, TypedDict, final +else: + from typing_extensions import Final, TypedDict, final + +_SimpleQuery = Union[str, int, float] +_QueryVariable = Union[_SimpleQuery, Sequence[_SimpleQuery]] +_Query = Union[ + None, str, Mapping[str, _QueryVariable], Sequence[Tuple[str, _QueryVariable]] +] + +@final +class URL: + scheme: Final[str] + raw_user: Final[str] + user: Final[Optional[str]] + raw_password: Final[Optional[str]] + password: Final[Optional[str]] + raw_host: Final[Optional[str]] + host: Final[Optional[str]] + port: Final[Optional[int]] + explicit_port: Final[Optional[int]] + raw_authority: Final[str] + authority: Final[str] + raw_path: Final[str] + path: Final[str] + raw_query_string: Final[str] + query_string: Final[str] + path_qs: Final[str] + raw_path_qs: Final[str] + raw_fragment: Final[str] + fragment: Final[str] + query: Final[multidict.MultiDict[str]] + raw_name: Final[str] + name: Final[str] + raw_suffix: Final[str] + suffix: Final[str] + raw_suffixes: Final[Tuple[str, ...]] + suffixes: Final[Tuple[str, ...]] + raw_parts: Final[Tuple[str, ...]] + parts: Final[Tuple[str, ...]] + parent: Final[URL] + def __init__( + self, val: Union[str, "URL"] = ..., *, encoded: bool = ... + ) -> None: ... + @classmethod + def build( + cls, + *, + scheme: str = ..., + authority: str = ..., + user: Optional[str] = ..., + password: Optional[str] = ..., + host: str = ..., + port: Optional[int] = ..., + path: str = ..., + query: Optional[_Query] = ..., + query_string: str = ..., + fragment: str = ..., + encoded: bool = ... + ) -> URL: ... + def __str__(self) -> str: ... + def __repr__(self) -> str: ... + def __bytes__(self) -> bytes: ... + def __eq__(self, other: Any) -> bool: ... + def __le__(self, other: Any) -> bool: ... + def __lt__(self, other: Any) -> bool: ... + def __ge__(self, other: Any) -> bool: ... + def __gt__(self, other: Any) -> bool: ... + def __hash__(self) -> int: ... + def __truediv__(self, name: str) -> URL: ... + def __mod__(self, query: _Query) -> URL: ... + def is_absolute(self) -> bool: ... + def is_default_port(self) -> bool: ... + def origin(self) -> URL: ... + def relative(self) -> URL: ... + def with_scheme(self, scheme: str) -> URL: ... + def with_user(self, user: Optional[str]) -> URL: ... + def with_password(self, password: Optional[str]) -> URL: ... + def with_host(self, host: str) -> URL: ... + def with_port(self, port: Optional[int]) -> URL: ... + def with_path(self, path: str, *, encoded: bool = ...) -> URL: ... + @overload + def with_query(self, query: _Query) -> URL: ... + @overload + def with_query(self, **kwargs: _QueryVariable) -> URL: ... + @overload + def update_query(self, query: _Query) -> URL: ... + @overload + def update_query(self, **kwargs: _QueryVariable) -> URL: ... + def with_fragment(self, fragment: Optional[str]) -> URL: ... + def with_name(self, name: str) -> URL: ... + def with_suffix(self, suffix: str) -> URL: ... + def join(self, url: URL) -> URL: ... + def joinpath(self, *url: str, encoded: bool = ...) -> URL: ... + def human_repr(self) -> str: ... + # private API + @classmethod + def _normalize_path(cls, path: str) -> str: ... + +@final +class cached_property: + def __init__(self, wrapped: Any) -> None: ... + def __get__(self, inst: URL, owner: Type[URL]) -> Any: ... + def __set__(self, inst: URL, value: Any) -> None: ... + +class CacheInfo(TypedDict): + idna_encode: _CacheInfo + idna_decode: _CacheInfo + +def cache_clear() -> None: ... +def cache_info() -> CacheInfo: ... +def cache_configure( + *, idna_encode_size: Optional[int] = ..., idna_decode_size: Optional[int] = ... +) -> None: ... diff --git a/env/Lib/site-packages/yarl/__pycache__/__init__.cpython-311.pyc b/env/Lib/site-packages/yarl/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000..6fc1e79 Binary files /dev/null and b/env/Lib/site-packages/yarl/__pycache__/__init__.cpython-311.pyc differ diff --git a/env/Lib/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc b/env/Lib/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc new file mode 100644 index 0000000..3a168f8 Binary files /dev/null and b/env/Lib/site-packages/yarl/__pycache__/_quoting.cpython-311.pyc differ diff --git a/env/Lib/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc b/env/Lib/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc new file mode 100644 index 0000000..c05cc80 Binary files /dev/null and b/env/Lib/site-packages/yarl/__pycache__/_quoting_py.cpython-311.pyc differ diff --git a/env/Lib/site-packages/yarl/__pycache__/_url.cpython-311.pyc b/env/Lib/site-packages/yarl/__pycache__/_url.cpython-311.pyc new file mode 100644 index 0000000..5e3620e Binary files /dev/null and b/env/Lib/site-packages/yarl/__pycache__/_url.cpython-311.pyc differ diff --git a/env/Lib/site-packages/yarl/_quoting.py b/env/Lib/site-packages/yarl/_quoting.py new file mode 100644 index 0000000..8d1c705 --- /dev/null +++ b/env/Lib/site-packages/yarl/_quoting.py @@ -0,0 +1,18 @@ +import os +import sys + +__all__ = ("_Quoter", "_Unquoter") + + +NO_EXTENSIONS = bool(os.environ.get("YARL_NO_EXTENSIONS")) # type: bool +if sys.implementation.name != "cpython": + NO_EXTENSIONS = True + + +if not NO_EXTENSIONS: # pragma: no branch + try: + from ._quoting_c import _Quoter, _Unquoter # type: ignore[assignment] + except ImportError: # pragma: no cover + from ._quoting_py import _Quoter, _Unquoter # type: ignore[assignment] +else: + from ._quoting_py import _Quoter, _Unquoter # type: ignore[assignment] diff --git a/env/Lib/site-packages/yarl/_quoting_c.cp311-win_amd64.pyd b/env/Lib/site-packages/yarl/_quoting_c.cp311-win_amd64.pyd new file mode 100644 index 0000000..bec9b3d Binary files /dev/null and b/env/Lib/site-packages/yarl/_quoting_c.cp311-win_amd64.pyd differ diff --git a/env/Lib/site-packages/yarl/_quoting_c.pyi b/env/Lib/site-packages/yarl/_quoting_c.pyi new file mode 100644 index 0000000..1c8fc24 --- /dev/null +++ b/env/Lib/site-packages/yarl/_quoting_c.pyi @@ -0,0 +1,16 @@ +from typing import Optional + +class _Quoter: + def __init__( + self, + *, + safe: str = ..., + protected: str = ..., + qs: bool = ..., + requote: bool = ... + ) -> None: ... + def __call__(self, val: Optional[str] = ...) -> Optional[str]: ... + +class _Unquoter: + def __init__(self, *, unsafe: str = ..., qs: bool = ...) -> None: ... + def __call__(self, val: Optional[str] = ...) -> Optional[str]: ... diff --git a/env/Lib/site-packages/yarl/_quoting_c.pyx b/env/Lib/site-packages/yarl/_quoting_c.pyx new file mode 100644 index 0000000..96f69c1 --- /dev/null +++ b/env/Lib/site-packages/yarl/_quoting_c.pyx @@ -0,0 +1,371 @@ +# cython: language_level=3 + +from cpython.exc cimport PyErr_NoMemory +from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc +from cpython.unicode cimport PyUnicode_DecodeASCII, PyUnicode_DecodeUTF8Stateful +from libc.stdint cimport uint8_t, uint64_t +from libc.string cimport memcpy, memset + +from string import ascii_letters, digits + + +cdef str GEN_DELIMS = ":/?#[]@" +cdef str SUB_DELIMS_WITHOUT_QS = "!$'()*," +cdef str SUB_DELIMS = SUB_DELIMS_WITHOUT_QS + '+?=;' +cdef str RESERVED = GEN_DELIMS + SUB_DELIMS +cdef str UNRESERVED = ascii_letters + digits + '-._~' +cdef str ALLOWED = UNRESERVED + SUB_DELIMS_WITHOUT_QS +cdef str QS = '+&=;' + +DEF BUF_SIZE = 8 * 1024 # 8KiB +cdef char BUFFER[BUF_SIZE] + +cdef inline Py_UCS4 _to_hex(uint8_t v): + if v < 10: + return (v+0x30) # ord('0') == 0x30 + else: + return (v+0x41-10) # ord('A') == 0x41 + + +cdef inline int _from_hex(Py_UCS4 v): + if '0' <= v <= '9': + return (v) - 0x30 # ord('0') == 0x30 + elif 'A' <= v <= 'F': + return (v) - 0x41 + 10 # ord('A') == 0x41 + elif 'a' <= v <= 'f': + return (v) - 0x61 + 10 # ord('a') == 0x61 + else: + return -1 + + +cdef inline int _is_lower_hex(Py_UCS4 v): + return 'a' <= v <= 'f' + + +cdef inline Py_UCS4 _restore_ch(Py_UCS4 d1, Py_UCS4 d2): + cdef int digit1 = _from_hex(d1) + if digit1 < 0: + return -1 + cdef int digit2 = _from_hex(d2) + if digit2 < 0: + return -1 + return (digit1 << 4 | digit2) + + +cdef uint8_t ALLOWED_TABLE[16] +cdef uint8_t ALLOWED_NOTQS_TABLE[16] + + +cdef inline bint bit_at(uint8_t array[], uint64_t ch): + return array[ch >> 3] & (1 << (ch & 7)) + + +cdef inline void set_bit(uint8_t array[], uint64_t ch): + array[ch >> 3] |= (1 << (ch & 7)) + + +memset(ALLOWED_TABLE, 0, sizeof(ALLOWED_TABLE)) +memset(ALLOWED_NOTQS_TABLE, 0, sizeof(ALLOWED_NOTQS_TABLE)) + +for i in range(128): + if chr(i) in ALLOWED: + set_bit(ALLOWED_TABLE, i) + set_bit(ALLOWED_NOTQS_TABLE, i) + if chr(i) in QS: + set_bit(ALLOWED_NOTQS_TABLE, i) + +# ----------------- writer --------------------------- + +cdef struct Writer: + char *buf + Py_ssize_t size + Py_ssize_t pos + bint changed + + +cdef inline void _init_writer(Writer* writer): + writer.buf = &BUFFER[0] + writer.size = BUF_SIZE + writer.pos = 0 + writer.changed = 0 + + +cdef inline void _release_writer(Writer* writer): + if writer.buf != BUFFER: + PyMem_Free(writer.buf) + + +cdef inline int _write_char(Writer* writer, Py_UCS4 ch, bint changed): + cdef char * buf + cdef Py_ssize_t size + + if writer.pos == writer.size: + # reallocate + size = writer.size + BUF_SIZE + if writer.buf == BUFFER: + buf = PyMem_Malloc(size) + if buf == NULL: + PyErr_NoMemory() + return -1 + memcpy(buf, writer.buf, writer.size) + else: + buf = PyMem_Realloc(writer.buf, size) + if buf == NULL: + PyErr_NoMemory() + return -1 + writer.buf = buf + writer.size = size + writer.buf[writer.pos] = ch + writer.pos += 1 + writer.changed |= changed + return 0 + + +cdef inline int _write_pct(Writer* writer, uint8_t ch, bint changed): + if _write_char(writer, '%', changed) < 0: + return -1 + if _write_char(writer, _to_hex(ch >> 4), changed) < 0: + return -1 + return _write_char(writer, _to_hex(ch & 0x0f), changed) + + +cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): + cdef uint64_t utf = symbol + + if utf < 0x80: + return _write_pct(writer, utf, True) + elif utf < 0x800: + if _write_pct(writer, (0xc0 | (utf >> 6)), True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + elif 0xD800 <= utf <= 0xDFFF: + # surogate pair, ignored + return 0 + elif utf < 0x10000: + if _write_pct(writer, (0xe0 | (utf >> 12)), True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 6) & 0x3f)), + True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + elif utf > 0x10FFFF: + # symbol is too large + return 0 + else: + if _write_pct(writer, (0xf0 | (utf >> 18)), True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 12) & 0x3f)), + True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 6) & 0x3f)), + True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + + +# --------------------- end writer -------------------------- + + +cdef class _Quoter: + cdef bint _qs + cdef bint _requote + + cdef uint8_t _safe_table[16] + cdef uint8_t _protected_table[16] + + def __init__( + self, *, str safe='', str protected='', bint qs=False, bint requote=True, + ): + cdef Py_UCS4 ch + + self._qs = qs + self._requote = requote + + if not self._qs: + memcpy(self._safe_table, + ALLOWED_NOTQS_TABLE, + sizeof(self._safe_table)) + else: + memcpy(self._safe_table, + ALLOWED_TABLE, + sizeof(self._safe_table)) + for ch in safe: + if ord(ch) > 127: + raise ValueError("Only safe symbols with ORD < 128 are allowed") + set_bit(self._safe_table, ch) + + memset(self._protected_table, 0, sizeof(self._protected_table)) + for ch in protected: + if ord(ch) > 127: + raise ValueError("Only safe symbols with ORD < 128 are allowed") + set_bit(self._safe_table, ch) + set_bit(self._protected_table, ch) + + def __call__(self, val): + cdef Writer writer + if val is None: + return None + if type(val) is not str: + if isinstance(val, str): + # derived from str + val = str(val) + else: + raise TypeError("Argument should be str") + _init_writer(&writer) + try: + return self._do_quote(val, &writer) + finally: + _release_writer(&writer) + + cdef str _do_quote(self, str val, Writer *writer): + cdef Py_UCS4 ch + cdef int changed + cdef int idx = 0 + cdef int length = len(val) + + while idx < length: + ch = val[idx] + idx += 1 + if ch == '%' and self._requote and idx <= length - 2: + ch = _restore_ch(val[idx], val[idx + 1]) + if ch != -1: + idx += 2 + if ch < 128: + if bit_at(self._protected_table, ch): + if _write_pct(writer, ch, True) < 0: + raise + continue + + if bit_at(self._safe_table, ch): + if _write_char(writer, ch, True) < 0: + raise + continue + + changed = (_is_lower_hex(val[idx - 2]) or + _is_lower_hex(val[idx - 1])) + if _write_pct(writer, ch, changed) < 0: + raise + continue + else: + ch = '%' + + if self._write(writer, ch) < 0: + raise + + if not writer.changed: + return val + else: + return PyUnicode_DecodeASCII(writer.buf, writer.pos, "strict") + + cdef inline int _write(self, Writer *writer, Py_UCS4 ch): + if self._qs: + if ch == ' ': + return _write_char(writer, '+', True) + + if ch < 128 and bit_at(self._safe_table, ch): + return _write_char(writer, ch, False) + + return _write_utf8(writer, ch) + + +cdef class _Unquoter: + cdef str _unsafe + cdef bint _qs + cdef _Quoter _quoter + cdef _Quoter _qs_quoter + + def __init__(self, *, unsafe='', qs=False): + self._unsafe = unsafe + self._qs = qs + self._quoter = _Quoter() + self._qs_quoter = _Quoter(qs=True) + + def __call__(self, val): + if val is None: + return None + if type(val) is not str: + if isinstance(val, str): + # derived from str + val = str(val) + else: + raise TypeError("Argument should be str") + return self._do_unquote(val) + + cdef str _do_unquote(self, str val): + if len(val) == 0: + return val + cdef list ret = [] + cdef char buffer[4] + cdef Py_ssize_t buflen = 0 + cdef Py_ssize_t consumed + cdef str unquoted + cdef Py_UCS4 ch = 0 + cdef Py_ssize_t idx = 0 + cdef Py_ssize_t length = len(val) + cdef Py_ssize_t start_pct + + while idx < length: + ch = val[idx] + idx += 1 + if ch == '%' and idx <= length - 2: + ch = _restore_ch(val[idx], val[idx + 1]) + if ch != -1: + idx += 2 + assert buflen < 4 + buffer[buflen] = ch + buflen += 1 + try: + unquoted = PyUnicode_DecodeUTF8Stateful(buffer, buflen, + NULL, &consumed) + except UnicodeDecodeError: + start_pct = idx - buflen * 3 + buffer[0] = ch + buflen = 1 + ret.append(val[start_pct : idx - 3]) + try: + unquoted = PyUnicode_DecodeUTF8Stateful(buffer, buflen, + NULL, &consumed) + except UnicodeDecodeError: + buflen = 0 + ret.append(val[idx - 3 : idx]) + continue + if not unquoted: + assert consumed == 0 + continue + assert consumed == buflen + buflen = 0 + if self._qs and unquoted in '+=&;': + ret.append(self._qs_quoter(unquoted)) + elif unquoted in self._unsafe: + ret.append(self._quoter(unquoted)) + else: + ret.append(unquoted) + continue + else: + ch = '%' + + if buflen: + start_pct = idx - 1 - buflen * 3 + ret.append(val[start_pct : idx - 1]) + buflen = 0 + + if ch == '+': + if not self._qs or ch in self._unsafe: + ret.append('+') + else: + ret.append(' ') + continue + + if ch in self._unsafe: + ret.append('%') + h = hex(ord(ch)).upper()[2:] + for ch in h: + ret.append(ch) + continue + + ret.append(ch) + + if buflen: + ret.append(val[length - buflen * 3 : length]) + + return ''.join(ret) diff --git a/env/Lib/site-packages/yarl/_quoting_py.py b/env/Lib/site-packages/yarl/_quoting_py.py new file mode 100644 index 0000000..585a1da --- /dev/null +++ b/env/Lib/site-packages/yarl/_quoting_py.py @@ -0,0 +1,197 @@ +import codecs +import re +from string import ascii_letters, ascii_lowercase, digits +from typing import Optional, cast + +BASCII_LOWERCASE = ascii_lowercase.encode("ascii") +BPCT_ALLOWED = {f"%{i:02X}".encode("ascii") for i in range(256)} +GEN_DELIMS = ":/?#[]@" +SUB_DELIMS_WITHOUT_QS = "!$'()*," +SUB_DELIMS = SUB_DELIMS_WITHOUT_QS + "+&=;" +RESERVED = GEN_DELIMS + SUB_DELIMS +UNRESERVED = ascii_letters + digits + "-._~" +ALLOWED = UNRESERVED + SUB_DELIMS_WITHOUT_QS + + +_IS_HEX = re.compile(b"[A-Z0-9][A-Z0-9]") +_IS_HEX_STR = re.compile("[A-Fa-f0-9][A-Fa-f0-9]") + +utf8_decoder = codecs.getincrementaldecoder("utf-8") + + +class _Quoter: + def __init__( + self, + *, + safe: str = "", + protected: str = "", + qs: bool = False, + requote: bool = True, + ) -> None: + self._safe = safe + self._protected = protected + self._qs = qs + self._requote = requote + + def __call__(self, val: Optional[str]) -> Optional[str]: + if val is None: + return None + if not isinstance(val, str): + raise TypeError("Argument should be str") + if not val: + return "" + bval = cast(str, val).encode("utf8", errors="ignore") + ret = bytearray() + pct = bytearray() + safe = self._safe + safe += ALLOWED + if not self._qs: + safe += "+&=;" + safe += self._protected + bsafe = safe.encode("ascii") + idx = 0 + while idx < len(bval): + ch = bval[idx] + idx += 1 + + if pct: + if ch in BASCII_LOWERCASE: + ch = ch - 32 # convert to uppercase + pct.append(ch) + if len(pct) == 3: # pragma: no branch # peephole optimizer + buf = pct[1:] + if not _IS_HEX.match(buf): + ret.extend(b"%25") + pct.clear() + idx -= 2 + continue + try: + unquoted = chr(int(pct[1:].decode("ascii"), base=16)) + except ValueError: + ret.extend(b"%25") + pct.clear() + idx -= 2 + continue + + if unquoted in self._protected: + ret.extend(pct) + elif unquoted in safe: + ret.append(ord(unquoted)) + else: + ret.extend(pct) + pct.clear() + + # special case, if we have only one char after "%" + elif len(pct) == 2 and idx == len(bval): + ret.extend(b"%25") + pct.clear() + idx -= 1 + + continue + + elif ch == ord("%") and self._requote: + pct.clear() + pct.append(ch) + + # special case if "%" is last char + if idx == len(bval): + ret.extend(b"%25") + + continue + + if self._qs: + if ch == ord(" "): + ret.append(ord("+")) + continue + if ch in bsafe: + ret.append(ch) + continue + + ret.extend((f"%{ch:02X}").encode("ascii")) + + ret2 = ret.decode("ascii") + if ret2 == val: + return val + return ret2 + + +class _Unquoter: + def __init__(self, *, unsafe: str = "", qs: bool = False) -> None: + self._unsafe = unsafe + self._qs = qs + self._quoter = _Quoter() + self._qs_quoter = _Quoter(qs=True) + + def __call__(self, val: Optional[str]) -> Optional[str]: + if val is None: + return None + if not isinstance(val, str): + raise TypeError("Argument should be str") + if not val: + return "" + decoder = cast(codecs.BufferedIncrementalDecoder, utf8_decoder()) + ret = [] + idx = 0 + while idx < len(val): + ch = val[idx] + idx += 1 + if ch == "%" and idx <= len(val) - 2: + pct = val[idx : idx + 2] + if _IS_HEX_STR.fullmatch(pct): + b = bytes([int(pct, base=16)]) + idx += 2 + try: + unquoted = decoder.decode(b) + except UnicodeDecodeError: + start_pct = idx - 3 - len(decoder.buffer) * 3 + ret.append(val[start_pct : idx - 3]) + decoder.reset() + try: + unquoted = decoder.decode(b) + except UnicodeDecodeError: + ret.append(val[idx - 3 : idx]) + continue + if not unquoted: + continue + if self._qs and unquoted in "+=&;": + to_add = self._qs_quoter(unquoted) + if to_add is None: # pragma: no cover + raise RuntimeError("Cannot quote None") + ret.append(to_add) + elif unquoted in self._unsafe: + to_add = self._quoter(unquoted) + if to_add is None: # pragma: no cover + raise RuntimeError("Cannot quote None") + ret.append(to_add) + else: + ret.append(unquoted) + continue + + if decoder.buffer: + start_pct = idx - 1 - len(decoder.buffer) * 3 + ret.append(val[start_pct : idx - 1]) + decoder.reset() + + if ch == "+": + if not self._qs or ch in self._unsafe: + ret.append("+") + else: + ret.append(" ") + continue + + if ch in self._unsafe: + ret.append("%") + h = hex(ord(ch)).upper()[2:] + for ch in h: + ret.append(ch) + continue + + ret.append(ch) + + if decoder.buffer: + ret.append(val[-len(decoder.buffer) * 3 :]) + + ret2 = "".join(ret) + if ret2 == val: + return val + return ret2 diff --git a/env/Lib/site-packages/yarl/_url.py b/env/Lib/site-packages/yarl/_url.py new file mode 100644 index 0000000..9cca27e --- /dev/null +++ b/env/Lib/site-packages/yarl/_url.py @@ -0,0 +1,1200 @@ +import functools +import math +import warnings +from collections.abc import Mapping, Sequence +from contextlib import suppress +from ipaddress import ip_address +from urllib.parse import SplitResult, parse_qsl, quote, urljoin, urlsplit, urlunsplit + +import idna +from multidict import MultiDict, MultiDictProxy + +from ._quoting import _Quoter, _Unquoter + +DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443} + +sentinel = object() + + +def rewrite_module(obj: object) -> object: + obj.__module__ = "yarl" + return obj + + +class cached_property: + """Use as a class method decorator. It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + + """ + + def __init__(self, wrapped): + self.wrapped = wrapped + try: + self.__doc__ = wrapped.__doc__ + except AttributeError: # pragma: no cover + self.__doc__ = "" + self.name = wrapped.__name__ + + def __get__(self, inst, owner, _sentinel=sentinel): + if inst is None: + return self + val = inst._cache.get(self.name, _sentinel) + if val is not _sentinel: + return val + val = self.wrapped(inst) + inst._cache[self.name] = val + return val + + def __set__(self, inst, value): + raise AttributeError("cached property is read-only") + + +def _normalize_path_segments(segments): + """Drop '.' and '..' from a sequence of str segments""" + + resolved_path = [] + + for seg in segments: + if seg == "..": + # ignore any .. segments that would otherwise cause an + # IndexError when popped from resolved_path if + # resolving for rfc3986 + with suppress(IndexError): + resolved_path.pop() + elif seg != ".": + resolved_path.append(seg) + + if segments and segments[-1] in (".", ".."): + # do some post-processing here. + # if the last segment was a relative dir, + # then we need to append the trailing '/' + resolved_path.append("") + + return resolved_path + + +@rewrite_module +class URL: + # Don't derive from str + # follow pathlib.Path design + # probably URL will not suffer from pathlib problems: + # it's intended for libraries like aiohttp, + # not to be passed into standard library functions like os.open etc. + + # URL grammar (RFC 3986) + # pct-encoded = "%" HEXDIG HEXDIG + # reserved = gen-delims / sub-delims + # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" + # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + # / "*" / "+" / "," / ";" / "=" + # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + # URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] + # hier-part = "//" authority path-abempty + # / path-absolute + # / path-rootless + # / path-empty + # scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + # authority = [ userinfo "@" ] host [ ":" port ] + # userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) + # host = IP-literal / IPv4address / reg-name + # IP-literal = "[" ( IPv6address / IPvFuture ) "]" + # IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) + # IPv6address = 6( h16 ":" ) ls32 + # / "::" 5( h16 ":" ) ls32 + # / [ h16 ] "::" 4( h16 ":" ) ls32 + # / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + # / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + # / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + # / [ *4( h16 ":" ) h16 ] "::" ls32 + # / [ *5( h16 ":" ) h16 ] "::" h16 + # / [ *6( h16 ":" ) h16 ] "::" + # ls32 = ( h16 ":" h16 ) / IPv4address + # ; least-significant 32 bits of address + # h16 = 1*4HEXDIG + # ; 16 bits of address represented in hexadecimal + # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + # dec-octet = DIGIT ; 0-9 + # / %x31-39 DIGIT ; 10-99 + # / "1" 2DIGIT ; 100-199 + # / "2" %x30-34 DIGIT ; 200-249 + # / "25" %x30-35 ; 250-255 + # reg-name = *( unreserved / pct-encoded / sub-delims ) + # port = *DIGIT + # path = path-abempty ; begins with "/" or is empty + # / path-absolute ; begins with "/" but not "//" + # / path-noscheme ; begins with a non-colon segment + # / path-rootless ; begins with a segment + # / path-empty ; zero characters + # path-abempty = *( "/" segment ) + # path-absolute = "/" [ segment-nz *( "/" segment ) ] + # path-noscheme = segment-nz-nc *( "/" segment ) + # path-rootless = segment-nz *( "/" segment ) + # path-empty = 0 + # segment = *pchar + # segment-nz = 1*pchar + # segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" ) + # ; non-zero-length segment without any colon ":" + # pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + # query = *( pchar / "/" / "?" ) + # fragment = *( pchar / "/" / "?" ) + # URI-reference = URI / relative-ref + # relative-ref = relative-part [ "?" query ] [ "#" fragment ] + # relative-part = "//" authority path-abempty + # / path-absolute + # / path-noscheme + # / path-empty + # absolute-URI = scheme ":" hier-part [ "?" query ] + __slots__ = ("_cache", "_val") + + _QUOTER = _Quoter(requote=False) + _REQUOTER = _Quoter() + _PATH_QUOTER = _Quoter(safe="@:", protected="/+", requote=False) + _PATH_REQUOTER = _Quoter(safe="@:", protected="/+") + _QUERY_QUOTER = _Quoter(safe="?/:@", protected="=+&;", qs=True, requote=False) + _QUERY_REQUOTER = _Quoter(safe="?/:@", protected="=+&;", qs=True) + _QUERY_PART_QUOTER = _Quoter(safe="?/:@", qs=True, requote=False) + _FRAGMENT_QUOTER = _Quoter(safe="?/:@", requote=False) + _FRAGMENT_REQUOTER = _Quoter(safe="?/:@") + + _UNQUOTER = _Unquoter() + _PATH_UNQUOTER = _Unquoter(unsafe="+") + _QS_UNQUOTER = _Unquoter(qs=True) + + def __new__(cls, val="", *, encoded=False, strict=None): + if strict is not None: # pragma: no cover + warnings.warn("strict parameter is ignored") + if type(val) is cls: + return val + if type(val) is str: + val = urlsplit(val) + elif type(val) is SplitResult: + if not encoded: + raise ValueError("Cannot apply decoding to SplitResult") + elif isinstance(val, str): + val = urlsplit(str(val)) + else: + raise TypeError("Constructor parameter should be str") + + if not encoded: + if not val[1]: # netloc + netloc = "" + host = "" + else: + host = val.hostname + if host is None: + raise ValueError("Invalid URL: host is required for absolute urls") + + try: + port = val.port + except ValueError as e: + raise ValueError( + "Invalid URL: port can't be converted to integer" + ) from e + + netloc = cls._make_netloc( + val.username, val.password, host, port, encode=True, requote=True + ) + path = cls._PATH_REQUOTER(val[2]) + if netloc: + path = cls._normalize_path(path) + + cls._validate_authority_uri_abs_path(host=host, path=path) + query = cls._QUERY_REQUOTER(val[3]) + fragment = cls._FRAGMENT_REQUOTER(val[4]) + val = SplitResult(val[0], netloc, path, query, fragment) + + self = object.__new__(cls) + self._val = val + self._cache = {} + return self + + @classmethod + def build( + cls, + *, + scheme="", + authority="", + user=None, + password=None, + host="", + port=None, + path="", + query=None, + query_string="", + fragment="", + encoded=False, + ): + """Creates and returns a new URL""" + + if authority and (user or password or host or port): + raise ValueError( + 'Can\'t mix "authority" with "user", "password", "host" or "port".' + ) + if not isinstance(port, (int, type(None))): + raise TypeError("The port is required to be int.") + if port and not host: + raise ValueError('Can\'t build URL with "port" but without "host".') + if query and query_string: + raise ValueError('Only one of "query" or "query_string" should be passed') + if ( + scheme is None + or authority is None + or host is None + or path is None + or query_string is None + or fragment is None + ): + raise TypeError( + 'NoneType is illegal for "scheme", "authority", "host", "path", ' + '"query_string", and "fragment" args, use empty string instead.' + ) + + if authority: + if encoded: + netloc = authority + else: + tmp = SplitResult("", authority, "", "", "") + netloc = cls._make_netloc( + tmp.username, tmp.password, tmp.hostname, tmp.port, encode=True + ) + elif not user and not password and not host and not port: + netloc = "" + else: + netloc = cls._make_netloc( + user, password, host, port, encode=not encoded, encode_host=not encoded + ) + if not encoded: + path = cls._PATH_QUOTER(path) + if netloc: + path = cls._normalize_path(path) + + cls._validate_authority_uri_abs_path(host=host, path=path) + query_string = cls._QUERY_QUOTER(query_string) + fragment = cls._FRAGMENT_QUOTER(fragment) + + url = cls( + SplitResult(scheme, netloc, path, query_string, fragment), encoded=True + ) + + if query: + return url.with_query(query) + else: + return url + + def __init_subclass__(cls): + raise TypeError(f"Inheriting a class {cls!r} from URL is forbidden") + + def __str__(self): + val = self._val + if not val.path and self.is_absolute() and (val.query or val.fragment): + val = val._replace(path="/") + return urlunsplit(val) + + def __repr__(self): + return f"{self.__class__.__name__}('{str(self)}')" + + def __bytes__(self): + return str(self).encode("ascii") + + def __eq__(self, other): + if not type(other) is URL: + return NotImplemented + + val1 = self._val + if not val1.path and self.is_absolute(): + val1 = val1._replace(path="/") + + val2 = other._val + if not val2.path and other.is_absolute(): + val2 = val2._replace(path="/") + + return val1 == val2 + + def __hash__(self): + ret = self._cache.get("hash") + if ret is None: + val = self._val + if not val.path and self.is_absolute(): + val = val._replace(path="/") + ret = self._cache["hash"] = hash(val) + return ret + + def __le__(self, other): + if not type(other) is URL: + return NotImplemented + return self._val <= other._val + + def __lt__(self, other): + if not type(other) is URL: + return NotImplemented + return self._val < other._val + + def __ge__(self, other): + if not type(other) is URL: + return NotImplemented + return self._val >= other._val + + def __gt__(self, other): + if not type(other) is URL: + return NotImplemented + return self._val > other._val + + def __truediv__(self, name): + if not isinstance(name, str): + return NotImplemented + return self._make_child((str(name),)) + + def __mod__(self, query): + return self.update_query(query) + + def __bool__(self) -> bool: + return bool( + self._val.netloc or self._val.path or self._val.query or self._val.fragment + ) + + def __getstate__(self): + return (self._val,) + + def __setstate__(self, state): + if state[0] is None and isinstance(state[1], dict): + # default style pickle + self._val = state[1]["_val"] + else: + self._val, *unused = state + self._cache = {} + + def is_absolute(self): + """A check for absolute URLs. + + Return True for absolute ones (having scheme or starting + with //), False otherwise. + + """ + return self.raw_host is not None + + def is_default_port(self): + """A check for default port. + + Return True if port is default for specified scheme, + e.g. 'http://python.org' or 'http://python.org:80', False + otherwise. + + """ + if self.port is None: + return False + default = DEFAULT_PORTS.get(self.scheme) + if default is None: + return False + return self.port == default + + def origin(self): + """Return an URL with scheme, host and port parts only. + + user, password, path, query and fragment are removed. + + """ + # TODO: add a keyword-only option for keeping user/pass maybe? + if not self.is_absolute(): + raise ValueError("URL should be absolute") + if not self._val.scheme: + raise ValueError("URL should have scheme") + v = self._val + netloc = self._make_netloc(None, None, v.hostname, v.port) + val = v._replace(netloc=netloc, path="", query="", fragment="") + return URL(val, encoded=True) + + def relative(self): + """Return a relative part of the URL. + + scheme, user, password, host and port are removed. + + """ + if not self.is_absolute(): + raise ValueError("URL should be absolute") + val = self._val._replace(scheme="", netloc="") + return URL(val, encoded=True) + + @property + def scheme(self): + """Scheme for absolute URLs. + + Empty string for relative URLs or URLs starting with // + + """ + return self._val.scheme + + @property + def raw_authority(self): + """Encoded authority part of URL. + + Empty string for relative URLs. + + """ + return self._val.netloc + + @cached_property + def authority(self): + """Decoded authority part of URL. + + Empty string for relative URLs. + + """ + return self._make_netloc( + self.user, self.password, self.host, self.port, encode_host=False + ) + + @property + def raw_user(self): + """Encoded user part of URL. + + None if user is missing. + + """ + # not .username + ret = self._val.username + if not ret: + return None + return ret + + @cached_property + def user(self): + """Decoded user part of URL. + + None if user is missing. + + """ + return self._UNQUOTER(self.raw_user) + + @property + def raw_password(self): + """Encoded password part of URL. + + None if password is missing. + + """ + return self._val.password + + @cached_property + def password(self): + """Decoded password part of URL. + + None if password is missing. + + """ + return self._UNQUOTER(self.raw_password) + + @property + def raw_host(self): + """Encoded host part of URL. + + None for relative URLs. + + """ + # Use host instead of hostname for sake of shortness + # May add .hostname prop later + return self._val.hostname + + @cached_property + def host(self): + """Decoded host part of URL. + + None for relative URLs. + + """ + raw = self.raw_host + if raw is None: + return None + if "%" in raw: + # Hack for scoped IPv6 addresses like + # fe80::2%Перевірка + # presence of '%' sign means only IPv6 address, so idna is useless. + return raw + return _idna_decode(raw) + + @property + def port(self): + """Port part of URL, with scheme-based fallback. + + None for relative URLs or URLs without explicit port and + scheme without default port substitution. + + """ + return self._val.port or DEFAULT_PORTS.get(self._val.scheme) + + @property + def explicit_port(self): + """Port part of URL, without scheme-based fallback. + + None for relative URLs or URLs without explicit port. + + """ + return self._val.port + + @property + def raw_path(self): + """Encoded path of URL. + + / for absolute URLs without path part. + + """ + ret = self._val.path + if not ret and self.is_absolute(): + ret = "/" + return ret + + @cached_property + def path(self): + """Decoded path of URL. + + / for absolute URLs without path part. + + """ + return self._PATH_UNQUOTER(self.raw_path) + + @cached_property + def query(self): + """A MultiDictProxy representing parsed query parameters in decoded + representation. + + Empty value if URL has no query part. + + """ + ret = MultiDict(parse_qsl(self.raw_query_string, keep_blank_values=True)) + return MultiDictProxy(ret) + + @property + def raw_query_string(self): + """Encoded query part of URL. + + Empty string if query is missing. + + """ + return self._val.query + + @cached_property + def query_string(self): + """Decoded query part of URL. + + Empty string if query is missing. + + """ + return self._QS_UNQUOTER(self.raw_query_string) + + @cached_property + def path_qs(self): + """Decoded path of URL with query.""" + if not self.query_string: + return self.path + return f"{self.path}?{self.query_string}" + + @cached_property + def raw_path_qs(self): + """Encoded path of URL with query.""" + if not self.raw_query_string: + return self.raw_path + return f"{self.raw_path}?{self.raw_query_string}" + + @property + def raw_fragment(self): + """Encoded fragment part of URL. + + Empty string if fragment is missing. + + """ + return self._val.fragment + + @cached_property + def fragment(self): + """Decoded fragment part of URL. + + Empty string if fragment is missing. + + """ + return self._UNQUOTER(self.raw_fragment) + + @cached_property + def raw_parts(self): + """A tuple containing encoded *path* parts. + + ('/',) for absolute URLs if *path* is missing. + + """ + path = self._val.path + if self.is_absolute(): + if not path: + parts = ["/"] + else: + parts = ["/"] + path[1:].split("/") + else: + if path.startswith("/"): + parts = ["/"] + path[1:].split("/") + else: + parts = path.split("/") + return tuple(parts) + + @cached_property + def parts(self): + """A tuple containing decoded *path* parts. + + ('/',) for absolute URLs if *path* is missing. + + """ + return tuple(self._UNQUOTER(part) for part in self.raw_parts) + + @cached_property + def parent(self): + """A new URL with last part of path removed and cleaned up query and + fragment. + + """ + path = self.raw_path + if not path or path == "/": + if self.raw_fragment or self.raw_query_string: + return URL(self._val._replace(query="", fragment=""), encoded=True) + return self + parts = path.split("/") + val = self._val._replace(path="/".join(parts[:-1]), query="", fragment="") + return URL(val, encoded=True) + + @cached_property + def raw_name(self): + """The last part of raw_parts.""" + parts = self.raw_parts + if self.is_absolute(): + parts = parts[1:] + if not parts: + return "" + else: + return parts[-1] + else: + return parts[-1] + + @cached_property + def name(self): + """The last part of parts.""" + return self._UNQUOTER(self.raw_name) + + @cached_property + def raw_suffix(self): + name = self.raw_name + i = name.rfind(".") + if 0 < i < len(name) - 1: + return name[i:] + else: + return "" + + @cached_property + def suffix(self): + return self._UNQUOTER(self.raw_suffix) + + @cached_property + def raw_suffixes(self): + name = self.raw_name + if name.endswith("."): + return () + name = name.lstrip(".") + return tuple("." + suffix for suffix in name.split(".")[1:]) + + @cached_property + def suffixes(self): + return tuple(self._UNQUOTER(suffix) for suffix in self.raw_suffixes) + + @staticmethod + def _validate_authority_uri_abs_path(host, path): + """Ensure that path in URL with authority starts with a leading slash. + + Raise ValueError if not. + """ + if len(host) > 0 and len(path) > 0 and not path.startswith("/"): + raise ValueError( + "Path in a URL with authority should start with a slash ('/') if set" + ) + + def _make_child(self, segments, encoded=False): + """add segments to self._val.path, accounting for absolute vs relative paths""" + # keep the trailing slash if the last segment ends with / + parsed = [""] if segments and segments[-1][-1:] == "/" else [] + for seg in reversed(segments): + if not seg: + continue + if seg[0] == "/": + raise ValueError( + f"Appending path {seg!r} starting from slash is forbidden" + ) + seg = seg if encoded else self._PATH_QUOTER(seg) + if "/" in seg: + parsed += ( + sub for sub in reversed(seg.split("/")) if sub and sub != "." + ) + elif seg != ".": + parsed.append(seg) + parsed.reverse() + old_path = self._val.path + if old_path: + parsed = [*old_path.rstrip("/").split("/"), *parsed] + if self.is_absolute(): + parsed = _normalize_path_segments(parsed) + if parsed and parsed[0] != "": + # inject a leading slash when adding a path to an absolute URL + # where there was none before + parsed = ["", *parsed] + new_path = "/".join(parsed) + return URL( + self._val._replace(path=new_path, query="", fragment=""), encoded=True + ) + + @classmethod + def _normalize_path(cls, path): + # Drop '.' and '..' from str path + + prefix = "" + if path.startswith("/"): + # preserve the "/" root element of absolute paths, copying it to the + # normalised output as per sections 5.2.4 and 6.2.2.3 of rfc3986. + prefix = "/" + path = path[1:] + + segments = path.split("/") + return prefix + "/".join(_normalize_path_segments(segments)) + + @classmethod + def _encode_host(cls, host, human=False): + try: + ip, sep, zone = host.partition("%") + ip = ip_address(ip) + except ValueError: + host = host.lower() + # IDNA encoding is slow, + # skip it for ASCII-only strings + # Don't move the check into _idna_encode() helper + # to reduce the cache size + if human or host.isascii(): + return host + host = _idna_encode(host) + else: + host = ip.compressed + if sep: + host += "%" + zone + if ip.version == 6: + host = "[" + host + "]" + return host + + @classmethod + def _make_netloc( + cls, user, password, host, port, encode=False, encode_host=True, requote=False + ): + quoter = cls._REQUOTER if requote else cls._QUOTER + if encode_host: + ret = cls._encode_host(host) + else: + ret = host + if port is not None: + ret = ret + ":" + str(port) + if password is not None: + if not user: + user = "" + else: + if encode: + user = quoter(user) + if encode: + password = quoter(password) + user = user + ":" + password + elif user and encode: + user = quoter(user) + if user: + ret = user + "@" + ret + return ret + + def with_scheme(self, scheme): + """Return a new URL with scheme replaced.""" + # N.B. doesn't cleanup query/fragment + if not isinstance(scheme, str): + raise TypeError("Invalid scheme type") + if not self.is_absolute(): + raise ValueError("scheme replacement is not allowed for relative URLs") + return URL(self._val._replace(scheme=scheme.lower()), encoded=True) + + def with_user(self, user): + """Return a new URL with user replaced. + + Autoencode user if needed. + + Clear user/password if user is None. + + """ + # N.B. doesn't cleanup query/fragment + val = self._val + if user is None: + password = None + elif isinstance(user, str): + user = self._QUOTER(user) + password = val.password + else: + raise TypeError("Invalid user type") + if not self.is_absolute(): + raise ValueError("user replacement is not allowed for relative URLs") + return URL( + self._val._replace( + netloc=self._make_netloc(user, password, val.hostname, val.port) + ), + encoded=True, + ) + + def with_password(self, password): + """Return a new URL with password replaced. + + Autoencode password if needed. + + Clear password if argument is None. + + """ + # N.B. doesn't cleanup query/fragment + if password is None: + pass + elif isinstance(password, str): + password = self._QUOTER(password) + else: + raise TypeError("Invalid password type") + if not self.is_absolute(): + raise ValueError("password replacement is not allowed for relative URLs") + val = self._val + return URL( + self._val._replace( + netloc=self._make_netloc(val.username, password, val.hostname, val.port) + ), + encoded=True, + ) + + def with_host(self, host): + """Return a new URL with host replaced. + + Autoencode host if needed. + + Changing host for relative URLs is not allowed, use .join() + instead. + + """ + # N.B. doesn't cleanup query/fragment + if not isinstance(host, str): + raise TypeError("Invalid host type") + if not self.is_absolute(): + raise ValueError("host replacement is not allowed for relative URLs") + if not host: + raise ValueError("host removing is not allowed") + val = self._val + return URL( + self._val._replace( + netloc=self._make_netloc(val.username, val.password, host, val.port) + ), + encoded=True, + ) + + def with_port(self, port): + """Return a new URL with port replaced. + + Clear port to default if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + if port is not None: + if isinstance(port, bool) or not isinstance(port, int): + raise TypeError(f"port should be int or None, got {type(port)}") + if port < 0 or port > 65535: + raise ValueError(f"port must be between 0 and 65535, got {port}") + if not self.is_absolute(): + raise ValueError("port replacement is not allowed for relative URLs") + val = self._val + return URL( + self._val._replace( + netloc=self._make_netloc(val.username, val.password, val.hostname, port) + ), + encoded=True, + ) + + def with_path(self, path, *, encoded=False): + """Return a new URL with path replaced.""" + if not encoded: + path = self._PATH_QUOTER(path) + if self.is_absolute(): + path = self._normalize_path(path) + if len(path) > 0 and path[0] != "/": + path = "/" + path + return URL(self._val._replace(path=path, query="", fragment=""), encoded=True) + + @classmethod + def _query_seq_pairs(cls, quoter, pairs): + for key, val in pairs: + if isinstance(val, (list, tuple)): + for v in val: + yield quoter(key) + "=" + quoter(cls._query_var(v)) + else: + yield quoter(key) + "=" + quoter(cls._query_var(val)) + + @staticmethod + def _query_var(v): + cls = type(v) + if issubclass(cls, str): + return v + if issubclass(cls, float): + if math.isinf(v): + raise ValueError("float('inf') is not supported") + if math.isnan(v): + raise ValueError("float('nan') is not supported") + return str(float(v)) + if issubclass(cls, int) and cls is not bool: + return str(int(v)) + raise TypeError( + "Invalid variable type: value " + "should be str, int or float, got {!r} " + "of type {}".format(v, cls) + ) + + def _get_str_query(self, *args, **kwargs): + if kwargs: + if len(args) > 0: + raise ValueError( + "Either kwargs or single query parameter must be present" + ) + query = kwargs + elif len(args) == 1: + query = args[0] + else: + raise ValueError("Either kwargs or single query parameter must be present") + + if query is None: + query = None + elif isinstance(query, Mapping): + quoter = self._QUERY_PART_QUOTER + query = "&".join(self._query_seq_pairs(quoter, query.items())) + elif isinstance(query, str): + query = self._QUERY_QUOTER(query) + elif isinstance(query, (bytes, bytearray, memoryview)): + raise TypeError( + "Invalid query type: bytes, bytearray and memoryview are forbidden" + ) + elif isinstance(query, Sequence): + quoter = self._QUERY_PART_QUOTER + # We don't expect sequence values if we're given a list of pairs + # already; only mappings like builtin `dict` which can't have the + # same key pointing to multiple values are allowed to use + # `_query_seq_pairs`. + query = "&".join( + quoter(k) + "=" + quoter(self._query_var(v)) for k, v in query + ) + else: + raise TypeError( + "Invalid query type: only str, mapping or " + "sequence of (key, value) pairs is allowed" + ) + + return query + + def with_query(self, *args, **kwargs): + """Return a new URL with query part replaced. + + Accepts any Mapping (e.g. dict, multidict.MultiDict instances) + or str, autoencode the argument if needed. + + A sequence of (key, value) pairs is supported as well. + + It also can take an arbitrary number of keyword arguments. + + Clear query if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + + new_query = self._get_str_query(*args, **kwargs) or "" + return URL( + self._val._replace(path=self._val.path, query=new_query), encoded=True + ) + + def update_query(self, *args, **kwargs): + """Return a new URL with query part updated.""" + s = self._get_str_query(*args, **kwargs) + query = None + if s is not None: + new_query = MultiDict(parse_qsl(s, keep_blank_values=True)) + query = MultiDict(self.query) + query.update(new_query) + + return URL( + self._val._replace(query=self._get_str_query(query) or ""), encoded=True + ) + + def with_fragment(self, fragment): + """Return a new URL with fragment replaced. + + Autoencode fragment if needed. + + Clear fragment to default if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + if fragment is None: + raw_fragment = "" + elif not isinstance(fragment, str): + raise TypeError("Invalid fragment type") + else: + raw_fragment = self._FRAGMENT_QUOTER(fragment) + if self.raw_fragment == raw_fragment: + return self + return URL(self._val._replace(fragment=raw_fragment), encoded=True) + + def with_name(self, name): + """Return a new URL with name (last part of path) replaced. + + Query and fragment parts are cleaned up. + + Name is encoded if needed. + + """ + # N.B. DOES cleanup query/fragment + if not isinstance(name, str): + raise TypeError("Invalid name type") + if "/" in name: + raise ValueError("Slash in name is not allowed") + name = self._PATH_QUOTER(name) + if name in (".", ".."): + raise ValueError(". and .. values are forbidden") + parts = list(self.raw_parts) + if self.is_absolute(): + if len(parts) == 1: + parts.append(name) + else: + parts[-1] = name + parts[0] = "" # replace leading '/' + else: + parts[-1] = name + if parts[0] == "/": + parts[0] = "" # replace leading '/' + return URL( + self._val._replace(path="/".join(parts), query="", fragment=""), + encoded=True, + ) + + def with_suffix(self, suffix): + """Return a new URL with suffix (file extension of name) replaced. + + Query and fragment parts are cleaned up. + + suffix is encoded if needed. + """ + if not isinstance(suffix, str): + raise TypeError("Invalid suffix type") + if suffix and not suffix.startswith(".") or suffix == ".": + raise ValueError(f"Invalid suffix {suffix!r}") + name = self.raw_name + if not name: + raise ValueError(f"{self!r} has an empty name") + old_suffix = self.raw_suffix + if not old_suffix: + name = name + suffix + else: + name = name[: -len(old_suffix)] + suffix + return self.with_name(name) + + def join(self, url): + """Join URLs + + Construct a full (“absolute”) URL by combining a “base URL” + (self) with another URL (url). + + Informally, this uses components of the base URL, in + particular the addressing scheme, the network location and + (part of) the path, to provide missing components in the + relative URL. + + """ + # See docs for urllib.parse.urljoin + if not isinstance(url, URL): + raise TypeError("url should be URL") + return URL(urljoin(str(self), str(url)), encoded=True) + + def joinpath(self, *other, encoded=False): + """Return a new URL with the elements in other appended to the path.""" + return self._make_child(other, encoded=encoded) + + def human_repr(self): + """Return decoded human readable string for URL representation.""" + user = _human_quote(self.user, "#/:?@[]") + password = _human_quote(self.password, "#/:?@[]") + host = self.host + if host: + host = self._encode_host(self.host, human=True) + path = _human_quote(self.path, "#?") + query_string = "&".join( + "{}={}".format(_human_quote(k, "#&+;="), _human_quote(v, "#&+;=")) + for k, v in self.query.items() + ) + fragment = _human_quote(self.fragment, "") + return urlunsplit( + SplitResult( + self.scheme, + self._make_netloc( + user, + password, + host, + self._val.port, + encode_host=False, + ), + path, + query_string, + fragment, + ) + ) + + +def _human_quote(s, unsafe): + if not s: + return s + for c in "%" + unsafe: + if c in s: + s = s.replace(c, f"%{ord(c):02X}") + if s.isprintable(): + return s + return "".join(c if c.isprintable() else quote(c) for c in s) + + +_MAXCACHE = 256 + + +@functools.lru_cache(_MAXCACHE) +def _idna_decode(raw): + try: + return idna.decode(raw.encode("ascii")) + except UnicodeError: # e.g. '::1' + return raw.encode("ascii").decode("idna") + + +@functools.lru_cache(_MAXCACHE) +def _idna_encode(host): + try: + return idna.encode(host, uts46=True).decode("ascii") + except UnicodeError: + return host.encode("idna").decode("ascii") + + +@rewrite_module +def cache_clear(): + _idna_decode.cache_clear() + _idna_encode.cache_clear() + + +@rewrite_module +def cache_info(): + return { + "idna_encode": _idna_encode.cache_info(), + "idna_decode": _idna_decode.cache_info(), + } + + +@rewrite_module +def cache_configure(*, idna_encode_size=_MAXCACHE, idna_decode_size=_MAXCACHE): + global _idna_decode, _idna_encode + + _idna_encode = functools.lru_cache(idna_encode_size)(_idna_encode.__wrapped__) + _idna_decode = functools.lru_cache(idna_decode_size)(_idna_decode.__wrapped__) diff --git a/env/Lib/site-packages/yarl/py.typed b/env/Lib/site-packages/yarl/py.typed new file mode 100644 index 0000000..dcf2c80 --- /dev/null +++ b/env/Lib/site-packages/yarl/py.typed @@ -0,0 +1 @@ +# Placeholder diff --git a/project/__pycache__/config.cpython-311.pyc b/project/__pycache__/config.cpython-311.pyc new file mode 100644 index 0000000..b53a14b Binary files /dev/null and b/project/__pycache__/config.cpython-311.pyc differ diff --git a/project/__pycache__/db.cpython-311.pyc b/project/__pycache__/db.cpython-311.pyc new file mode 100644 index 0000000..0284ae6 Binary files /dev/null and b/project/__pycache__/db.cpython-311.pyc differ diff --git a/project/bot.py b/project/bot.py new file mode 100644 index 0000000..0fcc23c --- /dev/null +++ b/project/bot.py @@ -0,0 +1,178 @@ +import psycopg2 +import telebot +from telebot import types +import config + +# Конфигурация +API_TOKEN = config.TOKEN +DATABASE_URL = config.DB_URL +SUPPORT_CHAT_ID = config.ADMIN_CHAT +SENIOR_CURATOR_CHAT_ID = config.SENIOR_CHAT + +bot = telebot.TeleBot(API_TOKEN) + +# Подключение к базе данных +conn = psycopg2.connect(DATABASE_URL) +cursor = conn.cursor() + +# Команда /start +@bot.message_handler(commands=['start']) +def start_command(message): + user_id = message.from_user.id + + cursor.execute("SELECT full_name, role FROM users WHERE user_id = %s", (user_id,)) + user = cursor.fetchone() + + if user: + bot.send_message(message.chat.id, f"Ваши данные:\nФИО: {user[0]}\nРоль: {user[1]}") + show_options(message, user[1]) + else: + msg = bot.send_message(message.chat.id, "Добро пожаловать! Пожалуйста, укажите ваше полное имя.") + bot.register_next_step_handler(msg, process_full_name) + +# Получаем ФИО пользователя +def process_full_name(message): + full_name = message.text + user_id = message.from_user.id + + cursor.execute("INSERT INTO users (user_id, full_name) VALUES (%s, %s) ON CONFLICT (user_id) DO UPDATE SET full_name = EXCLUDED.full_name", (user_id, full_name)) + conn.commit() + + # Запрос роли пользователя с кнопками + markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) + markup.add('Куратор', 'Первокурсник') + msg = bot.send_message(message.chat.id, "Пожалуйста, выберите вашу роль.", reply_markup=markup) + bot.register_next_step_handler(msg, process_role) + +# Получаем роль пользователя +def process_role(message): + role = message.text + user_id = message.from_user.id + + if role not in ["Куратор", "Первокурсник"]: + msg = bot.send_message(message.chat.id, "Пожалуйста, выберите роль из предложенных вариантов.") + bot.register_next_step_handler(msg, process_role) + return + + cursor.execute("UPDATE users SET role = %s WHERE user_id = %s", (role, user_id)) + conn.commit() + + if role == "Куратор": + msg = bot.send_message(message.chat.id, "Какую группу вы курируете?") + else: + msg = bot.send_message(message.chat.id, "В какой группе вы учитесь?") + + bot.register_next_step_handler(msg, process_group) + +# Получаем группу пользователя +def process_group(message): + group_name = message.text + user_id = message.from_user.id + + cursor.execute("SELECT full_name, role FROM users WHERE user_id = %s", (user_id,)) + user_data = cursor.fetchone() + + if user_data is None: + bot.send_message(message.chat.id, "Произошла ошибка. Пожалуйста, начните регистрацию заново.") + return + + cursor.execute( + "UPDATE users SET group_name = %s WHERE user_id = %s", + (group_name, user_id) + ) + conn.commit() + + bot.send_message(message.chat.id, f"Регистрация завершена!\nФИО: {user_data[0]}\nРоль: {user_data[1]}") + + show_options(message, user_data[1]) + +# Функция для отображения опций +def show_options(message, role): + markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True) + if role == "Куратор": + markup.add('Отчитаться', 'Тех. поддержка', 'Старший куратор') + elif role == "Первокурсник": + markup.add('Расскажу о кураторе', 'Тех. поддержка', 'Старший куратор') + + bot.send_message(message.chat.id, "Выберите одну из опций:", reply_markup=markup) + +# Обработка обращений в тех.поддержку +@bot.message_handler(func=lambda message: message.text == "Тех. поддержка") +def tech_support(message): + msg = bot.send_message(message.chat.id, "Пожалуйста, напишите ваше сообщение в тех.поддержку.") + bot.register_next_step_handler(msg, process_support_message) + +# Обработка сообщения для тех.поддержки +def process_support_message(message): + support_message = message.text + user_id = message.from_user.id + name = message.from_user.username + + # Отправляем сообщение в тех.поддержку + bot.send_message(SUPPORT_CHAT_ID, f"Сообщение от пользователя @{name}:\n{support_message}") + + # Отправляем подтверждение пользователю + bot.send_message(message.chat.id, "Ваше сообщение отправлено в тех.поддержку. Спасибо!") + + # Возвращаемся к меню выбора опций + cursor.execute("SELECT role FROM users WHERE user_id = %s", (user_id,)) + role = cursor.fetchone() + if role: + show_options(message, role[0]) + +# Обработка отчетов кураторов +@bot.message_handler(func=lambda message: message.text == "Отчитаться") +def curator_report(message): + user_id = message.from_user.id + + cursor.execute("SELECT role FROM users WHERE user_id = %s", (user_id,)) + role = cursor.fetchone() + + if role is None or role[0] != "Куратор": + bot.send_message(message.chat.id, "Эта опция доступна только для кураторов.") + show_options(message, role[0] if role else 'Неизвестно') + return + + bot.send_message(message.chat.id, "Введите ваш отчет...") # Здесь будет логика обработки отчетов + +# Обработка отзывов первокурсников +@bot.message_handler(func=lambda message: message.text == "Расскажу о кураторе") +def freshman_feedback(message): + user_id = message.from_user.id + + cursor.execute("SELECT role FROM users WHERE user_id = %s", (user_id,)) + role = cursor.fetchone() + + if role is None or role[0] != "Первокурсник": + bot.send_message(message.chat.id, "Эта опция доступна только для первокурсников.") + show_options(message, role[0] if role else 'Неизвестно') + return + + bot.send_message(message.chat.id, "Введите ваш отзыв о кураторе...") # Логика обработки отзывов + +# Обработка обращения к старшему куратору +@bot.message_handler(func=lambda message: message.text == "Старший куратор") +def senior_curator(message): + msg = bot.send_message(message.chat.id, "Пожалуйста, напишите ваше сообщение для старшего куратора.") + bot.register_next_step_handler(msg, process_senior_curator_message) + +# Обработка сообщения для старшего куратора +def process_senior_curator_message(message): + senior_message = message.text + user_id = message.from_user.id + name = message.from_user.username + + # Отправляем сообщение старшему куратору + bot.send_message(SENIOR_CURATOR_CHAT_ID, f"Сообщение от пользователя @{name}:\n{senior_message}") + + # Отправляем подтверждение пользователю + bot.send_message(message.chat.id, "Ваше сообщение отправлено старшему куратору. Спасибо!") + + # Возвращаемся к меню выбора опций + cursor.execute("SELECT role FROM users WHERE user_id = %s", (user_id,)) + role = cursor.fetchone() + if role: + show_options(message, role[0]) + +# Запуск бота +bot.polling() \ No newline at end of file