Search code examples
pythonreturnaws-lambdaserverless-frameworkchalice

return chalice Response object from chalicelib/utils.py


Using AWS Chalice, and suppose app.py looks like this:

from chalice import Chalice, Response
from chalicelib.utils import some_class

app = Chalice(app_name='myApp')
app.debug = True

@app.route('/myRoute',
       methods=['POST'],
       content_types=['application/octet-stream'])
def myRoute():
   some_class_instance = some_class()
   some_class_instance.some_def()

   return Response(
      body={'hello': 'world'},
      headers={'Content-Type': 'application/json'})

and in utils.py:

import requests
from chalice import Response

class some_class:
    def some_def():
        return Response(
             body={'key1': 'val1'},
             headers={'Content-Type': 'application/json'})

The return statement from some_class.some_def is not returned to the client if written as shown. But if I run some_def from inside app.py it is returned. Why?

How can I return objects to the client from outside of app.py?


Solution

  • The answer is trivially simple (hint from a colleague). You evaluate the returned value from some_def in the caller function (myRoute). If it's non-empty you return that one. Using the example from the question, app.py looks like so:

    from chalice import Chalice, Response
    from chalicelib.utils import some_class
    
    app = Chalice(app_name='myApp')
    app.debug = True
    
    @app.route('/myRoute',
               methods=['POST'],
               content_types=['application/octet-stream'])
    def myRoute():
        some_class_instance = some_class()
        r = some_class_instance.some_def()
        if r:
            return r
        else:
            return Response(
                   body={'hello': 'world'},
                   headers={'Content-Type': 'application/json'})