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

时间:2017-07-14 15:22:53

标签: python aws-lambda python-3.6 zappa

我使用Flask和Zappa部署到AWS Lambda,但我的一个任务需要300多秒才能执行,因此lambda会关闭。

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

1 个答案:

答案 0 :(得分:3)

以下是我制作的简单应用

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 app environ中填写了请求。这可以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()

并且响应符合预期

Time Before After

PS:详细解决方案,让您了解如何找到解决此类问题的方法