Reputation: 5697
I'm working on DataTables table to display large table from mySQL using Flask-SQLAlchemy. I have this flask code
from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secretkey'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://admin:[email protected]/test1'
db = SQLAlchemy(app)
class table1(db.Model):
__tablename__ = 'table1'
id = db.Column('id', db.Integer, primary_key=True)
first = db.Column('firstname', db.String(2))
last = db.Column('lastname', db.String(2))
def __init__(self, first, last):
self.first = first
self.last = last
pass
@property
def serialize(self):
return {
'id': self.id,
'first': self.first,
'last': self.last
}
tick = table1.query.all()
data=[i.serialize for i in tick]
# I HAVE TRIED THIS ROUTES WITH DIFFERENT APPROACH, BUT NONE WORKED FOR ME
@app.route('/tickets')
def get_tickets():
return jsonify(data)
@app.route('/users')
def get_users():
return jsonify(myData=[i.serialize for i in tick])
@app.route('/data')
def get_data():
return render_template('data.html',data=jsonify(data))
@app.route("/api/result")
def result_json():
data=dict(data=[i.serialize for i in tick])
return render_template('data.html', data=data)
It sends this valid JSON to my html:
[
{'id': 1, 'last': 'Spelec', 'first': 'Anton'},
{'id': 2, 'last': 'Pilcher', 'first': 'Rosamunde'},
{'id': 3, 'last': 'Burian', 'first': 'Vlasta'}
]
The problem is, that I need to have this code within {"data": ... }. Is it possible to add it to JSON in flask?
When I use return jsonify(data=[i.serialize for i in tick])
instead of return render_template('data.html', data=data)
, I get as a result
{"data":
[
{"first":"Anton","id":1,"last":"Spelec"},
{"first":"Rosamunde","id":2,"last":"Pilcher"},
{"first":"Vlasta","id":3,"last":"Burian"}
]
}
but without render_template the html page isn't displayed. Thank you for any advice.
Upvotes: 0
Views: 1953
Reputation: 38962
Make a dictionary with data
key e.g.
# Using dict function syntax
data=dict(data=[i.serialize for i in tick])
# Using dictional literal syntax
data={'data': [i.serialize for i in tick]}
Then pass data
as a context argument in render_template
...
return render_template('data.html', data=data)
This way data is serialised similar to the JSON you want as a result.
Upvotes: 1