0

My cloud function is meant to return all documents in the dealerships database, but I am getting {}. In the activation log its showing that all records have been sent successfully.

The problem occurs at dealers = json_result["entries"] because json_result is an empty object. Tried to Expecting value: line 1 column 1 (char 0). The serverless function is at the bottom of the file.

def get_dealerships(request):
    if request.method == "GET":
        
        url = "serverless-func-url"
        context = {
            "dealerships": get_dealers_from_cf(url),
        }
        # Prints {} evry time
        print(f'test {context["dealerships"]}') 
        return render(request, 'djangoapp/index.html', context)
def get_dealers_from_cf(url, **kwargs):
    results = []
    # Call get_request with a URL parameter
    json_result = get_request(url)
    if json_result:
        # Get the row list in JSON as dealers
        # Error
        dealers = json_result["entries"]
        # For each dealer object
        for dealer_doc in dealers:
            # Create a CarDealer object with values in `doc` object
            dealer_obj = CarDealer(
                address=dealer_doc["address"],
                city=dealer_doc["city"],
                full_name=dealer_doc["full_name"],
                id=dealer_doc["id"],
                lat=dealer_doc["lat"],
                long=dealer_doc["long"],
                short_name=dealer_doc["short_name"],
                st=dealer_doc["st"],
                zip=dealer_doc["zip"],
            )
            results.append(dealer_obj)
    return results
def get_request(url, **kwargs):
    print(kwargs)
    print("GET from {} ".format(url))
    try:
        # Call get method of requests library with URL and parameters
        response = requests.get(
            url, headers={'Content-Type': 'application/json'}, params=kwargs)
    except:
        # If any error occurs
        print("Network exception occurred")
    status_code = response.status_code
    print("With status {} ".format(status_code))
    json_data = json.loads(response.text)
    return json_data

The cloud function:

import json
from cloudant.client import Cloudant
from cloudant.error import CloudantException
from cloudant.result import Result, ResultByKey
 
def main(args):
    # Connect to the database
    client = Cloudant.iam(
        account_name='account_name',
        api_key='api_key',
        connect=True
    )
    db = client['dealerships']
 
    # Query all documents from the database
    documents = []
    for doc in db:
        documents.append(doc)
 
    # Disconnect from the database
    client.disconnect()
 
    # Return the list of documents as JSON
    return {"entries": documents}
data_henrik
  • 16,724
  • 2
  • 28
  • 49
javafan12
  • 3
  • 1
  • 2
  • Are you saying that the bug is `json_result = get_request(url)` is returning null and you are expecting it to return something? – Powell Quiring May 18 '23 at 17:22
  • Yes, but the root of the problem is that the cloud function is not being called correctly. In Postman, the function gives a status code of 204. I tried rewriting the function locally in Node.js using the latest version of Cloudant SDK, and it worked until I transferred the code to the cloud and got the same problem. – javafan12 May 18 '23 at 21:17
  • How did you create the cloud function? Which Python version? Is the cloudant package included in the runtime? And, in rewriting to Node.js, did you follow the documentation on how to handle async calls (https://cloud.ibm.com/docs/openwhisk?topic=openwhisk-ts_action_nodejs_fails)? – data_henrik May 19 '23 at 05:55
  • I'm using Node.js 16. I followed the docs for handling async calls. The cloudant package is probably included because the in the activation dashboard, the functions return a valid result. https://pastebin.com/cCicUiJB. – javafan12 May 19 '23 at 13:52

2 Answers2

0

You did not share enough information on how you set up the Python action in IBM Cloud Functions or how you call the action.

Based on the error, I guess you are calling it as web action, but forgot to use the correct context extension. Does your URL end on .json?

data_henrik
  • 16,724
  • 2
  • 28
  • 49
0

Take a look at your cloud function ... here:

db = client['dealerships']

# Query all documents from the database
documents = []
for doc in db:
    documents.append(doc)

You are trying to iterate over all documents in the database without running a query, you should be doing a query, something like:

results = client.postAllDocs({ db: "dealerships", includeDocs: true })

results will then have an object which you can iterate through.