Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we use Bokeh curdoc() in django

I want to achieve live graph in django using bokeh. I tried many ways but nothing has worked out for me. I got a code which is working fine as normal bokeh serve but not working in django. can anyone help me in this? I got stuck almost a week. code is below:

import numpy as np
from bokeh.client.session import push_session
from bokeh.layouts import column
from bokeh.models import Button
from bokeh.palettes import RdYlBu3
from bokeh.plotting import figure, curdoc
import pandas as pd
import random
from bokeh.embed import components



# create a plot and style its properties
p = figure(x_axis_type="datetime", title="EUR USD", plot_width=1000)
p.grid.grid_line_alpha = 0
p.xaxis.axis_label = 'Date'
p.yaxis.axis_label = 'Price'
p.ygrid.band_fill_color = "olive"
p.ygrid.band_fill_alpha = 0.1

# p.border_fill_color = 'black'
# p.background_fill_color = 'black'
# p.outline_line_color = None
# p.grid.grid_line_color = None

# add a text renderer to out plot (no data yet)
r = p.line(x = [], y = [],  legend='close', color='navy')
s = p.triangle(x = [], y = [],  legend='sell', color='red' ,size=10 )
t = p.triangle(x = [], y = [],  legend='buy', color='green' ,size=10 )
# r = p.text(x=[], y=[], text=[], text_color=[], text_font_size="20pt",
#            text_baseline="middle", text_align="center")

i = 0

dr = r.data_source
ds = s.data_source
dt = t.data_source

# create a callback that will add a number in a random location
def callback():
    global i
    a=fxdata()[0]
    val = np.random.random()*70 + 15
    dr.data['x'].append(i)  #     np.datetime64(str(a[1]))
    dr.data['y'].append( val )  #     np.float(a[2])
    rm = random.randint(1,10)
    if rm <= 2:
        ds.data['x'].append(i)  # np.datetime64(str(a[1]))
        ds.data['y'].append(val)
    elif rm >=9 :
        dt.data['x'].append(i)  # np.datetime64(str(a[1]))
        dt.data['y'].append(val)
    else:
        pass
    # ds.data['text_color'].append(RdYlBu3[i%3])
    # ds.data['text'].append(str("MJ"))
    dr.trigger('data', dr.data, dr.data)
    ds.trigger('data', ds.data, ds.data)
    dt.trigger('data', dt.data, dt.data)
    i = i + 1

# add a button widget and configure with the call back
button = Button(label="Press Me")
# button.on_click(callback)



# put the button and plot in a layout and add to the document
curdoc().add_root(column(button, p))
curdoc().add_periodic_callback(callback, 1000)

I tried this simple live plotting using random number. The same thing i want in django. can anyone help me? Help will be appreciated.

like image 307
Sarath_Mj Avatar asked Nov 08 '22 09:11

Sarath_Mj


1 Answers

If you want to run a Bokeh server inside the same process as the Django app, i.e. you do not want to run a separate bokeh serve process and embed that in your Django app with server_document, then you will have to embed the Bokeh server as a library.

def modify_doc(doc):
    # set up app here, use doc.add_root(...)

def bk_worker():
    # Can't pass num_procs > 1 in this configuration. If you need to run multiple
    # processes, see e.g. flask_gunicorn_embed.py
    server = Server({'/bkapp': modify_doc}, io_loop=IOLoop(), allow_websocket_origin=["localhost:8000"])
    server.start()
    server.io_loop.start()

from threading import Thread
Thread(target=bk_worker).start()

Then you can get a script to embed the app in the usual way:

script = server_document('http://localhost:5006/bkapp')

and include that in your page template wherever the app should be embedded.

like image 62
bigreddot Avatar answered Nov 15 '22 05:11

bigreddot