【问题标题】:How to set a crontab with html request using flask-crontab?如何使用 flask-crontab 设置带有 html 请求的 crontab?
【发布时间】:2021-12-25 11:03:56
【问题描述】:

我想运行一个 html 页面,在该页面中我使用一个按钮来设置一个特定的时间(见下文),该时间随后通过模块 flask-crontab 运行一个 cronjob。如何在不设置全局变量的情况下在def get_time() 之外使用minutehourdaymonth
在这里使用 flask-crontab 的可靠方法是什么?

APP = Flask(__name__)
Bootstrap(APP)
crontab = Crontab(APP)

...

@APP.route('/randompage.html' methods = ['POST', 'GET])
def get_time():
    time_req = request.args.get("html_time")
    format_time = datetime.strptime(time_req, "%Y-%m-%dT%H:%M")

    minute = format_time.minute
    hour = format_time.hour
    day = format_time.day
    month = fomrat_time.month

    return render_template('randompage.html', time_req=time_req)


@crontab.job()
def exe_control():
    do something here

html页面上的按钮:

<form action="/randompage.html" method="GET">
<input type="datetime-local" name="html_time"/>
<input type="submit"/></form>

【问题讨论】:

  • 您必须使用全局变量minute, hour, day, month,或者写入数据库,并在其他函数中从数据库读取。但是,如果您想在crontab.job(minute=minutes, ...) 中使用这些值,那么所有这些都是无用的。您必须直接使用crontab.job() 9 作为正常功能,而不是装饰器)get_time 才能将任务添加到 crontab。

标签: python html linux flask cron


【解决方案1】:

要在其他函数中使用值minute, hour, day, month,您必须使用global 变量或保存在全局list/dictionary 或保存在file/database` 中并在其他函数中读取。

但是,如果您希望这些值用作@crontab.job(minute=..., hour=...) 中的值,那么它是没有用的。您应该直接在get_time 中作为正常功能运行它

crontab.job(minute=minute, ...)(exe_control)


APP = Flask(__name__)
Bootstrap(APP)
crontab = Crontab(APP)

# ...

@APP.route('/randompage.html' methods = ['POST', 'GET'])
def get_time():
    time_req = request.args.get("html_time")
    format_time = datetime.strptime(time_req, "%Y-%m-%dT%H:%M")

    minute = format_time.minute
    hour = format_time.hour
    day = format_time.day
    month = fomrat_time.month

    crontab.job(minute=minute, hour=hour, day=day, month=month)(exe_control)

    return render_template('randompage.html', time_req=time_req)

# - without decorator -
def exe_control():
    do something here

【讨论】:

    猜你喜欢
    • 2011-06-30
    • 1970-01-01
    • 2011-05-08
    • 2015-11-13
    • 2011-10-10
    • 1970-01-01
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多