-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
89 lines (70 loc) · 2.48 KB
/
app.py
File metadata and controls
89 lines (70 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import time
from flask import Flask, request, render_template, session, flash, redirect, \
url_for, jsonify
from celery import Celery
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top-secret!'
# Celery configuration
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6380'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6380'
# Initialize Celery
celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)
@celery.task(bind=True)
def running_task(self, *args):
message = ""
total = args[0]
for i in range(1, total+1):
message = '{0} {1}...'.format("Something", i)
self.update_state(state='PROGRESS',
meta={'current': i, 'total': total,
'status': "", "message": message})
time.sleep(2)
return {'current': 100, 'total': 100, 'status': 'Task completed!',
'result': 42}
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html', email=session.get('email', ''))
return redirect(url_for('index'))
@app.route('/job', methods=['POST'])
def run_job():
my_number = int(request.json['data'])
if my_number > 0:
task = running_task.apply_async(args=[my_number])
return jsonify({}), 202, {'Location': url_for('job_state',
task_id=task.id)}
else:
return redirect(url_for('index'))
@app.route('/status/<task_id>')
def job_state(task_id):
task = running_task.AsyncResult(task_id)
if task.state == 'PENDING':
response = {
'state': task.state,
'current': 0,
'total': 1,
'status': 'Pending...',
"message": task.info.get('message', '')
}
elif task.state != 'FAILURE':
response = {
'state': task.state,
'current': task.info.get('current', 0),
'total': task.info.get('total', 1),
'status': task.info.get('status', ''),
"message": task.info.get('message', '')
}
if 'result' in task.info:
response['result'] = task.info['result']
else:
# something went wrong in the background job
response = {
'state': task.state,
'current': 1,
'total': 1,
'status': str(task.info),
}
return jsonify(response)
if __name__ == '__main__':
app.run(debug=True)