return 来自 chalicelib/utils.py 的圣杯响应对象

return chalice Response object from chalicelib/utils.py

使用 AWS Chalice,假设 app.py 看起来像这样:

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'})

并在 utils.py 中:

import requests
from chalice import Response

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

来自 some_class.some_def 的 return 语句不会 return 发送给客户端,如果这样写的话。但是如果我从 app.py 内部 运行 some_def 它是 returned。为什么?

如何从 app.py 之外 return 向客户提出异议?

如果您不想在 app.py 中保留应用程序代码,此解决方案适用于 <a href="http://chalice.readthedocs.io/en/latest/topics/multifile.html#multifile-support" rel="nofollow noreferrer">multifile</a> 支持。

您可以创建一个 chalicelib/ 目录,该目录中的任何内容都会递归包含在部署包中

├── app.py
├── chalicelib
│   └── __init__.py
|   └── utils.py
└── requirements.txt

然后在你的 app.py 中像这样导入

from chalicelib.utils import SomeClass

some_class = SomeClass()
some_class.some_def()

我看不到你在 utils.py 中调用 some_class.some_def。您需要像在 app.py:

中那样调用函数
some_class.some_def()

答案非常简单(来自同事的提示)。您在调用函数 (myRoute) 中评估来自 some_def 的 returned 值。如果它非空,你 return 那个。使用问题中的示例,app.py 看起来像这样:

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'})