James Ashby
07/22/2024, 4:56 PMMarvin
07/22/2024, 4:56 PMget_run_context
function from Prefect. Here's a concise example:
python
from prefect import flow, get_run_context
@flow
def my_workflow():
# Check if we are in a running flow
try:
context = get_run_context()
if context.flow_run:
print("This code is running within a Prefect Flow!")
else:
print("Not running in a Prefect Flow.")
except RuntimeError:
print("Not running in a Prefect Flow.")
if __name__ == "__main__":
my_workflow()
This code will output an appropriate message indicating whether the code is currently running within a flow.James Ashby
07/22/2024, 5:19 PM>>> from prefect import get_run_context
exit()Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'get_run_context' from 'prefect' (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/prefect/__init__.py)
Marvin
07/22/2024, 5:20 PMget_run_context
from prefect.context
. Here's the corrected example:
python
from prefect import flow
from prefect.context import get_run_context
@flow
def my_workflow():
# Check if we are in a running flow
try:
context = get_run_context()
if context:
print("This code is running within a Prefect Flow!")
else:
print("Not running in a Prefect Flow.")
except RuntimeError:
print("Not running in a Prefect Flow.")
if __name__ == "__main__":
my_workflow()
This should correctly check if the current code is running within a Prefect Flow.
For more details, you can refer to the documentation:
https://docs.prefect.io/latest/guides/runtime-context/