简体   繁体   English

Flask / Python修改JSON输出

[英]Flask/Python modify JSON output

I'm working on DataTables table to display large table from mySQL using Flask-SQLAlchemy. 我正在使用Flask-SQLAlchemy处理DataTables表以显示来自mySQL的大表。 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: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)

It sends this valid JSON to my html: 它将有效的JSON发送到我的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": ... }. 问题是,我需要在{“ data”:...}中包含此代码。 Is it possible to add it to JSON in flask? 是否可以将其添加到flask的JSON中?

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 当我使用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"}
 ]
}

but without render_template the html page isn't displayed. 但是如果没有render_template,则不会显示html页面。 Thank you for any advice. 感谢您的任何建议。

Make a dictionary with data key eg 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]}

Then pass data as a context argument in render_template 然后将data作为上下文参数传递给render_template

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

This way data is serialised similar to the JSON you want as a result. 这样,数据序列化的方式类似于所需的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM