Last active
March 31, 2021 22:59
-
-
Save atrisovic/ee64cd20df5dcf81d484ae97de0bc76e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, redirect, url_for | |
from celery import Celery | |
from celery import Task | |
from subprocess import PIPE, Popen | |
import logging, os | |
logging.basicConfig(level=logging.INFO) | |
logger = logging.getLogger(__name__) | |
# Running locally: | |
# Start: | |
# docker run -d -p 6379:6379 redis | |
# celery -A app.celery worker --loglevel=info | |
# python app.py | |
# Web: | |
# http://127.0.0.1:5000/docker to run celery task | |
# http://127.0.0.1:5000/result to see result | |
# This method is copied from here: https://flask.palletsprojects.com/en/1.0.x/patterns/celery/ | |
# No need to think about it! | |
def make_celery(app): | |
celery = Celery( | |
app.import_name, | |
backend=app.config['CELERY_RESULT_BACKEND'], | |
broker=app.config['CELERY_BROKER_URL'] | |
) | |
celery.conf.update(app.config) | |
class ContextTask(celery.Task): | |
def __call__(self, *args, **kwargs): | |
with app.app_context(): | |
return self.run(*args, **kwargs) | |
celery.Task = ContextTask | |
return celery | |
flask_app = Flask(__name__) | |
flask_app.config.update( | |
CELERY_BROKER_URL='redis://localhost:6379/1', | |
CELERY_RESULT_BACKEND='redis://localhost:6379/0' | |
) | |
celery = make_celery(flask_app) | |
@flask_app.route("/docker") | |
def docker(): | |
# starts new task to run the container: | |
run_container.delay() | |
return f"Container started." | |
# check results on another page: | |
@flask_app.route('/result') | |
def result(): | |
if os.path.isfile('res.txt'): | |
f = open("res.txt", "r") | |
return f.read() | |
else: | |
return f"Still processing." | |
@celery.task(name='celery_task.run_container') | |
def run_container(): | |
process = Popen(["docker", "run", "hello-world"], stdout=PIPE) | |
stdout, stderr = process.communicate() | |
# write output in 'db' (here text file) | |
with open('res.txt','w') as f: | |
f.write(str(stdout)) | |
if __name__ == '__main__': | |
flask_app.run(debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment