Refactored JsonPayload to JsonResponse

This commit is contained in:
Joel Collins 2019-09-13 18:04:33 +01:00
parent d13341dd5b
commit 6581385ab9
16 changed files with 37 additions and 43 deletions

View file

@ -1,6 +1,6 @@
from openflexure_microscope.plugins import MicroscopePlugin from openflexure_microscope.plugins import MicroscopePlugin
from openflexure_microscope.api.v1.views import MicroscopeViewPlugin from openflexure_microscope.api.v1.views import MicroscopeViewPlugin
from openflexure_microscope.api.utilities import JsonPayload from openflexure_microscope.api.utilities import JsonResponse
import os import os
import time import time
@ -115,7 +115,7 @@ class HelloWorldAPI(MicroscopeViewPlugin):
Assumes request will include a JSON payload. Assumes request will include a JSON payload.
""" """
# Get payload JSON # Get payload JSON
payload = JsonPayload(request) payload = JsonResponse(request)
# Extract a value from the JSON key 'plugin_string', and convert to a string. If no value is given, default to empty. # Extract a value from the JSON key 'plugin_string', and convert to a string. If no value is given, default to empty.
new_plugin_string = payload.param('plugin_string', default='', convert=str) new_plugin_string = payload.param('plugin_string', default='', convert=str)
@ -134,7 +134,7 @@ class TimelapseAPI(MicroscopeViewPlugin):
def post(self): def post(self):
# Get any JSON data in the body of the POST request # Get any JSON data in the body of the POST request
payload = JsonPayload(request) payload = JsonResponse(request)
# Extract the "n_images" parameter if it was passed. Otherwise, default to 10. # Extract the "n_images" parameter if it was passed. Otherwise, default to 10.
n_images = payload.param('n_images', default=10, convert=int) n_images = payload.param('n_images', default=10, convert=int)

View file

@ -80,7 +80,7 @@ For example, a timelapse plugin may look like:
from openflexure_microscope.plugins import MicroscopePlugin from openflexure_microscope.plugins import MicroscopePlugin
from openflexure_microscope.exceptions import TaskDeniedException from openflexure_microscope.exceptions import TaskDeniedException
from openflexure_microscope.api.v1.views import MicroscopeViewPlugin from openflexure_microscope.api.v1.views import MicroscopeViewPlugin
from openflexure_microscope.api.utilities import JsonPayload from openflexure_microscope.api.utilities import JsonResponse
### MICROSCOPE PLUGIN ### ### MICROSCOPE PLUGIN ###

View file

@ -130,7 +130,7 @@ An example web route with simple responses may look like:
Parsing JSON from HTTP POST requests Parsing JSON from HTTP POST requests
------------------------------------ ------------------------------------
To ease obtaining values from a JSON payload attached to an HTTP POST request, you can use the :py:class:`openflexure_microscope.api.utilities.JsonPayload` class. This allows parameters to be extracted by their key, with a default value supplied to avoid errors associated with nonexistent keys. Additionally, a converter function may be passed, used in the following examples to convert the type of a value. In principle, however, you can pass any single-argument function and it will apply that function to the value, if it exists. To ease obtaining values from a JSON payload attached to an HTTP POST request, you can use the :py:class:`openflexure_microscope.api.utilities.JsonResponse` class. This allows parameters to be extracted by their key, with a default value supplied to avoid errors associated with nonexistent keys. Additionally, a converter function may be passed, used in the following examples to convert the type of a value. In principle, however, you can pass any single-argument function and it will apply that function to the value, if it exists.
.. code-block:: python .. code-block:: python
@ -139,7 +139,7 @@ To ease obtaining values from a JSON payload attached to an HTTP POST request, y
def post(self): def post(self):
# Get payload JSON from request # Get payload JSON from request
payload = JsonPayload(request) payload = JsonResponse(request)
# Try to find value associated with 'my_string' key. # Try to find value associated with 'my_string' key.
# If that key doesn't exist in the payload, return '' instead. # If that key doesn't exist in the payload, return '' instead.
@ -147,5 +147,5 @@ To ease obtaining values from a JSON payload attached to an HTTP POST request, y
new_plugin_string = payload.param('my_string', default='', convert=str) new_plugin_string = payload.param('my_string', default='', convert=str)
... ...
.. autoclass:: openflexure_microscope.api.utilities.JsonPayload .. autoclass:: openflexure_microscope.api.utilities.JsonResponse
:members: :members:

View file

@ -3,7 +3,7 @@ from werkzeug.exceptions import BadRequest
from flask import url_for from flask import url_for
class JsonPayload: class JsonResponse:
def __init__(self, request): def __init__(self, request):
""" """
Object to wrap up simple functionality for parsing a JSON response. Object to wrap up simple functionality for parsing a JSON response.

View file

@ -1,4 +1,4 @@
from openflexure_microscope.api.utilities import gen, JsonPayload from openflexure_microscope.api.utilities import gen, JsonResponse
from openflexure_microscope.api.v1.views import MicroscopeView from openflexure_microscope.api.v1.views import MicroscopeView
from flask import Response, Blueprint, jsonify, request from flask import Response, Blueprint, jsonify, request
@ -203,7 +203,7 @@ class ConfigAPI(MicroscopeView):
:status 200: capture created :status 200: capture created
""" """
payload = JsonPayload(request) payload = JsonResponse(request)
logging.debug("Updating settings from POST request:") logging.debug("Updating settings from POST request:")
logging.debug(payload.json) logging.debug(payload.json)

View file

@ -1,4 +1,4 @@
from openflexure_microscope.api.utilities import get_bool, JsonPayload from openflexure_microscope.api.utilities import get_bool, JsonResponse
from openflexure_microscope.api.v1.views import MicroscopeView from openflexure_microscope.api.v1.views import MicroscopeView
from openflexure_microscope.utilities import filter_dict from openflexure_microscope.utilities import filter_dict
@ -98,7 +98,7 @@ class ListAPI(MicroscopeView):
:<header Content-Type: application/json :<header Content-Type: application/json
:status 200: capture created :status 200: capture created
""" """
payload = JsonPayload(request) payload = JsonResponse(request)
filename = payload.param('filename') filename = payload.param('filename')
temporary = payload.param('temporary', default=False, convert=bool) temporary = payload.param('temporary', default=False, convert=bool)
@ -258,7 +258,7 @@ class CaptureAPI(MicroscopeView):
if not capture_obj: if not capture_obj:
return abort(404) # 404 Not Found return abort(404) # 404 Not Found
data_dict = JsonPayload(request).json data_dict = JsonResponse(request).json
capture_obj.put_metadata(data_dict) capture_obj.put_metadata(data_dict)
@ -463,7 +463,7 @@ class TagsAPI(MicroscopeView):
if not capture_obj or not capture_obj.state['available']: if not capture_obj or not capture_obj.state['available']:
return abort(404) # 404 Not Found return abort(404) # 404 Not Found
data_dict = JsonPayload(request).json data_dict = JsonResponse(request).json
if type(data_dict) != list: if type(data_dict) != list:
return abort(400) return abort(400)
@ -499,7 +499,7 @@ class TagsAPI(MicroscopeView):
if not capture_obj: if not capture_obj:
return abort(404) # 404 Not Found return abort(404) # 404 Not Found
data_dict = JsonPayload(request).json data_dict = JsonResponse(request).json
if type(data_dict) != list: if type(data_dict) != list:
return abort(400) return abort(400)

View file

@ -1,5 +1,5 @@
from openflexure_microscope.api.v1.views import MicroscopeView from openflexure_microscope.api.v1.views import MicroscopeView
from openflexure_microscope.api.utilities import JsonPayload from openflexure_microscope.api.utilities import JsonResponse
from flask import jsonify, request from flask import jsonify, request
@ -43,7 +43,7 @@ class ZoomAPI(MicroscopeView):
:<header Content-Type: application/json :<header Content-Type: application/json
:status 200: preview started/stopped :status 200: preview started/stopped
""" """
payload = JsonPayload(request) payload = JsonResponse(request)
zoom_value = payload.param('zoom_value', default=1.0, convert=float) zoom_value = payload.param('zoom_value', default=1.0, convert=float)
self.microscope.camera.set_zoom(zoom_value) self.microscope.camera.set_zoom(zoom_value)
@ -93,7 +93,7 @@ class OverlayAPI(MicroscopeView):
:status 200: preview started/stopped :status 200: preview started/stopped
""" """
payload = JsonPayload(request) payload = JsonResponse(request)
text = payload.param('text', default="", convert=str) text = payload.param('text', default="", convert=str)
size = payload.param('size', default=50, convert=int) size = payload.param('size', default=50, convert=int)

