Python 使用 Django 将 python-amazon-simple-product-api 结果转换为 js



我正在用Python Django和rest框架编写一个API。我正在使用一个名为python-amazon-simple-product-api的python打包来访问亚马逊广告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)

使用此代码,我收到以下错误;

TypeError: Object of type 'AmazonProduct' is not JSON serializable

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

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

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

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

并像这样使用它:

products = amazon.search(Brand="Microsoft", SearchIndex="Software", ResponseGroup="Images,ItemAttributes,Accessories,Reviews,VariationSummary,Variations")
data = AmazonProductSerializer(products, many=True).data
return Response(data, status=status.HTTP_200_OK)

希望对您有所帮助!

如果您只想按原样获取亚马逊结果并转换为 JSON,最好的方法可能是使用宽吻 [ 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获取。

最新更新