Async with condition – Python

I created a python script that brings some data back from various APIs for accountIds list provided to it.

One API is crucial for the result of other APIs, however while using the script I noticed there can be some API calls to that crucial API that can be avoided, hence I thought of using asyncio.Condition()

However, What I’m facing is that my condition seems not be to honoured and still the API is called.

Example:
Providing a list of 3 account. Crucial API is called concurrently for them, but I need them to wait for a specific check to happen (if account is present in a dict then get the data from that dict) – that dict starts empty and data flows to it only if it is empty. I need each task to wait for the previous task to finish and based on its result it whether gets the data from the dict or call the API
so if first account is a PAYER, then get its children and update the dict. now the next task with other accounts needs to check if their account is in the dict and if not, they can proceed with the API call, other wise, they need to use the data form the dict.

my code is:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>self.initiated_data_dict = {
"Roles": {},
"Details": {},
"Children": {},
"PayersOfChildren": {}
}
self.in_progress = {}
self.checker = []
def find_role(self, account_id):
"""Determine the role of the account from the initiated data dictionary."""
logger.debug(f'Starting find_role for account_id: {account_id}')
logger.debug(f'Current initiated_data_dict: {json.dumps(self.initiated_data_dict, indent=4)}')
if account_id in self.initiated_data_dict["Roles"]:
logger.debug(f'Role found in find_role_ROLES: {account_id}')
return self.initiated_data_dict["Roles"][account_id]
if self.initiated_data_dict["Children"]:
if account_id in self.initiated_data_dict["Children"].keys():
logger.debug(f'Role found in find_role_CHILDREN_KEYS: {account_id}')
return "PAYER"
for children_list in self.initiated_data_dict["Children"].values():
if any(child.get("accountId") == account_id for child in children_list):
logger.debug(f'Role found in find_role_CHILDREN_VALUES: {account_id}')
return "LINKED"
if self.initiated_data_dict["PayersOfChildren"]:
if account_id in self.initiated_data_dict["PayersOfChildren"]:
logger.debug(f'Role found in find_role_PayersOfChildren_KEYS: {account_id}')
return "LINKED"
if account_id in self.initiated_data_dict["PayersOfChildren"].values():
logger.debug(f'Role found in find_role_PayersOfChildren_VALUES: {account_id}')
return "PAYER"
logger.debug(f'Role not found: {account_id}: dict_: {json.dumps(self.initiated_data_dict, indent=4)}')
return None
async def initiate(self, accountId, condition):
role_result = None
children_result = None
async with condition:
# Wait until the role for `accountId` is not being processed by another task
while accountId in self.in_progress:
await condition.wait()
if accountId not in self.initiated_data_dict["Roles"] and accountId not in self.in_progress:
self.checker.append(accountId)
self.in_progress[accountId] = True
# Notify other tasks that this task is now in progress
condition.notify_all()
# Determine the role of `accountId` using `find_role`
role_result = self.find_role(accountId)
if role_result is None:
# If `accountId` was not found, get the role and update data
role_result = await model.get_role(accountId)
logger.debug(f"API Called for {accountId}: Role is: {role_result}")
self.initiated_data_dict["Roles"][accountId] = role_result
# logger.debug(f"initiated_data_dict after ROLE API CALL {json.dumps(self.initiated_data_dict, indent=4)}")
if role_result == "PAYER":
children_result = await model.get_children(accountId)
self.initiated_data_dict["Children"][accountId] = children_result
# logger.debug(f"initiated_data_dict after CHILDREN API CALL {json.dumps(self.initiated_data_dict, indent=4)}")
self.initiated_data_dict["Roles"][accountId] = role_result
async with condition:
# Safely remove the key from self.in_progress if it exists
self.in_progress.pop(accountId, None)
# Notify all tasks that processing is complete
condition.notify_all()
return role_result, children_result
</code>
<code>self.initiated_data_dict = { "Roles": {}, "Details": {}, "Children": {}, "PayersOfChildren": {} } self.in_progress = {} self.checker = [] def find_role(self, account_id): """Determine the role of the account from the initiated data dictionary.""" logger.debug(f'Starting find_role for account_id: {account_id}') logger.debug(f'Current initiated_data_dict: {json.dumps(self.initiated_data_dict, indent=4)}') if account_id in self.initiated_data_dict["Roles"]: logger.debug(f'Role found in find_role_ROLES: {account_id}') return self.initiated_data_dict["Roles"][account_id] if self.initiated_data_dict["Children"]: if account_id in self.initiated_data_dict["Children"].keys(): logger.debug(f'Role found in find_role_CHILDREN_KEYS: {account_id}') return "PAYER" for children_list in self.initiated_data_dict["Children"].values(): if any(child.get("accountId") == account_id for child in children_list): logger.debug(f'Role found in find_role_CHILDREN_VALUES: {account_id}') return "LINKED" if self.initiated_data_dict["PayersOfChildren"]: if account_id in self.initiated_data_dict["PayersOfChildren"]: logger.debug(f'Role found in find_role_PayersOfChildren_KEYS: {account_id}') return "LINKED" if account_id in self.initiated_data_dict["PayersOfChildren"].values(): logger.debug(f'Role found in find_role_PayersOfChildren_VALUES: {account_id}') return "PAYER" logger.debug(f'Role not found: {account_id}: dict_: {json.dumps(self.initiated_data_dict, indent=4)}') return None async def initiate(self, accountId, condition): role_result = None children_result = None async with condition: # Wait until the role for `accountId` is not being processed by another task while accountId in self.in_progress: await condition.wait() if accountId not in self.initiated_data_dict["Roles"] and accountId not in self.in_progress: self.checker.append(accountId) self.in_progress[accountId] = True # Notify other tasks that this task is now in progress condition.notify_all() # Determine the role of `accountId` using `find_role` role_result = self.find_role(accountId) if role_result is None: # If `accountId` was not found, get the role and update data role_result = await model.get_role(accountId) logger.debug(f"API Called for {accountId}: Role is: {role_result}") self.initiated_data_dict["Roles"][accountId] = role_result # logger.debug(f"initiated_data_dict after ROLE API CALL {json.dumps(self.initiated_data_dict, indent=4)}") if role_result == "PAYER": children_result = await model.get_children(accountId) self.initiated_data_dict["Children"][accountId] = children_result # logger.debug(f"initiated_data_dict after CHILDREN API CALL {json.dumps(self.initiated_data_dict, indent=4)}") self.initiated_data_dict["Roles"][accountId] = role_result async with condition: # Safely remove the key from self.in_progress if it exists self.in_progress.pop(accountId, None) # Notify all tasks that processing is complete condition.notify_all() return role_result, children_result </code>
self.initiated_data_dict = {
            "Roles": {},
            "Details": {},
            "Children": {},
            "PayersOfChildren": {}
        }
