### call_batch usage example Source: https://github.com/alexeyleshchenko/fast_bitrix24 Example batch call with halt=0 and chained commands using $result references. ```python results = await bx.call_batch({ "halt": 0, "cmd": { "deals": "crm.deal.list", # используем результат первой команды внутри второй "activities": "crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]", }, }) print(results["deals"]) ``` -------------------------------- ### get_all constraint check: order parameter Source: https://github.com/alexeyleshchenko/fast_bitrix24 Demonstrates that passing 'order' in params raises a ValueError with the message "get_all() doesn't support parameters 'start' or 'order'". This is a constraint check example. ```python try: await bx.get_all("crm.deal.list", params={"order": {"ID": "DESC"}}) except ValueError as e: print(e) # get_all() doesn't support parameters 'start' or 'order' ``` -------------------------------- ### get_all example: fetch deals with user fields Source: https://github.com/alexeyleshchenko/fast_bitrix24 Example usage of get_all to fetch deals in progress including user fields. Uses the 'crm.deal.list' method with a filter for non-closed deals. ```python # список сделок в работе, включая пользовательские поля deals = await bx.get_all( "crm.deal.list", params={"select": ["*", "UF_*"], "filter": {"CLOSED": "N"}}, ) ``` -------------------------------- ### list_and_get usage example Source: https://github.com/alexeyleshchenko/fast_bitrix24 Example call to list_and_get with 'crm.lead' branch. Returns dict of entity fields keyed by ID. ```python all_lead_info = await bx.list_and_get("crm.lead") ``` -------------------------------- ### Basic Bitrix webhook setup Source: https://github.com/alexeyleshchenko/fast_bitrix24 Creates a Bitrix instance with a standard webhook URL. ```python from fast_bitrix24 import Bitrix # стандартный вебхук bx = Bitrix("https://domain.bitrix24.ru/rest/1/code/") ``` -------------------------------- ### BitrixAsync usage example Source: https://github.com/alexeyleshchenko/fast_bitrix24 Shows how to instantiate the async client with a webhook and call get_all to fetch CRM leads. Requires a valid webhook URL. ```python from fast_bitrix24 import BitrixAsync # замените на ваш вебхук bx = BitrixAsync("https://your_domain.bitrix24.ru/rest/1/your_code/") leads = await bx.get_all("crm.lead.list") print(leads) ``` -------------------------------- ### Bitrix usage example Source: https://github.com/alexeyleshchenko/fast_bitrix24 Shows synchronous calls without await, including get_all, call, and slow context manager. Errors propagate from sync wrappers. ```python from fast_bitrix24 import Bitrix bx = Bitrix("https://your_domain.bitrix24.ru/rest/1/your_code/") leads = bx.get_all("crm.lead.list") # без await updated = bx.call("crm.deal.update", tasks) with bx.slow(): bx.call("crm.lead.add", many_leads) ``` -------------------------------- ### call usage example: batch update Source: https://github.com/alexeyleshchenko/fast_bitrix24 Batch update of deal titles using call with a list of items. ```python # массовое обновление: вставляем ID в начало названий сделок tasks = [ {"ID": d["ID"], "fields": {"TITLE": f'{d["ID"]} - {d["TITLE"]}'}} for d in deals ] results = await bx.call("crm.deal.update", tasks) ``` -------------------------------- ### list_and_get example Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/API.md Deprecated method that downloads all IDs via method_branch.list and then all fields via method_branch.get. Use for large data volumes (over 20k items) for better speed than get_all with select ['*', 'UF_*']. Does not work with method groups that use different ID field names in list and get. ```python all_lead_info = b.list_and_get('crm.lead') ``` -------------------------------- ### call_batch example with $result Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/API.md Calls the batch method, supporting use of results from one command in another via $result. The example fetches a deal list and then activities for the first deal. ```python results = b.call_batch({ 'halt': 0, 'cmd': { 'deals': 'crm.deal.list', # берем список сделок # и берем список дел по первой из них 'activities': 'crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]' } }) ``` -------------------------------- ### get_by_ID example: fetch contacts for deals Source: https://github.com/alexeyleshchenko/fast_bitrix24 Example usage of get_by_ID to fetch contacts linked to deals. First gets all open deals, then retrieves contact items for each deal ID. ```python deals = await bx.get_all("crm.deal.list", params={"filter": {"CLOSED": "N"}}) contacts = await bx.get_by_ID( "crm.deal.contact.items.get", [d["ID"] for d in deals], ) # -> {ID_сделки_1: [контакт_1, ...], ID_сделки_2: [...], ...} ``` -------------------------------- ### get_warning_stack_level usage example Source: https://github.com/alexeyleshchenko/fast_bitrix24 Example of using get_warning_stack_level to set the stacklevel for warnings.warn, ensuring the warning points to the user's my_function() call rather than the library. ```python import warnings from fast_bitrix24.utils import get_warning_stack_level def my_function(): warnings.warn( "Предупреждение пользователю", UserWarning, stacklevel=get_warning_stack_level(["fast_bitrix24\\bitrix", "fast_bitrix24/bitrix"]), ) my_function() # предупреждение укажет на строку my_function(), а не на библиотеку ``` -------------------------------- ### OAuth token function and Bitrix setup Source: https://github.com/alexeyleshchenko/fast_bitrix24 Defines an async function to obtain a new OAuth token and passes it to Bitrix. The token_func is called on first request and on HTTP 401 responses. ```python async def get_new_token() -> str: import requests result = requests.get( "https://oauth.bitrix.info/oauth/token/", timeout=10, params={ "grant_type": "refresh_token", "client_id": ..., "client_secret": ..., "refresh_token": ..., }, ) return result.json()["access_token"] bx = Bitrix(webhook="https://domain.bitrix24.ru/rest/app_id/", token_func=get_new_token) ``` -------------------------------- ### _url_valid usage example Source: https://github.com/alexeyleshchenko/fast_bitrix24 Demonstrates _url_valid with a valid Bitrix24 webhook URL, a plain string, and None. Outputs True, False, False respectively. ```python from fast_bitrix24.utils import _url_valid print(_url_valid("https://domain.bitrix24.ru/rest/1/code/")) # True print(_url_valid("not a url")) # False print(_url_valid(None)) # False ``` -------------------------------- ### make_remaining_requests method with icontract decorator Source: https://github.com/alexeyleshchenko/fast_bitrix24 Fetches remaining pages using start parameters and handles batch requests. Raises ValueError if results is not a list. ```python @icontract.require(lambda self: isinstance(self.results, list)) async def make_remaining_requests(self): ``` -------------------------------- ### slow context manager example Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/API.md Limits concurrent requests to the Bitrix server to avoid 500 errors or timeouts when sending resource-intensive requests. The example limits to 5 concurrent requests while adding 2500 leads, then resumes normal speed. ```python # временно ограничиваем скорость # до 5 параллельно выполняемых запросов max_concurrent_requests = 5 with b.slow(max_concurrent_requests): b.call('crm.lead.add', [{'NAME': x} for x in range(2500)]) # а теперь несемся с прежней скоростью leads = b.get_all('crm.lead.list') ... ``` -------------------------------- ### http_build_query usage example with filter dict Source: https://github.com/alexeyleshchenko/fast_bitrix24 Serializes a filter dict into a query string. Output shows nested keys without URL encoding for numeric values. ```python print(http_build_query({"filter": {"ENTITY_TYPE": 3, "ENTITY_ID": 5}})) # filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=5& ``` -------------------------------- ### log Source: https://github.com/alexeyleshchenko/fast_bitrix24 Decorator for async functions that logs the start of the call (function name, arguments) at INFO level, and at DEBUG level logs the package version and IPython presence. Applied to methods of the BitrixAsync class. ```APIDOC ## log ### Description Decorator for async functions that logs the start of the call (function name, arguments) at INFO level, and at DEBUG level logs the package version and IPython presence. Applied to methods of the BitrixAsync class. ### Signature ```python def log(func): async def wrapper(*args, **kwargs): logger.info(f"Starting {func.__name__}({args}, {kwargs})") logger.debug(f"fast_bitrix24 version: {__version__}") try: from IPython import get_ipython logger.debug(f"IPython: {get_ipython()}") except ImportError: logger.debug("No IPython found") return await func(*args, **kwargs) return wrapper ``` ### Returns `Awaitable` - Wrapped coroutine with the result of the original function. ``` -------------------------------- ### http_build_query usage example with nested dict and list Source: https://github.com/alexeyleshchenko/fast_bitrix24 Serializes a dict with nested dict and list into a URL-encoded query string. Output shows URL-encoded Cyrillic and indexed list syntax. ```python from fast_bitrix24.utils import http_build_query print(http_build_query({"ID": 1, "fields": {"TITLE": "Привет", "X": [1, 2, 3]}})) # ID=1&fields[TITLE]=%D0%9F%D1%80%D0%B8%D0%B2%D0%B5%D1%82&fields[X][0]=1&fields[X][1]=2&fields[X][2]=3& ``` -------------------------------- ### Direct usage of ServerRequestHandler Source: https://github.com/alexeyleshchenko/fast_bitrix24 Shows how to instantiate ServerRequestHandler directly with a webhook, token_func, and various configuration parameters, then run a request and handle errors. The example includes closing the session if it was not provided by the user. ```python import aiohttp from fast_bitrix24.srh import ServerRequestHandler async def token_func(): return "my_oauth_token" handler = ServerRequestHandler( webhook="https://domain.bitrix24.ru/rest/1/code/", token_func=token_func, respect_velocity_policy=True, request_pool_size=50, requests_per_second=2.0, operating_time_limit=480, client=None, ) async def main(): response = await handler.run_async( handler.single_request("crm.lead.list", {"select": ["ID"]}) ) # на случай ошибок сервера from fast_bitrix24.srh import ServerError, TokenRejectedError try: response = await handler.single_request("crm.lead.list") except TokenRejectedError: print("токен отклонён — будет запрошен новый") except ServerError: print("сервер вернул 5XX — попытка будет повторена") await handler.session.close() # если сессия не предоставлена пользователем ``` -------------------------------- ### Метод check_expected_clause_types Source: https://github.com/alexeyleshchenko/fast_bitrix24 Проверяет типы значений стандартизированных ключей (SELECT, HALT, CMD, LIMIT, ORDER, FILTER, START, FIELDS). Бросает TypeError при несоответствии. ```python def check_expected_clause_types(self, p): ``` -------------------------------- ### call_batch() - Call batch methods Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Use call_batch() to invoke batch methods. The example shows a batch with halt=0 and multiple commands, including a reference to a previous result. ```python results = bx.call_batch ({ 'halt': 0, 'cmd': { 'deals': 'crm.deal.list', # берем список сделок # и берем список дел по первой из них 'activities': 'crm.activity.list?filter[ENTITY_TYPE]=3&filter[ENTITY_ID]=$result[deals][0][ID]' } }) ``` -------------------------------- ### call usage example: raw=True for clearing fields and legacy methods Source: https://github.com/alexeyleshchenko/fast_bitrix24 Use raw=True to send items as-is, e.g., to clear a field with None or for legacy methods that accept a list as a single parameter. ```python # стереть DESCRIPTION в лиде 123 (None в батче превращается в строку) await bx.call("crm.lead.update", {"ID": 123, "fields": {"DESCRIPTION": None}}, raw=True) # устаревшие методы принимают список как один параметр await bx.call("task.commentitem.add", [123, {"POST_MESSAGE": "Комментарий"}], raw=True) ``` -------------------------------- ### Parsing a server response with ServerResponseParser Source: https://github.com/alexeyleshchenko/fast_bitrix24 Direct usage example for parsing an arbitrary server response, e.g., from crm.lead.list. Shows accessing total, checking for more results, and extracting results. ```python from fast_bitrix24.server_response import ServerResponseParser, ErrorInServerResponseException # ответ сервера на crm.lead.list response = { "result": [{"ID": 1, "NAME": "Иван"}, {"ID": 2, "NAME": "Пётр"}], "total": 2, } parser = ServerResponseParser(response) print(parser.total) # 2 print(parser.more_results_expected()) # False (total <= 50) results = parser.extract_results() # [{"ID": 1, ...}, {"ID": 2, ...}] ``` -------------------------------- ### get_all Source: https://github.com/alexeyleshchenko/fast_bitrix24 Retrieves the full list of entities for a given Bitrix24 REST API method. It handles parallel requests, batch assembly, and pagination automatically, but does not support the 'start', 'limit', or 'order' parameters. ```APIDOC ## get_all ### Description Retrieves the full list of entities for a given Bitrix24 REST API method. It handles parallel requests, batch assembly, and pagination automatically, but does not support the 'start', 'limit', or 'order' parameters. ### Method async def get_all(self, method: str, params: dict = None) -> Union[list, dict] ### Parameters - **method** (str) - Required - Bitrix24 REST API method, e.g., "crm.lead.list" - **params** (dict) - Optional - Parameters in Bitrix24 REST API documentation format ### Response Returns a list of entities or a dict for methods whose result is not a list (e.g., crm.lead.fields). ### Exceptions - ValueError: if params contain 'start' or 'order' (not supported) - ValueError: if method starts with 'tasks.elapseditem.' (use call(raw=True) instead) - UserWarning: if method does not end with one of ALL_ENDINGS, or if LIMIT is passed, or if all fields ("*") are selected without a filter - RuntimeWarning: if the number of returned results does not match the 'total' from the server response ### Request Example ```python deals = await bx.get_all( "crm.deal.list", params={"select": ["*", "UF_*"], "filter": {"CLOSED": "N"}}, ) ``` ### Error Example ```python try: await bx.get_all("crm.deal.list", params={"order": {"ID": "DESC"}}) except ValueError as e: print(e) # get_all() doesn't support parameters 'start' or 'order' ``` ``` -------------------------------- ### log decorator implementation Source: https://github.com/alexeyleshchenko/fast_bitrix24 Decorator for async functions that logs the start of the call at INFO level (function name, arguments), and at DEBUG level logs the package version and IPython presence. Returns an awaitable wrapping the original coroutine. ```python def log(func): async def wrapper(*args, **kwargs): logger.info(f"Starting {func.__name__}({args}, {kwargs})") logger.debug(f"fast_bitrix24 version: {__version__}") try: from IPython import get_ipython logger.debug(f"IPython: {get_ipython()}") except ImportError: logger.debug("No IPython found") return await func(*args, **kwargs) return wrapper ``` -------------------------------- ### BitrixAsync.__init__ Source: https://github.com/alexeyleshchenko/fast_bitrix24 Constructor for the asynchronous Bitrix24 client. Initializes the client with a webhook URL and optional OAuth token function, along with various performance and behavior settings. ```APIDOC ## BitrixAsync.__init__ ### Description Constructor for the asynchronous Bitrix24 client. Initializes the client with a webhook URL and optional OAuth token function, along with various performance and behavior settings. ### Method Constructor ### Signature ```python @beartype def __init__( self, webhook: str, token_func=None, verbose: bool = True, respect_velocity_policy: bool = True, request_pool_size: int = 50, requests_per_second: float = 2.0, batch_size: int = 50, operating_time_limit: int = 480, client: aiohttp.ClientSession = None, ssl: bool = True, ): ``` ### Parameters - `webhook` (str) - Required - URL of the webhook obtained from the Bitrix server. - `token_func` (Awaitable) - Optional - Async function to obtain and refresh OAuth token; if None, OAuth is not used. - `verbose` (bool) - Optional - Whether to show progress bar during request execution. Default: True. - `respect_velocity_policy` (bool) - Optional - Whether to respect Bitrix's official request rate policy. Default: True. - `request_pool_size` (int) - Optional - Size of the request pool that can be sent without waiting. Default: 50. - `requests_per_second` (float) - Optional - Maximum request rate after pool overflow. Default: 2.0. - `batch_size` (int) - Optional - Maximum number of requests in one batch. Default: 50. - `operating_time_limit` (int) - Optional - Maximum total execution time for requests of one REST method per 10 minutes, after which requests are slowed down. Default: 480. - `client` (aiohttp.ClientSession) - Optional - Custom aiohttp session; user is expected to open and close it. Default: None. - `ssl` (bool) - Optional - Whether to verify SSL certificate for HTTP connections. Default: True. ### Raises - `ValueError` - If `token_func` is provided but is not an async (coroutine) function: "`token_func` must be an async function." ### Instance Attributes - `self.srh: ServerRequestHandler` - Request handler. - `self.verbose: bool` - Progress bar flag. - `self.batch_size: int` - Batch size. ### Request Example ```python from fast_bitrix24 import BitrixAsync # replace with your webhook bx = BitrixAsync("https://your_domain.bitrix24.ru/rest/1/your_code/") leads = await bx.get_all("crm.lead.list") print(leads) ``` Error handling for invalid token_func: ```python def sync_token(): # not async - will cause error return "token" try: BitrixAsync("https://your_domain.bitrix24.ru/rest/1/your_code/", token_func=sync_token) except ValueError as e: print(e) # "`token_func` must be an async function." ``` ``` -------------------------------- ### prepare_item_list method Source: https://github.com/alexeyleshchenko/fast_bitrix24 Adds an "__order" key to each item with a zero-padded order value (e.g., order0000000000) so responses can be mapped back to the original items. ```python def prepare_item_list(self): # ... adding "__order" keys to map results back to items ... self.item_list = [ ChainMap(item, {self.ID_field_name: f"order{i:010}"}) for i, item in enumerate(self.item_list) ] ``` -------------------------------- ### Bitrix() with OAuth Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Initializes the Bitrix client with OAuth authorization. Requires a webhook endpoint and a token function that returns an access token. ```APIDOC ## Bitrix() with OAuth ### Description Initializes the Bitrix client with OAuth authorization. Requires a webhook endpoint and a token function that returns an access token. ### Method N/A ### Endpoint `Bitrix(webhook, token_func)` ### Parameters #### Path Parameters - **webhook** (str) - Required - The Bitrix24 endpoint address. - **token_func** (Callable) - Required - An async function that returns the authorization token. ### Response #### Success Response (200) - **Bitrix** - An instance of the client. ### Request Example ```python from fast_bitrix24 import Bitrix import requests async def get_new_token() -> str: oauth_url = 'https://oauth.bitrix.info/oauth/token/' params={ 'grant_type': 'refresh_token', 'client_id': ..., 'client_secret': ..., 'refresh_token': ... } result = requests.get(oauth_url, timeout=10, params=params) return result.json()["access_token"] bx = Bitrix(webhook=ENDPOINT_ADDRESS, token_func=get_new_token) ``` ``` -------------------------------- ### Сигнатура UserRequestAbstract.__init__ Source: https://github.com/alexeyleshchenko/fast_bitrix24 Параметры пользовательских запросов: params может быть dict или None, по умолчанию None, есть флаг mute. ```python UserRequestAbstract.__init__(self, bitrix, method: str, params: Union[Dict[str, Any], None] = None, mute=False) ``` -------------------------------- ### Import Bitrix and BitrixAsync classes Source: https://github.com/alexeyleshchenko/fast_bitrix24 Shows two equivalent ways to import the public client classes from the fast_bitrix24 package. ```python from fast_bitrix24.bitrix import Bitrix, BitrixAsync # эквивалентно: from fast_bitrix24 import Bitrix, BitrixAsync ``` -------------------------------- ### get_by_ID with custom ID field name Source: https://github.com/alexeyleshchenko/fast_bitrix24 Example of using get_by_ID with the 'tasks.task.get' method and setting ID_field_name to 'taskId' for task groups. ```python tasks = await bx.get_by_ID("tasks.task.get", [1, 2, 3], ID_field_name="taskId") ``` -------------------------------- ### Direct usage of GetAllUserRequest Source: https://github.com/alexeyleshchenko/fast_bitrix24 Shows how to instantiate GetAllUserRequest directly with a Bitrix client and parameters, then run it to fetch leads. Typically these classes are not created directly; use Bitrix/BitrixAsync methods instead. ```python from fast_bitrix24 import Bitrix from fast_bitrix24.user_request import GetAllUserRequest bx = Bitrix("https://domain.bitrix24.ru/rest/1/code/") request = GetAllUserRequest(bx, "crm.lead.list", params={"select": ["ID", "NAME"]}) leads = await request.run() ``` -------------------------------- ### Direct use of MultipleServerRequestHandler to add leads Source: https://github.com/alexeyleshchenko/fast_bitrix24 Shows direct instantiation of MultipleServerRequestHandler with a Bitrix client, method 'crm.lead.add', and a list of parameters. The handler.run() method executes the batch and returns results, printing the count of created leads. ```python from fast_bitrix24 import Bitrix from fast_bitrix24.mult_request import MultipleServerRequestHandler bx = Bitrix("https://domain.bitrix24.ru/rest/1/code/") params_list = [ {"fields": {"NAME": f"Клиент {i}"}} for i in range(120) ] async def add_leads(): handler = MultipleServerRequestHandler(bx, "crm.lead.add", params_list) results = await handler.run() print(f"Создано лидов: {len(results)}") ``` -------------------------------- ### Using Bitrix (sync) client Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Synchronous client usage that may cause asyncio errors in notebooks or Spyder. ```python from fast_bitrix24 import Bitrix bx = Bitrix(webhook) leads = bx.get_all('crm.lead.list') ``` -------------------------------- ### Инициализация объекта Bitrix Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Импортируйте класс Bitrix и создайте объект, передав вебхук для доступа к Bitrix24. Замените URL на ваш собственный вебхук. ```python from fast_bitrix24 import Bitrix # замените на ваш вебхук для доступа к Bitrix24 webhook = "https://your_domain.bitrix24.ru/rest/1/your_code/" bx = Bitrix(webhook) ``` -------------------------------- ### ensure_new_token Source: https://github.com/alexeyleshchenko/fast_bitrix24 Ensures a new OAuth token is obtained. If the token retrieval process has not started, it initiates the retrieval; otherwise, it waits for the parallel token retrieval to complete. ```APIDOC ## ensure_new_token ### Description Ensures a new OAuth token is obtained. If the token retrieval process has not started, it initiates the retrieval; otherwise, it waits for the parallel token retrieval to complete. ### Method async def ensure_new_token(self) ### Parameters None ### Response None ``` -------------------------------- ### Bitrix / BitrixAsync Constructor Source: https://github.com/alexeyleshchenko/fast_bitrix24 Configuration for the fast_bitrix24 client is done through the constructor parameters of the Bitrix and BitrixAsync classes. This snippet documents the constructor signature and all available options. ```APIDOC ## Bitrix / BitrixAsync Constructor ### Description Configuration for the fast_bitrix24 client is done through the constructor parameters of the Bitrix and BitrixAsync classes. This snippet documents the constructor signature and all available options. ### Signature ```python @beartype def __init__( self, webhook: str, token_func=None, verbose: bool = True, respect_velocity_policy: bool = True, request_pool_size: int = 50, requests_per_second: float = 2.0, batch_size: int = 50, operating_time_limit: int = 480, client: aiohttp.ClientSession = None, ssl: bool = True, ): ``` ### Parameters - **webhook** (str) - Required - URL вебхука, полученного от сервера Битрикс (например, `https://domain.bitrix24.ru/rest/1/code/`). Стандартизируется: обрезка пробелов, добавление завершающего `/`; должен быть валидным URL. - **token_func** (Awaitable) - Optional - Асинхронная функция для получения и обновления токена при OAuth-авторизации. При `None` OAuth не используется. Вызывается при первом запросе и при каждом отклонении токена сервером (`TokenRejectedError`). Если функция не async — `ValueError` при инициализации. - **verbose** (bool) - Optional - Показывать ли прогрессбар `tqdm` при выполнении запросов. - **respect_velocity_policy** (bool) - Optional - Соблюдать ли официальную политику Битрикс24 по скорости запросов (Sliding Window по каждому методу). Если `False` — остаётся только Leaky Bucket и autothrottling. - **request_pool_size** (int) - Optional - Размер пула запросов, которые можно отправить на сервер без ожидания (параметр `pool_size` троттлера `LeakyBucketThrottler`). Для Энтерпрайза можно повышать, например `250`. - **requests_per_second** (float) - Optional - Максимальная скорость запросов, применяемая после переполнения пула (`requests_per_second` троттлера `LeakyBucketThrottler`). Для Энтерпрайза — напр. `5`. - **batch_size** (int) - Optional - Максимальное количество запросов, отправляемых на сервер в одном батче (максимум Битрикса — 50). Хранится как `self.batch_size`, используется в `MultipleServerRequestHandler.generate_tasks` при разбиении `item_list` порциями. - **operating_time_limit** (int) - Optional - Максимально допустимое суммарное время отработки запросов одного метода REST API в секундах за 10 минут, после которого запросы замедляются (параметр `max_request_running_time` троттлера `SlidingWindowThrottler`). - **client** (aiohttp.ClientSession) - Optional - Пользовательская `aiohttp`-сессия для HTTP-вызовов. Ожидается, что пользователь сам открывает и закрывает сессию; библиотека его сессию не трогает (`handle_sessions`). - **ssl** (bool) - Optional - Проверять ли SSL-сертификат при HTTP-соединениях с сервером Битрикс. Отключите (`ssl=False`) при `SSLCertVerificationError`/`CERTIFICATE_VERIFY_FAILED`. ``` -------------------------------- ### check_special_limitations method with icontract decorators Source: https://github.com/alexeyleshchenko/fast_bitrix24 Validates that get_all() is not used with 'start' or 'order' parameters and not with 'tasks.elapseditem.*' method group. Raises ValueError via icontract if conditions are violated. ```python @icontract.require( lambda self: not self.st_params or set(self.st_params.keys()).isdisjoint({"START", "ORDER"}), "get_all() doesn't support parameters 'start' or 'order'", ) @icontract.require( lambda self: not self.st_method.startswith("tasks.elapseditem."), "get_all() shouldn't be used with 'tasks.elapseditem.*' method group. " "Use call(raw=True) instead. Read more: " "https://github.com/alexeyleshchenko/fast_bitrix24/issues/199", ) def check_special_limitations(self): ``` -------------------------------- ### ServerRequestHandler: передача опций клиента Source: https://github.com/alexeyleshchenko/fast_bitrix24 Клиент передаёт в обработчик подмножество своих опций. Используется для настройки обработчика запросов. ```python ServerRequestHandler( webhook=webhook, token_func=token_func, respect_velocity_policy=respect_velocity_policy, request_pool_size=request_pool_size, requests_per_second=requests_per_second, operating_time_limit=operating_time_limit, ssl=ssl, client=client, ) ``` -------------------------------- ### call() Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Creates, modifies, or deletes a list of entities. Returns a list of server responses for each item. ```APIDOC ## call() ### Description Creates, modifies, or deletes a list of entities. Returns a list of server responses for each item. ### Method POST ### Endpoint `call(method: str, items: dict | Iterable[dict] | None = None, raw: bool = False) -> dict | list[dict]` ### Parameters #### Path Parameters - **method** (str) - Required - The Bitrix24 API method to call (e.g., 'crm.deal.update'). - **items** (dict | Iterable[dict]) - Required - The data to send, either a single dict or a list of dicts. - **raw** (bool) - Optional - If True, sends parameters as-is without batching (default: False). ### Response #### Success Response (200) - **dict | list[dict]** - Server response(s). ### Request Example ```python tasks = [ { 'ID': d['ID'], 'fields': { 'TITLE': f'{d["ID"]} - {d["TITLE"]}' } } for d in deals ] bx.call('crm.deal.update', tasks) ``` ``` -------------------------------- ### Установка модуля через pip Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Установите модуль fast-bitrix24 с помощью pip. ```shell pip install fast-bitrix24 ``` -------------------------------- ### prepare_item_list builds parameter dicts Source: https://github.com/alexeyleshchenko/fast_bitrix24 Creates a list of parameter dicts, one per ID. If params exist, each dict is a ChainMap combining ID_field_name with params; otherwise just {ID_field_name: ID}. ```python def prepare_item_list(self): if self.params: self.item_list = [ ChainMap({self.ID_field_name: ID}, self.params) for ID in self.ID_list ] else: self.item_list = [{self.ID_field_name: ID} for ID in self.ID_list] ``` -------------------------------- ### Настройка параметров нагрузки при инициализации Bitrix Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Позволяет регулировать нагрузку на сервер через параметры request_pool_size, requests_per_second, batch_size и operating_time_limit. Значения по умолчанию указаны в комментариях. ```python bx = Bitrix( webhook, request_pool_size = 20, # по умолчанию - 50 requests_per_second = 1.0, # по умолчанию - 2.0 batch_size = 20, # по умолчанию - 50 operating_time_limit = 100, # по умолчанию - 480 ) ``` -------------------------------- ### Отключение проверки SSL-сертификата Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Используйте ssl=False при инициализации BitrixAsync, если получаете ошибки SSLCertVerificationError или CERTIFICATE_VERIFY_FAILED. ```python bx = BitrixAsync(webhook, ssl=False) ``` -------------------------------- ### Direct usage of LeakyBucketThrottler Source: https://github.com/alexeyleshchenko/fast_bitrix24 Used directly when you need to limit request rate. The example shows a bucket with pool_size=2 and requests_per_second=1.0, allowing 2 requests without waiting, then 1 request per second. ```python import asyncio from fast_bitrix24.throttle import SlidingWindowThrottler, LeakyBucketThrottler # 2 запроса без ожидания, далее 1 запрос в секунду bucket = LeakyBucketThrottler(pool_size=2, requests_per_second=1.0) async def limited_request(i): async with bucket.acquire(): print(f"запрос {i} выполняется") async def main(): for i in range(5): await limited_request(i) asyncio.run(main()) ``` -------------------------------- ### MultipleServerRequestHandler constructor Source: https://github.com/alexeyleshchenko/fast_bitrix24 Initialize the handler with client, method, item list, and optional parameters for progress bar and ID preservation. ```python def __init__( self, bitrix, method, item_list, real_len=None, real_start=0, mute=False, get_by_ID=False, ): ``` -------------------------------- ### run method Source: https://github.com/alexeyleshchenko/fast_bitrix24 Executes the request. Handles single dict input by wrapping it in a list, prepares the item list, and dispatches to MultipleServerRequestHandlerPreserveIDs. Returns a tuple for list input, the first result for single dict input, or the raw result otherwise. ```python async def run(self): is_single_item = isinstance(self.item_list, dict) if is_single_item: self.item_list = [self.item_list] self.prepare_item_list() raw_results = await MultipleServerRequestHandlerPreserveIDs( self.bitrix, self.method, self.item_list, ID_field=self.ID_field_name, get_by_ID=False, ).run() if isinstance(raw_results, dict) and not is_single_item: return tuple(raw_results.values()) elif raw_results and isinstance(raw_results, list) and is_single_item: return raw_results[0] else: return raw_results ``` -------------------------------- ### ensure_new_token method Source: https://github.com/alexeyleshchenko/fast_bitrix24 Defines the async method that obtains a new token if the token retrieval process has not started, or waits for its completion. The method clears the token_received event, calls token_func, and sets the event again. ```python async def ensure_new_token(self): """Получает новый токен, если процесс получения токена еще не запущен, или ждет его завершения.""" ``` -------------------------------- ### Import utility functions from fast_bitrix24.utils Source: https://github.com/alexeyleshchenko/fast_bitrix24 Import the public utility functions http_build_query and get_warning_stack_level from the module. ```python from fast_bitrix24.utils import http_build_query, get_warning_stack_level ``` -------------------------------- ### Bitrix.__init__ Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/API.md Creates a Bitrix client for accessing Bitrix24. Initializes the client with webhook URL and optional OAuth token function, along with various configuration parameters. ```APIDOC ## Bitrix.__init__ ### Description Creates a Bitrix client for accessing Bitrix24. Initializes the client with webhook URL and optional OAuth token function, along with various configuration parameters. ### Method Constructor ### Signature `__init__(self, webhook: str, token_func: Awaitable = None, verbose: bool = True, respect_velocity_policy: bool = True, request_pool_size: int = 50, requests_per_second: float = 2.0, batch_size: int = 50, operating_time_limit: int = 480, ssl: bool = True, client: aiohttp.ClientSession = None)` ### Parameters - `webhook` (str) - Required - URL of the webhook received from the Bitrix server. - `token_func` (Awaitable) - Optional - Reference to an async function that returns an OAuth token for requests to the server. If not specified, OAuth authorization is not used. - `verbose` (bool) - Optional - Show progress bar during request execution. Default: True. - `respect_velocity_policy` (bool) - Optional - Respect Bitrix's request speed policy. Default: True. - `request_pool_size` (int) - Optional - Size of the request pool that can be sent to the server without waiting. Default: 50. - `requests_per_second` (float) - Optional - Maximum request speed used after the pool is exhausted. Default: 2.0. - `batch_size` (int) - Optional - Maximum number of requests sent to the server in one batch. Default: 50. - `operating_time_limit` (int) - Optional - Maximum allowed operating time for requests to one REST API method in seconds, allowed within 10 minutes, after which requests will be slowed down. Default: 480. - `ssl` (bool) - Optional - Whether to use SSL certificate verification for HTTP connections to the Bitrix server. Default: True. - `client` (aiohttp.ClientSession) - Optional - Use a user-initialized and configured client for HTTP calls. ### Notes - The `request_pool_size` and `requests_per_second` parameters are set according to Bitrix24 limitations. They can be increased for Enterprise plans or decreased to reduce request speed. ``` -------------------------------- ### logger object initialization Source: https://github.com/alexeyleshchenko/fast_bitrix24 Creates the fast_bitrix24 logger with name 'fast_bitrix24', level DEBUG, and a NullHandler by default (no output). To see request/response logs, add a handler. ```python logger = getLogger("fast_bitrix24") logger.setLevel(DEBUG) logger.addHandler(NullHandler()) ``` -------------------------------- ### get_all method signature Source: https://github.com/alexeyleshchenko/fast_bitrix24 Signature of the get_all method. It retrieves a full list of entities via a REST API method, using parallel requests and batching. Does not support 'start', 'limit', or 'order' parameters. ```python @log async def get_all(self, method: str, params: dict = None) -> Union[list, dict]: ``` -------------------------------- ### run method of GetAllUserRequest Source: https://github.com/alexeyleshchenko/fast_bitrix24 Executes the get_all() workflow: adds order parameter, makes first request, loads remaining pages if needed, deduplicates results, and returns them. ```python async def run(self): self.add_order_parameter() await self.make_first_request() if self.first_response.more_results_expected(): await self.make_remaining_requests() self.dedup_results() return self.results ``` -------------------------------- ### Конструктор UserRequestAbstract Source: https://github.com/alexeyleshchenko/fast_bitrix24 Конструктор абстрактного базового класса пользовательского запроса. Проверяет и стандартизирует метод и параметры. Метод не может быть пустым или равным 'batch' (используйте call_batch()). ```python @beartype @icontract.require(lambda method: method, "Method cannot be empty") def __init__( self, bitrix, method: str, params: Union[Dict[str, Any], None] = None, mute=False, ): ``` -------------------------------- ### success and failure methods Source: https://github.com/alexeyleshchenko/fast_bitrix24 success() increments the successful attempts counter. failure() increments the failure counter and raises RuntimeError("All attempts to get data from server exhausted") when attempts are exhausted. ```python def success(self): """Увеличить счетчик удачных попыток.""" def failure(self, err: Exception): """Увеличить счетчик неудачных попыток и поднять исключение, если попытки исчерпаны.""" ``` -------------------------------- ### Direct usage of SlidingWindowThrottler Source: https://github.com/alexeyleshchenko/fast_bitrix24 Used directly when you need to limit total execution time over a period. The example shows a window with max_request_running_time=3.0 and measurement_period=10.0, allowing no more than 3 seconds of total execution time per 10 seconds. ```python window = SlidingWindowThrottler(max_request_running_time=3.0, measurement_period=10.0) async def work(i): async with window.acquire(): # имитация выполнения запроса await asyncio.sleep(1) window.add_request_record(1.0) # регистрируем длительность async def main(): for i in range(5): await work(i) asyncio.run(main()) ``` -------------------------------- ### make_first_request method Source: https://github.com/alexeyleshchenko/fast_bitrix24 Sends the initial request, parses the response, and stores total and results. ```python async def make_first_request(self): self.first_response = ServerResponseParser( await self.srh.single_request(self.method, self.params) ) self.total = self.first_response.total self.results = self.first_response.extract_results() ``` -------------------------------- ### BitrixAsync constructor signature Source: https://github.com/alexeyleshchenko/fast_bitrix24 Defines the async client constructor with parameters for webhook, token function, verbosity, velocity policy, request pool size, requests per second, batch size, operating time limit, custom aiohttp session, and SSL verification. Raises ValueError if token_func is not async. ```python @beartype def __init__( self, webhook: str, token_func=None, verbose: bool = True, respect_velocity_policy: bool = True, request_pool_size: int = 50, requests_per_second: float = 2.0, batch_size: int = 50, operating_time_limit: int = 480, client: aiohttp.ClientSession = None, ssl: bool = True, ): ``` -------------------------------- ### ListAndGetUserRequest run method with icontract precondition Source: https://github.com/alexeyleshchenko/fast_bitrix24 Run method for list_and_get() that loads all IDs via *.list and then fetches each entity via *.get. Enforces via icontract that method_branch does not end in '.list' or '.get'. Raises ValueError if the list results lack the ID field. ```python @icontract.require( lambda self: not re.search( r"(\.list|\.get)$", self.method_branch.strip().lower() ), 'list_and_get(): "method_branch" should not end in ".list" or ".get"', ) async def run(self): ``` -------------------------------- ### Get all deals and their contacts using get_all and get_by_ID Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/API.md Retrieves all open deals with get_all, then fetches contacts for each deal ID using get_by_ID. The get_by_ID method requires an iterable of IDs and returns a dictionary keyed by ID. ```python deals = b.get_all( 'crm.deal.list', params={'filter': {'CLOSED': 'N'}}) contacts = b.get_by_ID( 'crm.deal.contact.item.get', [d['ID'] for d in deals]) ``` -------------------------------- ### Обернуть обращения в slow для снижения нагрузки Source: https://github.com/alexeyleshchenko/fast_bitrix24/blob/master/README.md Используйте контекстный менеджер slow, чтобы ограничить скорость запросов к Битриксу и избежать ошибок сервера при высокой нагрузке. ```python with bx.slow(): results = bx.call('crm.lead.add', tasks) ```