Skip to content

Commit

Permalink
Poll job status and get result
Browse files Browse the repository at this point in the history
  • Loading branch information
beenje authored and beenje committed Aug 21, 2016
1 parent 437e710 commit da8360a
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 4 deletions.
20 changes: 18 additions & 2 deletions app/main/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"""
import redis
from flask import Blueprint, render_template, request, jsonify, current_app, g
from flask import Blueprint, render_template, request, jsonify, current_app, g, url_for
from rq import push_connection, pop_connection, Queue
from .. import tasks
from .forms import TaskForm
Expand All @@ -36,12 +36,28 @@ def pop_rq_connection(exception=None):
pop_connection()


@bp.route('/status/<job_id>')
def job_status(job_id):
q = Queue()
job = q.fetch_job(job_id)
if job is None:
response = {'status': 'unknown'}
else:
response = {
'status': job.get_status(),
'result': job.result,
}
if job.is_failed:
response['message'] = job.exc_info.strip().split('\n')[-1]
return jsonify(response)


@bp.route('/_run_task', methods=['POST'])
def run_task():
task = request.form.get('task')
q = Queue()
job = q.enqueue(tasks.run, task)
return jsonify({'job_id': job.get_id()})
return jsonify({}), 202, {'Location': url_for('main.job_status', job_id=job.get_id())}


@bp.route('/')
Expand Down
32 changes: 30 additions & 2 deletions app/static/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,31 @@ $(document).ready(function() {
});
}

function check_job_status(status_url) {
$.getJSON(status_url, function(data) {
console.log(data);
switch (data.status) {
case "unknown":
flash_alert("Unknown job id", "danger");
$("#submit").removeAttr("disabled");
break;
case "finished":
flash_alert(data.result, "success");
$("#submit").removeAttr("disabled");
break;
case "failed":
flash_alert("Job failed: " + data.message, "danger");
$("#submit").removeAttr("disabled");
break;
default:
// queued/started/deferred
setTimeout(function() {
check_job_status(status_url);
}, 500);
}
});
}

// submit form
$("#submit").on('click', function() {
var task = $("#task").val();
Expand All @@ -28,8 +53,11 @@ $(document).ready(function() {
data: $("#taskForm").serialize(),
method: "POST",
dataType: "json",
success: function(data) {
flash_alert("Job " + data.job_id + " started...", "info", false);
success: function(data, status, request) {
$("#submit").attr("disabled", "disabled");
flash_alert("Running " + task + "...", "info");
var status_url = request.getResponseHeader('Location');
check_job_status(status_url);
},
error: function(jqXHR, textStatus, errorThrown) {
flash_alert("Failed to start " + task, "danger");
Expand Down

0 comments on commit da8360a

Please sign in to comment.