aws lambda事件处理程序管理器

domovoi的Python项目详细描述


domovoiAWS Chalice的扩展,用于处理AWS Lambdaevent sources其他 通过api网关的http请求。domovoi允许您轻松地配置和部署lambda函数来服务http 通过ALB的请求, 在一个时间表上,或响应各种事件,如SNSSQS消息、s3事件或自定义 state machine转换:

importjson,boto3,domovoiapp=domovoi.Domovoi()# Compared to API Gateway, ALB increases the response timeout from 30s to 900s, but reduces the payload# limit from 10MB to 1MB. It also does not try to negotiate on the Accept/Content-Type headers.@app.alb_target()defserve(event,context):returndict(statusCode=200,statusDescription="200 OK",isBase64Encoded=False,headers={"Content-Type":"application/json"},body=json.dumps({"hello":"world"}))@app.scheduled_function("cron(0 18 ? * MON-FRI *)")deffoo(event,context):context.log("foo invoked at 06:00pm (UTC) every Mon-Fri")returndict(result=True)@app.scheduled_function("rate(1 minute)")defbar(event,context):context.log("bar invoked once a minute")boto3.resource("sns").create_topic(Name="bartender").publish(Message=json.dumps({"beer":1}))returndict(result="Work work work")@app.sns_topic_subscriber("bartender")deftend(event,context):message=json.loads(event["Records"][0]["Sns"]["Message"])context.log(dict(beer="Quadrupel",quantity=message["beer"]))# SQS messages are deleted upon successful exit, requeued otherwise.# See https://docs.aws.amazon.com/lambda/latest/dg/with-sqs.html@app.sqs_queue_subscriber("my_queue",batch_size=64)defprocess_queue_messages(event,context):message=json.loads(event["Records"][0]["body"])message_attributes=event["Records"][0]["messageAttributes"]# You can colocate a state machine definition with an SQS handler to launch a SFN driven lambda from SQS.returnapp.state_machine.start_execution(**message)["executionArn"]@app.cloudwatch_event_handler(source=["aws.ecs"])defmonitor_ecs_events(event,context):message=json.loads(event["Records"][0]["Sns"]["Message"])context.log("Got an event from ECS: {}".format(message))@app.s3_event_handler(bucket="myS3bucket",events=["s3:ObjectCreated:*"],prefix="foo",suffix=".bar")defmonitor_s3(event,context):context.log("Got an event from S3: {}".format(event))# Set use_sns=False, use_sqs=False to subscribe your Lambda directly to S3 events without forwarding them through an SNS-SQS bridge.# That approach has fewer moving parts, but you can only subscribe one Lambda function to events in a given S3 bucket.@app.s3_event_handler(bucket="myS3bucket",events=["s3:ObjectCreated:*"],prefix="foo",suffix=".bar",use_sns=False,use_sqs=False)defmonitor_s3(event,context):context.log("Got an event from S3: {}".format(event))# DynamoDB event format: https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html@app.dynamodb_stream_handler(table_name="MyDynamoTable",batch_size=200)defhandle_dynamodb_stream(event,context):context.log("Got {} events from DynamoDB".format(len(event["Records"])))context.log("First event: {}".format(event["Records"][0]["dynamodb"]))# Use the following command to log a CloudWatch Logs message that will trigger this handler:# python -c'import watchtower as w, logging as l; L=l.getLogger(); L.addHandler(w.CloudWatchLogHandler()); L.error(dict(x=8))'# See http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html for the filter pattern syntax@app.cloudwatch_logs_sub_filter_handler(log_group_name="watchtower",filter_pattern="{$.x = 8}")defmonitor_cloudwatch_logs(event,context):print("Got a CWL subscription filter event:",event)# See http://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html# See the "AWS Step Functions state machines" section below for a complete example of setting up a state machine.@app.step_function_task(state_name="Worker",state_machine_definition=state_machine)defworker(event,context):return{"result":event["input"]+1,"my_state":context.stepfunctions_task_name}

安装

pip install domovoi