self.in_progress = {}
self.checker = []


def find_role(self, account_id):
        """Determine the role of the account from the initiated data dictionary."""
        logger.debug(f'Starting find_role for account_id: {account_id}')
        logger.debug(f'Current initiated_data_dict: {json.dumps(self.initiated_data_dict, indent=4)}')

        if account_id in self.initiated_data_dict["Roles"]:
            logger.debug(f'Role found in find_role_ROLES: {account_id}')
            return self.initiated_data_dict["Roles"][account_id]

        if self.initiated_data_dict["Children"]:
            if account_id in self.initiated_data_dict["Children"].keys():
                logger.debug(f'Role found in find_role_CHILDREN_KEYS: {account_id}')
                return "PAYER"
            for children_list in self.initiated_data_dict["Children"].values():
                if any(child.get("accountId") == account_id for child in children_list):
                    logger.debug(f'Role found in find_role_CHILDREN_VALUES: {account_id}')
                    return "LINKED"

        if self.initiated_data_dict["PayersOfChildren"]:
            if account_id in self.initiated_data_dict["PayersOfChildren"]:
                logger.debug(f'Role found in find_role_PayersOfChildren_KEYS: {account_id}')
                return "LINKED"
            
            if account_id in self.initiated_data_dict["PayersOfChildren"].values():
                logger.debug(f'Role found in find_role_PayersOfChildren_VALUES: {account_id}')
                return "PAYER"

        logger.debug(f'Role not found: {account_id}: dict_: {json.dumps(self.initiated_data_dict, indent=4)}')
        return None



async def initiate(self, accountId, condition):
        role_result = None
        children_result = None
        async with condition:
            # Wait until the role for `accountId` is not being processed by another task
            while accountId in self.in_progress:
                await condition.wait()
            if accountId not in self.initiated_data_dict["Roles"] and accountId not in self.in_progress:
                self.checker.append(accountId)
                self.in_progress[accountId] = True
                # Notify other tasks that this task is now in progress
                condition.notify_all()

        # Determine the role of `accountId` using `find_role`
        role_result = self.find_role(accountId)

        if role_result is None:
            # If `accountId` was not found, get the role and update data
            role_result = await model.get_role(accountId)
            logger.debug(f"API Called for {accountId}: Role is: {role_result}")
            self.initiated_data_dict["Roles"][accountId] = role_result
            # logger.debug(f"initiated_data_dict after ROLE API CALL {json.dumps(self.initiated_data_dict, indent=4)}")
            
            if role_result == "PAYER":
                children_result = await model.get_children(accountId)
                self.initiated_data_dict["Children"][accountId] = children_result
                # logger.debug(f"initiated_data_dict after CHILDREN API CALL {json.dumps(self.initiated_data_dict, indent=4)}")
            
        self.initiated_data_dict["Roles"][accountId] = role_result

        async with condition:
            # Safely remove the key from self.in_progress if it exists
            self.in_progress.pop(accountId, None)
            # Notify all tasks that processing is complete
            condition.notify_all()

        return role_result, children_result

I’m not able to figure out what am I doing wrong that is causing the API to be called for all accounts.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật