如何使用 Python 和 Zappa 获取 AWS Lambda 剩余时间?

How do I get an AWS Lambda Remaining time using Python and Zappa?

我正在使用 Flask 和 Zappa 部署到 AWS Lambda,但我的一项任务执行时间超过 300 秒,因此 lambda 关闭。

我想在它恰好完成工作之前调用另一个 lambda,是否可以使用 Zappa 获取剩余时间?

下面是我构建的简单应用程序

from flask import Flask, jsonify, request
import time
import traceback

app = Flask(__name__)

@app.route("/")
def index():
    return jsonify(traceback.format_stack())

if __name__ == "__main__":
   app.run()

这给了我回溯

[
" File "/var/runtime/awslambda/bootstrap.py", line 534, in <module> main() ",
" File "/var/runtime/awslambda/bootstrap.py", line 529, in main handle_event_request(request_handler, invokeid, event_body, context_objs, invoked_function_arn) ",
" File "/var/runtime/awslambda/bootstrap.py", line 249, in handle_event_request result = request_handler(json_input, context) ",
" File "/var/task/handler.py", line 511, in lambda_handler return LambdaHandler.lambda_handler(event, context) ",
" File "/var/task/handler.py", line 242, in lambda_handler return handler.handler(event, context) ",
" File "/var/task/handler.py", line 454, in handler response = Response.from_app(self.wsgi_app, environ) ",
" File "/var/task/werkzeug/wrappers.py", line 903, in from_app return cls(*_run_wsgi_app(app, environ, buffered)) ",
" File "/var/task/werkzeug/test.py", line 884, in run_wsgi_app app_rv = app(environ, start_response) ",
" File "/var/task/zappa/middleware.py", line 70, in __call__ response = self.application(environ, encode_response) ",
" File "/var/task/flask/app.py", line 1997, in __call__ return self.wsgi_app(environ, start_response) ",
" File "/var/task/flask/app.py", line 1982, in wsgi_app response = self.full_dispatch_request() ",
" File "/var/task/flask/app.py", line 1612, in full_dispatch_request rv = self.dispatch_request() ",
" File "/var/task/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) ",
" File "/var/task/myapp.py", line 8, in index return jsonify(traceback.format_stack()) "
]

回溯指向我

https://github.com/Miserlou/Zappa/blob/f7a785351450fa9115864c7dfe223660f5a99ae6/zappa/handler.py#L454

就在那之前

# We are always on https on Lambda, so tell our wsgi app that.
environ['HTTPS'] = 'on'
environ['wsgi.url_scheme'] = 'https'
environ['lambda.context'] = context

这些是为请求填写在 WSGI 应用程序环境中的。这可以作为 flask.request.environ.get 访问。于是我把代码改成了

from flask import Flask, jsonify, request
import time
import traceback

app = Flask(__name__)

@app.route("/")
def index():
    context = request.environ.get('lambda.context', None)
    if context is not None:
       before = context.get_remaining_time_in_millis()
       time.sleep(1)
       after = context.get_remaining_time_in_millis()
       return "Time Before={}\nTime After={}".format(before, after)
    return jsonify(traceback.format_stack())

if __name__ == "__main__":
   app.run()

响应如预期

PS: 详细的解决方法,让你明白如何解决此类问题