用法

首次设置:

domovoi new-project
  • 使用上面的示例编辑app.py中的domovoi应用入口点。

  • my_project/.chalice/policy-dev.json中编辑lambda函数的iam策略以添加任何权限 需要。

  • 部署事件处理程序:

    domovoi deploy
    

要将文件转移到部署包中,请在项目中使用domovoilib目录 chalicelib在酒杯里。例如,my_project/domovoilib/rds_cert.pem变成/var/task/domovoilib/rds_cert.pem/var/task/app.py中执行函数,以/var/task作为工作目录。见 Chalice docs了解有关如何设置chalice配置的更多信息。

支持的事件类型

有关 可用于触发lambda函数的事件源概述。domovoi支持以下事件源:

未来可能支持的事件源:

  • 动觉流事件
  • SES(电子邮件)活动

AWS步骤功能状态机

domovoi支持aws lambda与AWS Step Functions的集成。步骤函数状态机可以使用 StartExecution方法或 API Gateway Step Functions integration

有关使用状态机的domovoi app.py应用程序的示例,请参见domovoi/examples目录, 包括在lambda即将达到执行时间限制时重新启动它的循环,以及 在多个lambda之间分配工作。

创建步骤函数时,状态机将承担与 羔羊本身。若要允许状态机调用lambda,请编辑IAM策略(在应用程序目录下,在 .chalice/policy-dev.json)包含一个语句,允许对所有资源或 了解lambda本身。

配置

alb

要使用lambda作为带有@alb_target(prefix="...")decorator的alb目标,您应该预先配置 AWS帐户中的以下资源:

  • 路由53承载的dns区域,例如example.com.,有一个域(example.com)指向它
  • DNS区域内DNS名称的活动(已验证/已颁发)ACM证书,例如^{TT14}$

配置这些配置之后,将文件.chalice/config.json中的alb_acm_cert_dns_name配置键设置为 你的域名。例如:

{
  "app_name": "my_app",
  ...
  "alb_acm_cert_dns_name": "domovoi.example.com"
}

domovoi将自动创建、管理和链接路由53区域中的alb和dns记录。

死信队列

要使lambda函数能够将失败的调用通知转发到dead letter queues,请在 文件.chalice/config.json到目标dlq arn。例如:

{
  "app_name": "my_app",
  ...
  "dead_letter_queue_target_arn": "arn:aws:sns:us-east-1:123456789012:my-dlq"
}

您可能需要更新lambda iam策略(.chalice/policy-dev.json),以便让lambda访问sns或sqs。

并发保留

对于具有多个lambda的帐户中的大容量lambda调用,可能需要设置per-function concurrency limits来划分总体并发性 配额并防止一组lambda重载另一组lambda。在domovoi中,可以通过设置配置来实现 将文件.chalice/config.json中的reserved_concurrent_executions键设置为所需的并发保留。为了 示例:

{
  "app_name": "my_app",
  ...
  "reserved_concurrent_executions": 500
}

许可证

根据Apache License, Version 2.0条款授权。

https://travis-ci.org/kislyuk/domovoi.pnghttps://codecov.io/github/kislyuk/domovoi/coverage.svg?branch=masterhttps://img.shields.io/pypi/v/domovoi.svghttps://img.shields.io/pypi/l/domovoi.svghttps://readthedocs.org/projects/domovoi/badge/?version=latest

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java根据两个数组的值对数组进行排序   具有自签名证书和NTLM代理的java Maven SSL repo错误   java自定义字体按钮不工作AndroidStudio   java通过Spring MVC web应用程序向客户端发送文本文件   Java Spring Web服务SOAP身份验证   ANT property environment=“env”无法在JAVA中检索它,但如果作为ANT命令运行,则可以正常工作   java是为spring mvc rest api或spring boot api对应用服务器的每个新请求创建的服务、存储库和组件的新实例吗?   java私有静态最终字符串未完成其工作   PKCS12的安全Java密钥重新处理   java JPA继承表每类SQLSyntaxErrorException