(Cloud) I need to programmatically delete a lot of...
# prefect-cloud
k
(Cloud) I need to programmatically delete a lot of Pending flows. Ideally I would use the Python SDK or Rest API directly but the client method delete_flow_run is unable to delete flows in a Pending state.
raise UnfinishedRun(
prefect.exceptions.UnfinishedRun: Run is in PENDING state, its result is not available.)
Is this intended? Is there another way of cancelling or deleting Pending flowruns without using the UI
1
j
hey, using the client to delete flows runs should be totally doable. Could you share your script?
Something like this should work to delete flow runs programmatically in a
PENDING
state
Copy code
import asyncio
from prefect import get_client
from prefect.client.schemas.filters import FlowRunFilter, FlowRunFilterState, FlowRunFilterStateType
from prefect.states import StateType


async def delete_flow_runs():
    async with get_client() as client:
        limit = 50
        while True:
            flow_runs = await client.read_flow_runs(
                limit=limit,
                flow_run_filter=FlowRunFilter(
                    state=FlowRunFilterState(
                        type=FlowRunFilterStateType(
                            any_=[StateType.PENDING]
                        )
                    )
                )
            )
            print(f"Deleting {len(flow_runs)} flow runs")
            if not flow_runs:
                break

            for flow_run in flow_runs:
                print(f"Deleting flow run {flow_run.id}")
                await client.delete_flow_run(flow_run.id)


if __name__ == '__main__':
    asyncio.run(delete_flow_runs())
k
Thanks Jake - your example is working. I'll adjust mine accordingly 🙏
🙌 1