Blogs

How-To: Loading YAML

By Erdem posted 08-06-2015 05:24

  

Overview

Explains the use of loadyaml() to create new Table/View widgets.

 

Discussion

 

Tables and Views are generally defined using the YAML syntax, as described in other topic pages.  YAML files are typically loaded as part of a Python module so that they can be natively imported. 

An example of this is the EthPortTable.  The EthPortTable widget is defined by the YAML file "ethport.yml".  The definition is imported using a short Python module, "ethport.py", that looks like this:

 

1 """
2 Pythonifier for EthPort Table/View
3 """
4 from ..factory import loadyaml
5 from os.path import splitext
6 _YAML_ = splitext(__file__)[0] + '.yml'
7 globals().update(loadyaml(_YAML_))

 

The above "pythonifier" uses the Junos PyEZ loadyaml() routine to load the YAML file and then import it into the global namespace of the module (line 7).  In doing this, the user simply has do to the following to include the EthPortTable:

 

1 >>> from jnpr.junos.op.ethport import *
2 >>> dir()
3 ['EthPortTable', 'EthPortView', '__builtins__', <snip>]

 

You can manually load Table/View definitions using loadyaml() as well, with or without the use of the "pythonifier" wrappers.

 

Example

 

Let's say that you have a YAML file called "myfoo.yml" that defines a table called "MyFooTable" and a view called "MyFooView".  Here is the process to load (factory) the widgets:

 

1 >>> from jnpr.junos.factory import loadyaml
2 >>>
3 >>> mydefs = loadyaml('myfoo.yml')
4 >>> pprint(mydefs)
5 {'MyFooTable': <class 'jnpr.junos.factory.OpTable.MyFooTable'>,
6  'MyFooView': <class 'jnpr.junos.factory.View.MyFooView'>}


The mydefs variable acts like as a container or namespace for the widgets.  You could import the widgets directly into the global namespace by doing the following:

 

1 >>> globals().update(mydefs)
2 >>>
3 >>> table = MyFooTable(dev)
4 >>> table.get()


Alternatively, you could use the widget definitions from the mydefs container, and avoid cluttering your global namespace:

 

1 >>> table = mydefs['MyFooTable'](dev)
2 >>> table.get()

 


#junospyez
#yaml
#How-To
#overview