Show HTML
For interactive visualizations using Plotly, it is recommended to use the
dedicated PlotlyView
.
This guide explains how to add a WebView
to an editor. This could for instance be used to
incorporate interactive visualizations or present other dynamic or static HTML (web)
content:
Implementation
Example of how an interactive visualization in a web view could look like (source: plot.ly)
There are 3 ways to pass the HTML content to a WebResult
:
- From a URL
- From a static HTML file
- From a dynamic HTML content
From a URL
You can point to a live URL and use that HTML page:
from viktor import ViktorController
from viktor.views import WebResult
from viktor.views import WebView
class Controller(ViktorController):
...
@WebView('Python wiki', duration_guess=1)
def get_web_view(self, params, **kwargs):
return WebResult(url='https://en.wikipedia.org/wiki/Python_(programming_language)')
From a static HTML file
If the HTML page is always the same (it is not necessary to generate it on every call), use the from_path
method to
construct a WebResult
:
from pathlib import Path
from viktor import ViktorController
from viktor.views import WebResult
from viktor.views import WebView
class Controller(ViktorController):
...
@WebView('Hello page', duration_guess=1)
def get_web_view(self, params, **kwargs):
static_html_path = Path(__file__).parent / 'page.html'
return WebResult.from_path(static_html_path)
page.html
(in this example next to controller.py):
<html>
Hello Everyone!
</html>
From dynamic HTML content
If the HTML page is dependent on some input (so needs to be generated on every call), use the html
argument in
WebResult
:
from io import StringIO
from viktor import ViktorController
from viktor.views import WebResult
from viktor.views import WebView
class Controller(ViktorController):
...
@WebView('Hello page', duration_guess=1)
def get_web_view(self, params, **kwargs):
name = 'John Doe'
html_text = f'<html>Hello {name}</html>'
return WebResult(html=html_text)
A web view can be combined with a data view using a
WebAndDataView
Interactive visualizations
A very useful application of the web view is for interactive visualizations (for instance maps/graphs). The following Python libraries offer the functionality to export interactive visualizations as an HTML page:
Testing
mock_View
decorator for easier testing of view methods
Methods decorated with @WebView
or @WebAndDataView
need to be
mocked within the context of (automated) testing.
import unittest
from viktor.testing import mock_View
from app.my_entity_type.controller import MyEntityTypeController
class TestMyEntityTypeController(unittest.TestCase):
@mock_View(MyEntityTypeController)
def test_web_view(self):
params = ...
result = MyEntityTypeController().web_view(params=params)
self.assertEqual(result.html, ...)