From 5796f211c164c74da78ac5a28567b52af06e16ad Mon Sep 17 00:00:00 2001 From: Shawn Niederriter Date: Fri, 14 Apr 2017 17:17:23 +0000 Subject: [PATCH] Added detailed plotly example project --- examples/plotly_example/plotlyjs_example.py | 85 ++++++++++++++++++++ examples/plotly_example/requirements.txt | 5 ++ examples/plotly_example/templates/index.html | 0 3 files changed, 90 insertions(+) create mode 100644 examples/plotly_example/plotlyjs_example.py create mode 100644 examples/plotly_example/requirements.txt create mode 100644 examples/plotly_example/templates/index.html diff --git a/examples/plotly_example/plotlyjs_example.py b/examples/plotly_example/plotlyjs_example.py new file mode 100644 index 00000000..f536067c --- /dev/null +++ b/examples/plotly_example/plotlyjs_example.py @@ -0,0 +1,85 @@ +from sanic import Sanic + +from sanic_session import InMemorySessionInterface +from sanic_jinja2 import SanicJinja2 + +import json +import plotly + +import pandas as pd +import numpy as np + +app = Sanic(__name__) + +jinja = SanicJinja2(app) +session = InMemorySessionInterface(cookie_name=app.name, prefix=app.name) + +@app.middleware('request') +async def print_on_request(request): + print(request.headers) + await session.open(request) + +@app.middleware('response') +async def print_on_response(request, response): + await session.save(request, response) + + + +@app.route('/') +async def index(request): + rng = pd.date_range('1/1/2011', periods=7500, freq='H') + ts = pd.Series(np.random.randn(len(rng)), index=rng) + + graphs = [ + dict( + data=[ + dict( + x=[1, 2, 3], + y=[10, 20, 30], + type='scatter' + ), + ], + layout=dict( + title='first graph' + ) + ), + + dict( + data=[ + dict( + x=[1, 3, 5], + y=[10, 50, 30], + type='bar' + ), + ], + layout=dict( + title='second graph' + ) + ), + + dict( + data=[ + dict( + x=ts.index, # Can use the pandas data structures directly + y=ts + ) + ] + ) + ] + + # Add "ids" to each of the graphs to pass up to the client + # for templating + ids = ['graph-{}'.format(i) for i, _ in enumerate(graphs)] + + # Convert the figures to JSON + # PlotlyJSONEncoder appropriately converts pandas, datetime, etc + # objects to their JSON equivalents + graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder) + + return jinja.render('index.html', request, + ids=ids, + graphJSON=graphJSON) + + +if __name__ == '__main__': + app.run(host='0.0.0.0', port=8000, debug=True) \ No newline at end of file diff --git a/examples/plotly_example/requirements.txt b/examples/plotly_example/requirements.txt new file mode 100644 index 00000000..91875907 --- /dev/null +++ b/examples/plotly_example/requirements.txt @@ -0,0 +1,5 @@ +pandas==0.19.2 +plotly==2.0.7 +sanic==0.5.0 +sanic-jinja2==0.5.1 +sanic-session==0.1.3 \ No newline at end of file diff --git a/examples/plotly_example/templates/index.html b/examples/plotly_example/templates/index.html new file mode 100644 index 00000000..e69de29b