Created
April 23, 2018 20:27
-
-
Save benman1/08b855e1d40f57deab15792075f390ed to your computer and use it in GitHub Desktop.
bokeh server with data update and plot endpoints
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from bokeh.embed import components | |
from bokeh.core.templates import FILE | |
from bokeh.models import ColumnDataSource, DataRange1d, Plot | |
from bokeh.models.glyphs import Line | |
from bokeh.resources import INLINE | |
from bokeh.util.string import encode_utf8 | |
from flask import Flask, request, jsonify | |
import numpy as np | |
""" | |
Very basic flask server to display and update a bokeh line plot. | |
This could be extended for more plots or changed for live updates to plots. | |
Example update: | |
>> curl -X POST -d '{"x": [0, 1, 2], "y": [2, 1, 0]}' \ | |
http://localhost:5000/update --header "Content-Type:application/json" | |
""" | |
app = Flask(__name__) | |
data = dict() | |
def init(): | |
N = 30 | |
data['x'] = np.linspace(-2, 2, N) | |
data['y'] = data['x']**2 | |
@app.route("/update", methods=['POST']) | |
def update_data(): | |
data_read = False | |
req_data = request.get_json() | |
if req_data is not None: | |
data_read = True | |
data['x'] = req_data['x'] | |
data['y'] = req_data['y'] | |
return jsonify({ | |
'OK': True, | |
'updated': data_read, | |
'x': str(data['x']), | |
'y': str(data['y']) | |
}) | |
@app.route("/", methods=['GET']) | |
def line_plot(): | |
source = ColumnDataSource(dict(x=data['x'], y=data['y'])) | |
xdr = DataRange1d() | |
ydr = DataRange1d() | |
plot = Plot( | |
title=None, x_range=xdr, y_range=ydr, | |
plot_width=300, plot_height=300, | |
h_symmetry=False, v_symmetry=False, min_border=0, | |
toolbar_location=None | |
) | |
glyph = Line( | |
x="x", y="y", line_color="#f46d43", line_width=6, line_alpha=0.6 | |
) | |
plot.add_glyph(source, glyph) | |
script, div = components(plot, INLINE) | |
html = FILE.render( | |
plot_script=script, | |
plot_div=div, | |
bokeh_js=INLINE.render_js(), | |
bokeh_css=INLINE.render_css(), | |
) | |
return encode_utf8(html) | |
init() | |
app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment