Skip to content Skip to sidebar Skip to footer

Flask: How To Run A Function With A Post Method As A Background Task And Then Access It In Another Class

I'm automating a pump which is turned on only when the soil humidity value(obtained from a soil humidity sensor) exceeds a certain value. This is how it is: A user selects a value

Solution 1:

Consider using Celery which is an asynchronous task queue. You keep run your long running job, get status updates (even custom updates).

These links should help you understand how it works :

https://github.com/miguelgrinberg/flask-celery-example

https://blog.miguelgrinberg.com/post/using-celery-with-flask

And you can even look at the Celery documentation.

This is example of how you can implement your function. You can take it forward from there.

/tasks.py

@celery.taskdefmy_task(self, threshold):
    if sensor_val < threshold:
        self.update_state(state="Sensor Value below threshold", meta={'sensor_val':sensor_val, 'threshold':threshold})
    else:
        self.update_state(state="Sensor Value past threshold. Please check.", meta={'sensor_val':sensor_val, 'threshold':threshold})
        """Do whatever you would like to do"""

/views.py

defsensor_check(request):
    if request.method == "POST":
        threshold = request.POST['threshold']
        from tasks import my_task
        job = my_task.delay(threshold)
        return HttpResponseRedirect(reverse("task_status")+"?job_id="+job.id)

deftask_status(request):
    if'job_id'in request.GET:
        job_id = request.GET['job_id']
        job = AsyncResult(job_id)
        data = job._get_task_meta()
        return JsonResponse(data)
    else:
        JsonResponse("No job ID given")

Post a Comment for "Flask: How To Run A Function With A Post Method As A Background Task And Then Access It In Another Class"