Skipole WSGI generator.

Topics:

Introduction Getting Started Your Code skiadmin start_call submit_data end_call Exceptions PageData SectionData skicall Serving wsgi Code Examples

Development at GitHub:

github.com/bernie-skipole/skipole

Using Matplotlib to serve an inline svg chart

Ensure your virtual environment has:

pip install matplotlib numpy skipole

Create a directory, and move to it, then create a project "myproj", note the trailing space dot, for current directory.

python -m skilift myproj .

which creates the file myproj.py in your current directory.

Run the project and use skiadmin to add a paras.TagUnEscaped widget with name 'matptest' on the template page 4001.

Edit the start of your myproj.py file to include the imports:


from io import StringIO

from matplotlib.figure import Figure

import numpy as np

And edit the end_call function as shown here:


def end_call(page_ident, page_type, skicall):
    """This function is called prior to returning a page,
       it can also be used to return an optional session cookie string."""

    # The following code could have been set in a submit_data function called by a responder,
    # but in this simple case it is set here when the returned page is the template page
    # with ident number 4001
    if page_ident[1] == 4001:
        # this template page contains the TagUnEscaped widget which holds the inline svg figure created here

        # Generate the svg figure
        fig = Figure()
        ax = fig.subplots()
        # create a plot, this example from the matplotlib website
        x = np.linspace(0, 2, 100)
        ax.plot(x, x, label='linear')  # Plot some data on the axes.
        ax.plot(x, x**2, label='quadratic')  # Plot more data on the axes...
        ax.plot(x, x**3, label='cubic')  # ... and some more.
        ax.set_xlabel('x label')  # Add an x-label to the axes.
        ax.set_ylabel('y label')  # Add a y-label to the axes.
        ax.set_title("Simple Plot")  # Add a title to the axes.
        ax.legend()  # Add a legend.
        # Save it to a temporary string buffer.
        with StringIO() as figbuffer:
            fig.savefig(figbuffer, format="svg")
            # The figbuffer.getvalue() string contains the code however,the beginning of
            # the string contains xml information before the svg tag which we want to remove:
            figdata = '<svg' + figbuffer.getvalue().split('<svg')[1]

        # so figdata can now be set into a TagUnEscaped widget called matptest
        # this widget has been set in the template page with a 'div' tag - which will now
        # contain all the figdata code

        pd = PageData()
        pd['matptest', 'content'] = figdata
        skicall.update(pd)
    return

 

The code string produced in variable figdata is inserted into the 'matptest' widget, which serves the code without escapes, and hence the chart will be shown on the page.