问题
I would like to make use of a javascript library (specifically this one) in my Bokeh javascript callback. How can I specify importing of this javascript library such that the library is accessible from Bokeh's js callback functions?
The examples at:
https://docs.bokeh.org/en/latest/docs/user_guide/extensions.html
mainly talk about creating a custom Bokeh Model. I am not particularly interested in creating a new Model, just want to use the library functions in a callback to modify the data that is plotted.
回答1:
Server app:
You can create a Bokeh server directory structure.
- create a directory called myapp
- name your Python script main.py and put it there
- create a subdirectory there called templates
- create index.html, main.js and optional styles.css files and put them in templates subdirectory
- open terminal, navigate to directory one level higher than
myapp
directory and start your app with this command:bokeh serve --show myapp
The following example works for Bokeh v1.0.4.
Directory structure:
myapp
|
+---main.py
+---templates
+---index.html
+---main.js
+---styles.css
main.py
from bokeh.plotting import curdoc
from bokeh.models import Button, CustomJS
button = Button(label = 'Click Me')
button.callback = CustomJS(code = """ alert($) """)
curdoc().add_root(button)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<meta charset="utf-8">
{{ bokeh_css }}
{{ bokeh_js }}
<style>
{% include 'styles.css' %}
</style>
</head>
<body>
<script>
{% include 'main.js' %}
</script>
{{ plot_div|indent(8) }}
{{ plot_script|indent(8) }}
</body>
</html>
Please note that this way you can include local, but also remote JS libraries or style sheets.
main.js
$(document).ready(function() {
alert('jQuery succesfully loaded !')
});
styles.css
body { background: #111122; }
Standalone HTML app:
from bokeh.io import save
from bokeh.models import Slider
from bokeh.util.browser import view
template = """
{% block postamble %}
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function() {
var slider = Bokeh.documents[0].get_model_by_name('my_slider')
alert('slider value: ' + slider.value)
});
</script>
{% endblock %}
"""
slider = Slider(start=0, end=10, value=5, name='my_slider')
save(slider, template=template)
view("external_js.html")
来源:https://stackoverflow.com/questions/54502065/how-to-import-external-javascript-library-into-bokeh-generated-html