1
我使用的燒瓶中,SQLAlchemy的查詢的結果繪製的matplotlib數據被用來提取數據的列。我有一些工作代碼,但它不夠優雅而且效率低下。我希望能夠從一個單一的查詢中獲取數據的多個列中,我可以在matplotlib使用的一種形式。我是Python的新手(使用v3.4),而且我還沒有真正「獲得」它。目前我正在爲每一列數據查詢數據庫一次。如何從表單中的燒瓶中,SQLAlchemy的查詢,可與matplotlib
所有幫助感激地接受。
# views.py
import matplotlib.pyplot as plt
from .models import Sensor
def DrawChart():
# Draw a chart
x = Sensor.query.with_entities(Sensor.UnixTime).filter(Sensor.UnixTime >= config.startDateTime).filter(
Sensor.UnixTime <= config.endDateTime).all()
y1 = Sensor.query.with_entities(Sensor.SupplyVoltage).filter(Sensor.UnixTime >= config.startDateTime).filter(
Sensor.UnixTime <= config.endDateTime).all()
y2 = Sensor.query.with_entities(Sensor.TotalCurrent).filter(Sensor.UnixTime >= config.startDateTime).filter(
Sensor.UnixTime <= config.endDateTime).all()
# Draw the chart
fig, ax = plt.subplots()
ax.plot(x, y1, 'k--')
ax.plot(x, y2, 'ro')
# models.py
from . import db
db.Model.metadata.reflect(db.engine)
class Sensor(db.Model):
"""Sensor model links to sensor data table for displaying data and feeding MatPlotLib"""
__table__ = db.Model.metadata.tables['sensorReadings']
def __repr__(self):
return 'Sensor model'
# __INIT__.py
from flask import Flask
from flask_sslify import SSLify
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
import matplotlib
matplotlib.use('Agg') # Stops errors when maplotlob tries to use X-windows backend
app = Flask(__name__, instance_relative_config=True) # Use Flask instance folders to keep some settings out of GIT.
app.config.from_object('config') # Main config file
app.config.from_pyfile('config.py') # Instance config file
sslify = SSLify(app) # Force Flask to use SSL i.e. HTTPS
bcrypt = Bcrypt(app) # Initialize encryption for hashing passwords
db = SQLAlchemy(app) # Initialize SQLite database
感謝您有用的答案。我將執行錯誤處理。祝一切順利! – Martin