View file

@ -1,4 +1,4 @@
from openflexure_microscope.api.utilities import JsonPayload from openflexure_microscope.api.utilities import JsonResponse
from openflexure_microscope.api.v1.views import MicroscopeView from openflexure_microscope.api.v1.views import MicroscopeView
from flask import jsonify, request from flask import jsonify, request
@ -37,7 +37,7 @@ class GPUPreviewAPI(MicroscopeView):
:status 200: preview started/stopped :status 200: preview started/stopped
""" """
if operation == "start": if operation == "start":
payload = JsonPayload(request) payload = JsonResponse(request)
window = payload.param('window', default=[]) window = payload.param('window', default=[])
logging.debug(window) logging.debug(window)

View file

@ -1,4 +1,4 @@
from openflexure_microscope.api.utilities import JsonPayload from openflexure_microscope.api.utilities import JsonResponse
from openflexure_microscope.api.v1.views import MicroscopeView from openflexure_microscope.api.v1.views import MicroscopeView
from openflexure_microscope.utilities import axes_to_array, filter_dict from openflexure_microscope.utilities import axes_to_array, filter_dict
@ -60,7 +60,7 @@ class PositionAPI(MicroscopeView):
""" """
# Create response object # Create response object
payload = JsonPayload(request) payload = JsonResponse(request)
logging.debug(payload.json) logging.debug(payload.json)
# Construct position array # Construct position array

View file

@ -29,12 +29,6 @@ USER_CONFIG_FILE_OLD = os.path.join(USER_CONFIG_DIR, "microscoperc.yaml")
with open(DEFAULT_CONFIG_PATH, 'r') as default_rc: with open(DEFAULT_CONFIG_PATH, 'r') as default_rc:
DEFAULT_CONFIG = default_rc.read() DEFAULT_CONFIG = default_rc.read()
# Run a one-time conversion of the old microscoperc.yaml into the new microscope_settings.yaml
# TODO: Should be removed in >1.0.1?
if (not os.path.isfile(USER_CONFIG_FILE)) and (os.path.isfile(USER_CONFIG_FILE_OLD)):
os.rename(USER_CONFIG_FILE_OLD, USER_CONFIG_FILE)
# HANDLE CUSTOM YAML PARSING # HANDLE CUSTOM YAML PARSING
def construct_yaml_bool(self, node): def construct_yaml_bool(self, node):
""" """

View file

@ -8,7 +8,7 @@ as well as some Flask imports to simplify API route development
# Plugin classes # Plugin classes
from openflexure_microscope.plugins import MicroscopePlugin from openflexure_microscope.plugins import MicroscopePlugin
from openflexure_microscope.api.v1.views import MicroscopeViewPlugin from openflexure_microscope.api.v1.views import MicroscopeViewPlugin
from openflexure_microscope.api.utilities import JsonPayload from openflexure_microscope.api.utilities import JsonResponse
# Exceptions # Exceptions
from openflexure_microscope.exceptions import TaskDeniedException from openflexure_microscope.exceptions import TaskDeniedException

View file

@ -1,17 +1,17 @@
import numpy as np import numpy as np
import logging import logging
from openflexure_microscope.devel import MicroscopeViewPlugin, JsonPayload, request, jsonify from openflexure_microscope.devel import MicroscopeViewPlugin, JsonResponse, request, jsonify
class MeasureSharpnessAPI(MicroscopeViewPlugin): class MeasureSharpnessAPI(MicroscopeViewPlugin):
def post(self): def post(self):
payload = JsonPayload(request) payload = JsonResponse(request)
return jsonify({'sharpness': self.plugin.measure_sharpness()}) return jsonify({'sharpness': self.plugin.measure_sharpness()})
class AutofocusAPI(MicroscopeViewPlugin): class AutofocusAPI(MicroscopeViewPlugin):
def post(self): def post(self):
payload = JsonPayload(request) payload = JsonResponse(request)
# Figure out the range of z values to use # Figure out the range of z values to use
dz = payload.param("dz", default=np.linspace(-300, 300, 7), convert=np.array) dz = payload.param("dz", default=np.linspace(-300, 300, 7), convert=np.array)
@ -24,7 +24,7 @@ class AutofocusAPI(MicroscopeViewPlugin):
class FastAutofocusAPI(MicroscopeViewPlugin): class FastAutofocusAPI(MicroscopeViewPlugin):
def post(self): def post(self):
payload = JsonPayload(request) payload = JsonResponse(request)
# Figure out the parameters to use # Figure out the parameters to use
dz = payload.param("dz", default=2000, convert=int) dz = payload.param("dz", default=2000, convert=int)

