Create Flow

An empty Flow can be created via:

  1. from jina import Flow
  2. f = Flow()

Use a Flow

To use f, always open it as a context manager, just like you open a file. This is considered the best practice in Jina:

  1. with f:
  2. ...

Note

Flow follows a lazy construction pattern: it won’t actually run until you use with to open it.

Warning

Once a Flow is open via with, you can send data requests to it. However, you cannot change its construction via .add() any more until it leaves the with context.

Important

The context exits when its inner code is finished. A Flow’s context without inner code will immediately exit. To prevent that, use .block() to suspend the current process.

  1. with f:
  2. f.block() # block the current process

To terminate a blocked Flow, one can send use threading.Event or multiprocessing.Event to send the terminate signal. The following example terminates a Flow from another process.

  1. import multiprocessing
  2. import time
  3. from jina import Flow
  4. ev = multiprocessing.Event()
  5. def close_after_5s():
  6. time.sleep(5)
  7. ev.set()
  8. f = Flow().add()
  9. with f:
  10. t = multiprocessing.Process(target=close_after_5s)
  11. t.start()
  12. f.block(stop_event=ev)

Visualize a Flow

  1. from jina import Flow
  2. f = Flow().add().plot('f.svg')

../../../_images/empty-flow.svg

In Jupyter Lab/Notebook, the Flow object is rendered automatically without needing to call plot().