如何使用 flask 和 jsonify 在 json 响应中添加嵌套数组和对象
How can you add nested arrays and objects within json responses using flask and jsonify
我目前正在关注此 example 以获得 API 和 运行(我的代码如下)
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
import mysql.connector
db_connect = create_engine('mysql+pymysql://root:pass@localhost/news')
app = Flask(__name__)
api = Api(app)
class Events(Resource):
def get(self):
conn = db_connect.connect() # connect to database
query = conn.execute("select id, title, description, date, scheduled,favourite,count_audio,count_video,count_articles from events;")
result = [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]
return jsonify(result)
api.add_resource(Events, '/events') # Route_1
if __name__ == '__main__':
app.run(port='5002')
我想得到一个嵌套数组 tags
和一个嵌套对象 location
,如下所示
[{
"description": "TEST DESCRIPTION",
"id": 1,
"title": "TEST TITLE",
"date": "2020-09-02",
"scheduled":"true",
"favourite":"true",
"tags": ["celebration", "national holiday"],
"location": {
"state": {
"name": "new zealand",
"affiliation": ["United Nations"]
},
"province": "",
"urbanisation": "Wellington"
}
},
{
"description": "LONG DESCRIPTION",
"id": 2,
"title": "SECOND ENTRY",
"date": "2020-09-03",
"scheduled":"false",
"favourite":"false",
"tags": ["election", "national holiday"],
"location": {
"state": {
"name": "Brazil",
"affiliation": [""]
},
"province": "",
"urbanisation": ""
}
}]
这样的事情有可能吗?我是否需要重新考虑 API 让端点覆盖每个嵌套对象?
api.add_resource(Events, '/events')
api.add_resource(tags, '/events/tag')
api.add_resource(location, '/events/location')
或者,我是否像 那样嵌套字典。
是的,它可能而且完全有效。但我不会直接查询数据库。我会使用像 SQLAlchemy, for flask use can use flask-sqlalchemy extension. The serialization can be achieved using flask-marshmallow
这样的 ORM
使用 SQLAlchemy 创建模型:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class EventModel(db.Model):
__tablename__ = "event"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=True)
class LocationModel(db.Model):
__tablename__ = "location"
id = db.Column(db.Integer, primary_key=True)
province = db.Column(db.String, nullable=True)
event_id = db.Column(db.Integer, db.ForeignKey("event.id", ondelete="CASCADE"), nullable=False)
event = db.relationship("EventModel", backref=db.backref("locations", lazy=True))
然后你需要序列化器类(使用flask-marshmallow)来处理序列化:
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, fields
from marshmallow_sqlalchemy import auto_field
class LocationSchema(SQLAlchemyAutoSchema):
class Meta:
model = LocationModel
load_instance = True
include_fk = False
id = auto_field(load_only=True)
class EventSchema(SQLAlchemyAutoSchema):
class Meta:
model = EventModel
load_instance = True
include_fk = False
id = auto_field(load_only=True)
locations = fields.Nested(LocationSchema, many=True)
最后,您可以序列化为 json,如下所示:
db.drop_all()
db.create_all()
event = EventModel(title="Summer Show")
db.session.add(event)
db.session.commit()
location1 = LocationModel(province="Upper Austria", event_id=event.id)
db.session.add(location1)
location2 = LocationModel(province="Tirol", event_id=event.id)
db.session.add(location2)
db.session.commit()
schema = EventSchema()
result = db.session.query(EventModel).all()
print(schema.dump(result, many=True))
可以找到完整的教程 here。
我目前正在关注此 example 以获得 API 和 运行(我的代码如下)
from flask import Flask, request, jsonify
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from json import dumps
import mysql.connector
db_connect = create_engine('mysql+pymysql://root:pass@localhost/news')
app = Flask(__name__)
api = Api(app)
class Events(Resource):
def get(self):
conn = db_connect.connect() # connect to database
query = conn.execute("select id, title, description, date, scheduled,favourite,count_audio,count_video,count_articles from events;")
result = [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]
return jsonify(result)
api.add_resource(Events, '/events') # Route_1
if __name__ == '__main__':
app.run(port='5002')
我想得到一个嵌套数组 tags
和一个嵌套对象 location
,如下所示
[{
"description": "TEST DESCRIPTION",
"id": 1,
"title": "TEST TITLE",
"date": "2020-09-02",
"scheduled":"true",
"favourite":"true",
"tags": ["celebration", "national holiday"],
"location": {
"state": {
"name": "new zealand",
"affiliation": ["United Nations"]
},
"province": "",
"urbanisation": "Wellington"
}
},
{
"description": "LONG DESCRIPTION",
"id": 2,
"title": "SECOND ENTRY",
"date": "2020-09-03",
"scheduled":"false",
"favourite":"false",
"tags": ["election", "national holiday"],
"location": {
"state": {
"name": "Brazil",
"affiliation": [""]
},
"province": "",
"urbanisation": ""
}
}]
这样的事情有可能吗?我是否需要重新考虑 API 让端点覆盖每个嵌套对象?
api.add_resource(Events, '/events')
api.add_resource(tags, '/events/tag')
api.add_resource(location, '/events/location')
或者,我是否像
是的,它可能而且完全有效。但我不会直接查询数据库。我会使用像 SQLAlchemy, for flask use can use flask-sqlalchemy extension. The serialization can be achieved using flask-marshmallow
这样的 ORM使用 SQLAlchemy 创建模型:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)
class EventModel(db.Model):
__tablename__ = "event"
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String, nullable=True)
class LocationModel(db.Model):
__tablename__ = "location"
id = db.Column(db.Integer, primary_key=True)
province = db.Column(db.String, nullable=True)
event_id = db.Column(db.Integer, db.ForeignKey("event.id", ondelete="CASCADE"), nullable=False)
event = db.relationship("EventModel", backref=db.backref("locations", lazy=True))
然后你需要序列化器类(使用flask-marshmallow)来处理序列化:
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, fields
from marshmallow_sqlalchemy import auto_field
class LocationSchema(SQLAlchemyAutoSchema):
class Meta:
model = LocationModel
load_instance = True
include_fk = False
id = auto_field(load_only=True)
class EventSchema(SQLAlchemyAutoSchema):
class Meta:
model = EventModel
load_instance = True
include_fk = False
id = auto_field(load_only=True)
locations = fields.Nested(LocationSchema, many=True)
最后,您可以序列化为 json,如下所示:
db.drop_all()
db.create_all()
event = EventModel(title="Summer Show")
db.session.add(event)
db.session.commit()
location1 = LocationModel(province="Upper Austria", event_id=event.id)
db.session.add(location1)
location2 = LocationModel(province="Tirol", event_id=event.id)
db.session.add(location2)
db.session.commit()
schema = EventSchema()
result = db.session.query(EventModel).all()
print(schema.dump(result, many=True))
可以找到完整的教程 here。