gpt4 book ai didi

python - 修改 Flask-ReSTLess 结果数组

转载 作者:太空宇宙 更新时间:2023-11-03 15:54:21 25 4
gpt4 key购买 nike

我有这样的东西:

{
"id": 1,
"username": "plasmy",
"userdetails": [
{
"detail": "A Name",
"detail_name": "Full Name",
"id": 1,
"user_id": 1
},
{
"detail": "an@email.com",
"detail_name": "Email",
"id": 2,
"user_id": 1
},
{
"detail": "An Address",
"detail_name": "Address",
"id": 3,
"user_id": 1
},
{
"detail": "999-999-9999",
"detail_name": "Phone Number",
"id": 4,
"user_id": 1
}
]
}

这是使用 Flask_ReSTLess 和 SQLAlchemy 的结果。有一个用户表和一个用户详细信息表,它们放在该 JSON 的用户详细信息部分中。我想要做的是,找到一种方式让数据看起来像这样:

{
"id": 1,
"username": "plasmy",
"userdetails": {
"Full Name": "A Name",
"Email": "an@email.com",
"Address": "An Address",
"Phone Number": "A Phone Number"
}
}

看看我是如何删除 ID 并使用字段“detail_name”作为键和“detail”作为值的。我试过使用预处理器,但它们没有用,或者我用错了。我把预处理器放在“子”表中。

这是我尝试做的(但没有成功):

def detail_sort(results):
return {'user_details': results['userdetails']}


manager.create_api(User, methods=['GET', 'POST'])
manager.create_api(UserDetails, methods=['GET', 'POST'],
preprocessors={
'GET_COLLECTION': [detail_sort]
})

我尝试了 GET_COLLECTION、GET_SINGLE 和 GET_MANY。对此的任何帮助将不胜感激。

更新:这是我根据答案尝试的新代码

from flask import Blueprint
from medinv import manager
from medinv.User.models import User, UserDetails

blueprint = Blueprint('blueprint', __name__)


@blueprint.route('/')
@blueprint.route('/home')
def home():
return "Welcome."


def detail_sort(results):
print(results)
results['userdetails'] = {item['detail_name']: item['detail'] for item in results['userdetails']}
return results['userdetails']


manager.create_api(User, methods=['GET', 'POST'])
manager.create_api(UserDetails, methods=['GET', 'POST'],
postprocessors={
'GET_COLLECTION': [detail_sort]
})

最佳答案

我认为您需要使用后处理器,因为您需要在将 json 响应发送回客户端之前对其进行修改。

好的,我重现了你的问题。现在它正在工作。这是我的代码:

import flask
import flask_sqlalchemy
import flask_restless

# Create the Flask application and the Flask-SQLAlchemy object.
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = flask_sqlalchemy.SQLAlchemy(app)


# Create your Flask-SQLALchemy models as usual but with the following
# restriction: they must have an __init__ method that accepts keyword
# arguments for all columns (the constructor in
# flask_sqlalchemy.SQLAlchemy.Model supplies such a method, so you
# don't need to declare a new one).

class User(db.Model):

__tablename__ = 'user'

id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String)
userdetails = db.relationship('UserDetails', backref='User', lazy='dynamic')


class UserDetails(db.Model):

__tablename__ = 'user_details'

id = db.Column(db.Integer, primary_key=True)
detail = db.Column(db.String)
detail_name = db.Column(db.String)
user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False)

# Create the database tables.
db.create_all()

# Create the Flask-Restless API manager.
manager = flask_restless.APIManager(app, flask_sqlalchemy_db=db)

user = User(username='plasmy')
userdetail_0 = UserDetails(detail='A name', detail_name='Full Name' )
userdetail_1 = UserDetails(detail='an@email.com', detail_name='Email')
userdetail_2 = UserDetails(detail='An Address', detail_name='Address')
userdetail_3 = UserDetails(detail='999-999-9999', detail_name='Phone Number')


user.userdetails.append(userdetail_0)
user.userdetails.append(userdetail_1)
user.userdetails.append(userdetail_2)
user.userdetails.append(userdetail_3)

db.session.add(user)
db.session.commit()

print('USER CREATED')

def detail_sort(result, **kw):
print('detail_sort called')
print(result)

for entry in result['objects']:
entry['userdetails'] = {item['detail_name']: item['detail'] for item in
entry['userdetails']}
print('MODIFIED JSON: ', result)

# Create API endpoints, which will be available at /api/<tablename> by
# default. Allowed HTTP methods can be specified as well.
# manager.create_api(Person, methods=['GET', 'POST', 'DELETE'])
# manager.create_api(Article, methods=['GET'])

manager.create_api(User, methods=['GET', 'POST', 'DELETE'],
postprocessors={
'GET_MANY': [detail_sort]
})
manager.create_api(UserDetails, methods=['GET'], )

# start the flask loop
app.run(use_reloader=False)

请注意,您需要使用GET_MANY 并查看detail_sort 是如何实现的。

不使用后处理器的响应是这样的:

{
"num_results": 1,
"objects": [
{
"id": 1,
"userdetails": [
{
"detail": "A name",
"detail_name": "Full Name",
"id": 1,
"user_id": 1
},
{
"detail": "an@email.com",
"detail_name": "Email",
"id": 2,
"user_id": 1
},
{
"detail": "An Address",
"detail_name": "Address",
"id": 3,
"user_id": 1
},
{
"detail": "999-999-9999",
"detail_name": "Phone Number",
"id": 4,
"user_id": 1
}
],
"username": "plasmy"
}
],
"page": 1,
"total_pages": 1
}

使用后处理器,响应如下所示:

{
"num_results": 1,
"objects": [
{
"id": 1,
"userdetails": {
"Address": "An Address",
"Email": "an@email.com",
"Full Name": "A name",
"Phone Number": "999-999-9999"
},
"username": "plasmy"
}
],
"page": 1,
"total_pages": 1
}

希望这对您有所帮助。

关于python - 修改 Flask-ReSTLess 结果数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44514376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com