Anybody have a snippet that sends a command to the...
# ask-community
d
Anybody have a snippet that sends a command to the server to run a deployment? Context: I have a flow that I want to run when another flow’s state is completed. Actually running the flow in the on_completed function issues an error (I think related to it being run in a worker thread?), so I need to command the server to queue it.
Solution for any interested
Copy code
from prefect import Flow
from prefect.cli.deployment import get_deployment
from prefect.client.orchestration import get_client
from prefect.engine import FlowRun
from prefect.server.schemas.responses import DeploymentResponse
from prefect.states import Scheduled, State

async def trigger_flow_run_on_state(flow: Flow, flow_run: FlowRun, state: State):
    """Triggers a deployment to run via Prefect `on_completion`, `on_failure`, or `on_crashed`."""
    # Get the client to communicate with the Prefect server
    async with get_client() as client:
        # Get the deployment to run.
        # TODO Update the {flow.name} and {deployment.name} to match your deployment.
        deployment: DeploymentResponse = await get_deployment(
            client, name="{flow.name}/{deployment.name}", deployment_id=None
        )

        # Submits the deployment to be run immediately.
        # Returns the FlowRun object.
        hooked_flow_run: FlowRun = await client.create_flow_run_from_deployment(
            deployment.id,
            state=Scheduled(),
        )