Flask Application

You can use pyvista in to make a flask application to display static plots. See the following example as well as the demo at Flask Example.

For dynamic examples, it’s recommended to use Jupyter Notebooks. See our documentation regarding this at Jupyter Notebook Plotting.

../_images/flask_example.png

Example Flask Webpage

Python Application app.py

"""Simple flask app to display static images generated from pyvista.

Expected paths:
flask_example
└── app.py
    templates
    └── index.html

"""
import os
import pyvista
from flask import Flask, render_template, request


static_image_path = os.path.join('static', 'images')
if not os.path.isdir(static_image_path):
    os.makedirs(static_image_path)


app = Flask(__name__)

@app.route("/")
def index():
    return render_template('index.html')


@app.route("/getimage")
def get_img():
    """Generate a screenshot of a simple pyvista mesh.

    Returns
    -------
    str
        Local path within the static directory of the image.

    """
    # get the user selected mesh option
    meshtype = request.args.get('meshtype')
    if meshtype == 'Sphere':
        mesh = pyvista.Sphere()
    elif meshtype == 'Cube':
        mesh = pyvista.Cube()
    elif meshtype == 'Bohemian Dome':
        mesh = pyvista.ParametricBohemianDome()
    elif meshtype == 'Cylinder':
        mesh = pyvista.Cylinder()
    else:
        # invalid entry
        raise ValueError('Invalid Option')

    # generate screenshot
    filename = f'{meshtype}.png'
    filepath = os.path.join(static_image_path, filename)
    mesh.plot(off_screen=True,
              window_size=(300, 300),
              screenshot=filepath)
    return os.path.join('images', filename)


if __name__ == '__main__':
    app.run()

Ajax Template index.html

This template should be within the templates directory in the same path as app.py.

This template returns the meshtype parameter back to the get_img method in the flask app, which is used to select the type of mesh to be plotted.

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  </head>
   <body>

     <select style="background-color: #ffffa0" name="country", id="meshtype" onchange="getState(this.value)">
       <option>Select Mesh Type</option>
       <option>Sphere</option>
       <option>Cube</option>
       <option>Bohemian Dome</option>
       <option>Cylinder</option>
     </select>

     <button type='button' id ='retrieve'>Plot</button>
     <img src="" id="myimg" />
   </body>
  <script>
    $(document).ready(function() {
       $('#retrieve').click(function(){
           $.ajax({
           url: "{{ url_for ('get_img') }}",
           type: "GET",
           data: { 
               meshtype:  $('#meshtype option:selected').val()
           },
           success: function(response) {
               $("#myimg").attr('src', '/static/' + response);
          },
          error: function(xhr) {
              alert("Please select a mesh type from the drop down menu.");
         }
         });
       });
    });
  </script>
</html>