Answer a question

I'm using following serverless.yml file to run a flask application. My flask application has a cli command and I want to invoke it periodically.

So yml file should do two tasks, executing api calls as a normal wsgi application and invoking a command line function periodically.

What are the changes I should do for it in the yml file?

functions:
  app:
    handler: wsgi.handler
    events:
      - http: ANY /
      - http: 'ANY {proxy+}'

Serverless.yml

app = Flask(__name__)
user_cli = AppGroup('user')

@user_cli.command('create')
def create_user():
    pass

app.cli.add_command(user_cli)

Command need to run: "flask user create"

Answers

Since you might have more than one instance of lambda function running at the same time. Do you want to run this command on all instances, most probably you want it to run the command once regardless of the number of lambda functions running at a given time.

Since you are using serverless, writing a cronjob-like function is supported. Here are the steps you need to follow:

  • Add the schedule of how frequently you want the function create_user to run.

    functions:
      cronCreateUser:
        handler: app.create_user
        events:
          # At 00:00 on Sunday
          - schedule: cron(0 0 * * SUN)
    

    OR

    functions:
      cronCreateUser:
        handler: app.create_user
        events:
          # Every 1 hour
          - schedule: rate(1 hour)
    

Notes:

  1. You don't need to think of the cli command, just call the function instead (e.g. create_user).
  2. I assumed the function create_user is in a file called app.py located in the root (a.k.a. top directory) of the project.

I suggest you read more on the following:

  1. Serverless docs and examples.
  2. Crontab examples
  3. AWS Cloudwatch Event Rules (what's really happening under the hood).
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