使用Python中的Google Cloud Endpoints Framework返回JSON数组作为响应
问题描述:
我正在使用Google Endpoints Framework和Python(https://cloud.google.com/endpoints/docs/frameworks/python/get-started-frameworks-python),并一直在使用它构建REST API。使用Python中的Google Cloud Endpoints Framework返回JSON数组作为响应
我能够在像响应返回JSON对象(字典):
{
"items":[
{
"id": "brand_1_id",
"name": "Brand 1"
},
{
"id": "brand_2_id",
"name": "Brand 2"
}
]
}
然而,我无法返回JSON数组(列表)作为样应答:
[ { “ID”: “brand_1_id”, “名称”: “品牌1” },{ “ID”: “brand_2_id”, “名称”: “品牌2” } ]
以下是我一直使用到返回响应
下面是类创建发送响应代码段:
class BrandResponse(messages.Message):
id=messages.StringField(1, required=True)
brandName = messages.StringField(2, required=True)
brandEmail=messages.StringField(3, required=True)
brandPhone=messages.StringField(4,required=True)
brandAddress=messages.StringField(5,required=True)
brandCity=messages.StringField(6,required=True)
brandState=messages.StringField(7,required=True)
brandCountry=messages.StringField(8,required=True)
brandPostalCode=messages.StringField(9,required=True)
class MultipleBrandResponse(messages.Message):
items=messages.MessageField(BrandResponse,1,repeated=True)
以下是处理请求的方法:
@endpoints.method(
MULTIPLE_BRAND_PAGINATED_CONTAINER,
MultipleBrandResponse,
path='brand',
http_method='GET',
name='Get Brands',
audiences=firebaseAudience
)
def getBrands(self,request):
brandResponse=[]
query = BrandDB.query()
brands = query.fetch(request.limit, offset=request.start)
for brand in brands:
brandResponse.append(BrandResponse(
id=brand.key.urlsafe(),
brandName=brand.name,
brandAddress=brand.address,
brandCity=brand.city,
brandState=brand.state,
brandCountry=brand.country,
brandPostalCode=brand.postalCode,
brandPhone=brand.phone,
brandEmail=brand.email))
print("Brand count: "+str(brandResponse.count))
if len(brandResponse) == 0:
raise endpoints.NotFoundException("No brands")
return MultipleBrandResponse(items=brandResponse)
任何想法如何返回JSON数组直接而不是在一个JSON对象内部封装一个键。
答
该框架是围绕返回协议缓冲区消息而非JSON而设计的。你可能已经指定了一个结构匹配的消息,很难说没有看到你的代码。
我已更新该问题以包含实际的代码。 – Tejas
您没有使用JSON对象。您正在使用协议缓冲区消息; MultipleBrandResponse是包含一个字段的消息,其中包含BrandResponse消息的列表。协议缓冲区响应的“根”必须是单个消息,而不是消息列表。 –
认为你是对的。因此,使用Protocol Buffers并创建REST API,无法获取多个消息,因此无法获取JSON数组作为响应。 – Tejas