How to schedule a function to run every hour on Flask?

前端 未结 9 2314
我寻月下人不归
我寻月下人不归 2020-11-28 01:10

I have a Flask web hosting with no access to cron command.

How can I execute some Python function every hour?

9条回答
  •  借酒劲吻你
    2020-11-28 01:23

    For a simple solution, you could add a route such as

    @app.route("/cron/do_the_thing", methods=['POST'])
    def do_the_thing():
        logging.info("Did the thing")
        return "OK", 200
    

    Then add a unix cron job that POSTs to this endpoint periodically. For example to run it once a minute, in terminal type crontab -e and add this line:

    * * * * * /opt/local/bin/curl -X POST https://YOUR_APP/cron/do_the_thing
    

    (Note that the path to curl has to be complete, as when the job runs it won't have your PATH. You can find out the full path to curl on your system by which curl)

    I like this in that it's easy to test the job manually, it has no extra dependencies and as there isn't anything special going on it is easy to understand.

    Security

    If you'd like to password protect your cron job, you can pip install Flask-BasicAuth, and then add the credentials to your app configuration:

    app = Flask(__name__)
    app.config['BASIC_AUTH_REALM'] = 'realm'
    app.config['BASIC_AUTH_USERNAME'] = 'falken'
    app.config['BASIC_AUTH_PASSWORD'] = 'joshua'
    

    To password protect the job endpoint:

    from flask_basicauth import BasicAuth
    basic_auth = BasicAuth(app)
    
    @app.route("/cron/do_the_thing", methods=['POST'])
    @basic_auth.required
    def do_the_thing():
        logging.info("Did the thing a bit more securely")
        return "OK", 200
    

    Then to call it from your cron job:

    * * * * * /opt/local/bin/curl -X POST https://falken:joshua@YOUR_APP/cron/do_the_thing
    

提交回复
热议问题