【发布时间】:2017-06-26 18:22:25
【问题描述】:
尝试使用 AJAX 对数据表进行分页。我创建了一个接受用户输入的 SQLAlchemy 查询,并从那里创建了一个包含每个查询结果的字典列表。我需要使我的数据 JSON 可序列化,并且我尝试使用 this JavaScript tool,但它说我的查询对象(models.py 中的变量“select”)不可序列化。我尝试解决这个问题并使用标题为“行”的字典列表,但我的每个查询都太大而无法存储在烧瓶“会话”对象中(如 views.py 中所示)。
我知道 SQLAlchemy 的分页功能,但我不确定这是否是对我的表实现分页功能的最佳方式。我很想用AJAX(sqlalchemy的分页功能和AJAX可以结合使用吗?),但是我是JS的初学者,不知道如何完成AJAX的实现。有什么帮助吗?
到目前为止,这是我的代码的细分。我认为不需要发布表模式,但请注意,我通过创建类并将自动加载设置为 True 来加载现有表。每个查询中都会出现日期时间对象,所以也许这就是查询对象不是 JSON 可序列化的原因?
models.py:
class Stations(Base):
__tablename__ = "stations"
__table_args__ = {'autoload':True}
class Metar(Base):
__tablename__ = "metar"
__table_args__ = {'autoload':True}
def loadSession(form):
clear_mappers()
metadata = MetaData()
metadata.reflect(engine, only=['metar', 'stations'])
stations = Table('stations', metadata, \
Column('stationID', Integer, \
ForeignKey("metar.stationID"), primary_key=True), \
autoload=True, autoload_with=engine, extend_existing=True)
mapper(Stations, stations)
metar = Table('metar', metadata, autoload=True, autoload_with=engine)
mapper(Metar, metar)
Session = sessionmaker(bind=engine)
connect = Session()
queries = []
#
# Code not pertinent to question
# takes user input query params and enters them into query
time_constraints = []
#
# Code not pertinent to question
# takes user input query params and enters them into query
# creates sqlalchemy query object
select = connect.query(Metar.stationID, Metar.ldatetime, Metar.temp, Metar.dew,
Metar.wspd, Metar.wdir, Metar.wgust, Metar.vrb,
Stations.id, Stations.name, Stations.state).\
join(Stations).\
filter(or_(*queries), and_(*time_constraints))
# creates list of dicts containing query response information
rows = []
for result in select:
rows.append(dict(zip(result.keys(), result)))
return rows, select
views.py
@app.route('/data_post', methods=['GET', 'POST'])
def data_post():
rows, select = loadSession(form=form)
session['rows'] = rows
return redirect(url_for('results'))
@app.route('/results', methods=['GET','POST'])
def results():
rows = session.get('rows', None)
return render_template('data_display.html', rows=rows)
data_display.html
<div class="data_display" id="ajax">
<table>
<tr>
<th>ID</th>
<th>ICAO ID</th>
<th>State</th>
<th>Station Name</th>
<th>Local Time</th>
<th>Temp</th>
<th>Dew Point</th>
<th>Wind Speed</th>
<th>Wind Direction</th>
<th>Wind Gust</th>
<th>Variable Wind</th>
</tr>
{% for row in rows %}
<tr>
<td>{{ row['stationID'] }}</td>
<td><a href="{{ url_for('stations', stationID = row['id']) }}">{{ row['id'] }}</td>
<td><a href="{{ url_for('state', state = row['state']) }}">{{ row['state'] }}</td>
<td>{{ row['name'] }}</td>
<td>{{ row['ldatetime'] }}</td>
<td>{{ row['temp'] }}</td>
<td>{{ row['dew'] }}</td>
<td>{{ row['wspd'] }}</td>
<td>{{ row['wdir'] }}</td>
<td>{{ row['wgust'] }}</td>
<td>{{ row['vrb'] }}</td>
</tr>
{% endfor %}
</table>
</div>
【问题讨论】:
标签: jquery python ajax flask flask-sqlalchemy