View file

@ -1,4 +1,4 @@
from openflexure_microscope.devel import MicroscopePlugin, MicroscopeViewPlugin, JsonPayload, request, jsonify from openflexure_microscope.devel import MicroscopePlugin, MicroscopeViewPlugin, JsonResponse, request, jsonify
import logging import logging

View file

@ -1,10 +1,10 @@
from openflexure_microscope.devel import MicroscopeViewPlugin, JsonPayload, request, jsonify, abort from openflexure_microscope.devel import MicroscopeViewPlugin, JsonResponse, request, jsonify, abort
import logging import logging
class TileScanAPI(MicroscopeViewPlugin): class TileScanAPI(MicroscopeViewPlugin):
def post(self): def post(self):
payload = JsonPayload(request) payload = JsonResponse(request)
# Get params # Get params
filename = payload.param('filename') filename = payload.param('filename')

View file

@ -1,4 +1,4 @@
from openflexure_microscope.api.utilities import JsonPayload from openflexure_microscope.api.utilities import JsonResponse
from openflexure_microscope.api.v1.views import MicroscopeViewPlugin from openflexure_microscope.api.v1.views import MicroscopeViewPlugin
from openflexure_microscope.exceptions import TaskDeniedException from openflexure_microscope.exceptions import TaskDeniedException
@ -40,7 +40,7 @@ class HelloWorldAPI(MicroscopeViewPlugin):
Assumes request will include a JSON payload. Assumes request will include a JSON payload.
""" """
# Get payload JSON # Get payload JSON
payload = JsonPayload(request) payload = JsonResponse(request)
# Extract a value from the JSON key 'plugin_string', and convert to a string. If no value is given, default to empty. # Extract a value from the JSON key 'plugin_string', and convert to a string. If no value is given, default to empty.
new_plugin_string = payload.param('plugin_string', default='', convert=str) new_plugin_string = payload.param('plugin_string', default='', convert=str)
@ -61,7 +61,7 @@ class LongRunningAPI(MicroscopeViewPlugin):
Method to call when an HTTP POST request is made. Method to call when an HTTP POST request is made.
""" """
# Get payload JSON # Get payload JSON
payload = JsonPayload(request) payload = JsonResponse(request)
# Extract a values from the JSON payload. # Extract a values from the JSON payload.
time_to_run = payload.param('time', default=10, convert=int) time_to_run = payload.param('time', default=10, convert=int)
@ -84,7 +84,7 @@ class SomeExceptionAPI(MicroscopeViewPlugin):
Method to call when an HTTP POST request is made. Method to call when an HTTP POST request is made.
""" """
# Get payload JSON # Get payload JSON
payload = JsonPayload(request) payload = JsonResponse(request)
# Attach the long-running method as a microscope task # Attach the long-running method as a microscope task
try: try:

View file

@ -1,4 +1,4 @@
from openflexure_microscope.devel import MicroscopeViewPlugin, TaskDeniedException, JsonPayload, Response, request, escape, jsonify from openflexure_microscope.devel import MicroscopeViewPlugin, TaskDeniedException, JsonResponse, Response, request, escape, jsonify
import logging import logging
@ -12,7 +12,7 @@ class DoAPI(MicroscopeViewPlugin):
def post(self): def post(self):
# Get payload JSON # Get payload JSON
payload = JsonPayload(request) payload = JsonResponse(request)
# Extract a values from the JSON payload. # Extract a values from the JSON payload.
val_int = payload.param('val_int', default=None, convert=int) val_int = payload.param('val_int', default=None, convert=int)
@ -49,7 +49,7 @@ class TaskAPI(MicroscopeViewPlugin):
def post(self): def post(self):
# Get payload JSON # Get payload JSON
payload = JsonPayload(request) payload = JsonResponse(request)
# Extract a values from the JSON payload. # Extract a values from the JSON payload.
val_int = payload.param('run_time', default=5, convert=int) val_int = payload.param('run_time', default=5, convert=int)