我正在尝试使用以下代码查询和获取数据库的最后一行:
from flask import Flask, render_template, redirect, url_for
from flask_bootstrap import Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import InputRequired, Email, Length
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
import json
app = Flask(__name__)
app.config['SECRET_KEY'] = 'removed'
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+mysqlconnector://{username}:{password}@{hostname}/{databasename}".format(
username="removed",
password="removed",
hostname="removed",
databasename="removed",
) #used to use sqlite here so potential for errors...
app.config["SQLALCHEMY_POOL_RECYCLE"] = 299 #do i need this line and below line???
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
class temperaturelog(db.Model):
TemperatureID = db.Column(db.Integer, primary_key=True)
Temperature = db.Column(db.Float(5))
dTime = db.Column(db.DateTime) #check the actual data types here
def __init__(self, TemperatureID, Temperature, dTime):
self.TemperatureID = TemperatureID
self.Temperature = Temperature
self.dTime = dTime
def __repr__(self):
return '%r' % self.Temperature
def getTemperatureData():
#need to convert this query into sqlalchemy queries "SELECT * FROM readings ORDER BY ID DESC LIMIT 1";
#need to connect/use the right table below
#data = jsonify(temperaturelog.query.order_by(temperaturelog.dTime.desc()).first())
datalist = {}
data = temperaturelog.query.order_by(temperaturelog.TemperatureID.desc()).first()
data = data.Temperature
datalist["temperature"] = data
datalist["datetime"] = "12-12-12 23-23-23"
datalist = json.dumps(datalist)
return datalist
这里我连接到一个在线数据库(我使用pythonanywhere来托管这一切)我需要数据库中的最后一行数据我相信通常的SQL命令是:
"SELECT * FROM readings ORDER BY ID DESC LIMIT 1";
当我使用下面的代码尝试检索dTime值以进行进一步处理时,它会抛出错误对象' float'没有属性.dTime,因此我的查询只是返回温度,如何让查询返回整个最后一行,以便我可以使用.Temperature和.dTime来访问特定值?
data2 = data.dTime
datalist["datetime"] = data2
答案 0 :(得分:3)
在getTemperatureData()
中,您首先使用data
变量存储查询结果集:
data = temperaturelog.query.order_by(temperaturelog.TemperatureID.desc()).first()
在下一行中,用温度覆盖data
(可能是浮点数):
data = data.Temperature
因此,下次尝试使用data
时,它包含一个浮点而不是结果集。
例如,将第二行中的变量重命名为data_temperature
。