Python使用Djang将pythonamazonsimpleproductapi结果转换为json

2024-10-03 11:13:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用pythondjango和rest框架编写API。我正在使用一个名为python-amazon-simple-product-api的python包来访问amazon广告API。我试图将结果输入rest框架,并将结果作为JSON返回,这是我目前为止的代码。在

class AmazonProductsViewSet(viewsets.ViewSet):
    def list(self, request, format=None):
        products = amazon.search(Brand="Microsoft", SearchIndex="Software",
                                 ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations")
        products = list(products)

使用此代码,我得到以下错误:

^{pr2}$

所以我试图找到一种使AmazonProduct对象可序列化的方法或更好的解决方案。在


Tags: 代码框架restapijsonamazonproductsimple
2条回答

不是JSON序列化意味着您的响应是一个对象,而不是可以通过网络发送的原始数据。在

您需要为该模型编写序列化程序。像这样:

class AmazonProductSerializer(serializers.Serializer):
    color = serializers.CharField()
    title = serializers.CharField()

像这样使用它:

^{pr2}$

希望有帮助!在

如果您只想获得amazon的结果并将其转换为JSON,那么最好的方法可能是使用bottlenose[https://github.com/lionheart/bottlenose]。我是这样做的

amazon = bottlenose.Amazon(access_key_id, secret_key, associate_tag)
class AmazonProductsViewSet(viewsets.ViewSet):
    def list(self, request, format=None):
        response = amazon.ItemSearch(Keywords="Kindle 3G", SearchIndex="All")
        return Response(xmltodict.parse(response)) #json.dumps(xmltodict.parse(response))

现在我将整个XML文档作为JSON。在

相关问题 更多 >