Implemented basic threaded tasks for long-running functionality

This commit is contained in:
Joel Collins 2019-01-23 16:48:49 +00:00
parent 4a09727e65
commit a40cb9b9f6
10 changed files with 328 additions and 14 deletions

View file

@ -1,7 +1,8 @@
from openflexure_microscope.api.utilities import JsonPayload
from openflexure_microscope.api.v1.views import MicroscopeViewPlugin
from openflexure_microscope.exceptions import TaskDeniedException
from flask import request, Response, escape
from flask import request, Response, escape, jsonify, abort
import logging
@ -51,3 +52,24 @@ class HelloWorldAPI(MicroscopeViewPlugin):
self.microscope.plugin_string = new_plugin_string
return Response(self.microscope.plugin_string)
class LongRunningAPI(MicroscopeViewPlugin):
"""
An example API plugin that uses a long-running plugin method.
"""
def post(self):
"""
Method to call when an HTTP POST request is made.
"""
# Get payload JSON
payload = JsonPayload(request)
# Extract a values from the JSON payload.
time_to_run = payload.param('time', default=10, convert=int)
try:
task = self.microscope.task.start(self.plugin.long_running, time_to_run)
return jsonify(task.state), 202
except TaskDeniedException:
return abort(409)

View file

@ -1,6 +1,8 @@
import random
import time
from openflexure_microscope.plugins import MicroscopePlugin
from .api import IdentifyAPI, HelloWorldAPI
from .api import IdentifyAPI, HelloWorldAPI, LongRunningAPI
class Plugin(MicroscopePlugin):
@ -11,6 +13,7 @@ class Plugin(MicroscopePlugin):
api_views = {
'/identify': IdentifyAPI,
'/hello': HelloWorldAPI,
'/long_running': LongRunningAPI,
}
def identify(self):
@ -27,4 +30,19 @@ class Plugin(MicroscopePlugin):
Demonstrate passive method
"""
return "Hello world!"
return "Hello world!"
def long_running(self, t_run):
"""
Demonstrate a long-running method that requires microscope hardware
"""
print("Starting a long-running task...")
n_array = []
for _ in range(t_run):
n_array.append(random.random())
time.sleep(1)
print("Long-running task finished!")
return n_array