Search code examples
pythondjangoapihttpresponseamazon-product-api

How to return python script response as Http response using Django framework


I am using Python Django framework, new to it.

I am getting "None" in the browser, not sure what is wrong with my code.

from django.http import HttpResponse

def index(request):
 from amazon.api import AmazonAPI
 AMAZON_ACCESS_KEY = "cant share my key"
 AMAZON_SECRET_KEY = "cant share my key"
 AMAZON_ASSOC_TAG = "cant share my tag"
 REGION = "US"
 amazon = AmazonAPI(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY, AMAZON_ASSOC_TAG)

 products = amazon.search(BrowseNode='3760911', SearchIndex='Beauty', 
 MaximumPrice='30')

 for i, product in enumerate(products, 1):
    return HttpResponse(print(str(product)))

The code works like a charm when I run in python shell however it doesn't run in the browser.


Solution

  • for i, product in enumerate(products, 1):
        return HttpResponse(print(str(product)))
    

    There are two problems here:

    • You don't need print. HttpResponse accepts a string and renders it to web browsers.
    • You can only return once.

    The simplest solution I can think of is:

    resp = ''
    for i, product in enumerate(products, 1):
        resp += str(product) + '<br>'
    return HttpResponse(resp)