Это код Flask (пример кода биткойна в реальном времени). pusher.trigger отправляет данные в канал Pusher. Событие «data-updated» также отображается на панели инструментов Pusher. Но я не могу увидеть график на моей странице HTML.
# ./app.py
from flask import Flask, render_template
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from pusher import Pusher
import requests, json, atexit, time, plotly, plotly.graph_objs as go
# create flask app
app = Flask(__name__)
# configure pusher object
pusher = Pusher(
app_id="<Hidden>",
key="<Hidden>",
secret="<Hidden>",
cluster="<Hidden>",
ssl=True
)
# define variables for data retrieval
times = []
currencies = ["BTC"]
prices = {"BTC": []}
@app.route("/")
def index():
return render_template("index.html")
def retrieve_data():
# create dictionary for saving current prices
current_prices = {}
for currency in currencies:
current_prices[currency] = []
# append new time to list of times
times.append(time.strftime('%H:%M:%S'))
# make request to API and get response as object
api_url = "https://min-api.cryptocompare.com/data/pricemulti?fsyms={}&tsyms=USD".format(",".join(currencies))
response = json.loads(requests.get(api_url).content)
# append new price to list of prices for graph
# and set current price for bar chart
for currency in currencies:
price = response[currency]['USD']
current_prices[currency] = price
prices[currency].append(price)
# create an array of traces for graph data
graph_data = [go.Scatter(
x=times,
y=prices.get(currency),
name="{} Prices".format(currency)
) for currency in currencies]
# create an array of traces for bar chart data
bar_chart_data = [go.Bar(
x=currencies,
y=list(current_prices.values())
)]
data = {
'graph': json.dumps(list(graph_data), cls=plotly.utils.PlotlyJSONEncoder),
'bar_chart': json.dumps(list(bar_chart_data), cls=plotly.utils.PlotlyJSONEncoder)
}
# trigger event
pusher.trigger("crypto", "data-updated", data)
# create schedule for retrieving prices
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(
func=retrieve_data,
trigger=IntervalTrigger(seconds=10),
id='prices_retrieval_job',
name='Retrieve prices every 10 seconds',
replace_existing=True)
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
# run Flask app
app.run(debug=True, use_reloader=False)
Код JavaScript связывает событие «data-updated» с функцией Plotly.newPlot для перезаписи предыдущего графика. Но я не могу получить график на моей веб-странице. Заранее спасибо.
<!-- ./templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CryptoLiveChart!</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/css/bulma.min.css">
<style>
.chart {
height: 800px;
}
</style>
</head>
<body>
<section class="section">
<div class="container">
<h1 class="title">Welcome to <strong>Crypto</strong>LiveChart!</h1>
<p class="subtitle">View live prices for <strong>Bitcoin</strong> and <strong>Ethereum</strong> in real time!</p>
<hr>
<div class="columns">
<div class="column">
<h5 class="title is-6">Prices (in USD)</h5>
<div id='price_chart' class="chart">
Graph
</div>
</div>
<div class="column">
<h5 class="title is-6">Market Cap</h5>
<div id='market_cap_chart' class="chart">
Bar Chart
</div>
</div>
</div>
</div>
</section>
<!-- D3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<!-- Plotly.js -->
<script src="https://d14fo0winaifog.cloudfront.net/plotly-basic.js"></script>
<!-- import Pusher-js library -->
<script src="https://js.pusher.com/4.1/pusher.min.js"></script>
<script type="text/javascript">
// connect to Pusher
const pusher = new Pusher("<Hidden>", {
cluster: "<Hidden>", // gotten from Pusher app dashboard
encrypted: true // optional
});
// subscribe to crypto channel
const channel = pusher.subscribe('crypto')
// listen for relevant events
channel.bind('data-updated', data => {
const graph = JSON.parse(data.graph);
Plotly.newPlot('price_chart', graph);
const bar_chart = JSON.parse(data.bar_chart);
Plotly.newPlot('market_cap_chart', bar_chart);
});
</script>
</body>
</html>