Flask / Python修改JSON输出

时间:2018-08-30 17:36:17

标签: python json flask

我正在使用Flask-SQLAlchemy处理DataTables表以显示来自mySQL的大表。我有这个烧瓶代码

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:pass@10.10.99.11/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)

它将此有效JSON发送到我的html:

[
  {'id': 1, 'last': 'Spelec', 'first': 'Anton'}, 
  {'id': 2, 'last': 'Pilcher', 'first': 'Rosamunde'}, 
  {'id': 3, 'last': 'Burian', 'first': 'Vlasta'}
]

问题是,我需要将此代码包含在{“ data”:...}中。是否可以将其添加到flask的JSON中?

当我使用return jsonify(data=[i.serialize for i in tick])而不是return render_template('data.html', data=data)时,我得到

{"data":
 [
  {"first":"Anton","id":1,"last":"Spelec"},
  {"first":"Rosamunde","id":2,"last":"Pilcher"},
  {"first":"Vlasta","id":3,"last":"Burian"}
 ]
}

但没有render_template,则不会显示html页面。谢谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

使用data例如

# 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]}

然后将data作为上下文参数传递给render_template

...
return render_template('data.html', data=data)

这样,数据序列化的方式类似于所需的JSON。