Newer
Older
Functionality needed to run a client request sequence (clients.*.main) in the ImageJ model_server 2.7 script environment

Christopher Randolph Rhodes
committed
import httplib
import json
import urllib

Christopher Randolph Rhodes
committed
from ij import ImagePlus
HOST = '127.0.0.1'
PORT = 6221
uri = 'http://{}:{}/'.format(HOST, PORT)
def hit_endpoint(method, endpoint, params=None, body=None, drop_none=True):
"""
Python 2.7 implementation of HTTP client
:param method: (str) either 'GET' or 'PUT'
:param endpoint: (str) endpoint of HTTP request
:param params: (dict) of parameters that are embedded in client request URL
:param body: (dict) of parameters that JSON-encoded and attached as payload in request
:param drop_none: (bool) remove (presumably optional) parameters with value equal to None
:return: (dict) of response status and content, formatted as dict if request is successful
"""

Christopher Randolph Rhodes
committed
connection = httplib.HTTPConnection(HOST, PORT)
if not method in ['GET', 'PUT']:
raise Exception('Can only handle GET and PUT requests')
if drop_none and params is not None:
for k, v in params.items():
if v is None:
k_pop.append(k)
for ki in k_pop:
params.pop(ki)

Christopher Randolph Rhodes
committed
if params:
url = endpoint + '?' + urllib.urlencode(params)
else:
url = endpoint
connection.request(method, url, body=json.dumps(body))

Christopher Randolph Rhodes
committed
resp = connection.getresponse()
resp_str = resp.read()
try:
content = json.loads(resp_str)

Christopher Randolph Rhodes
committed
except Exception:
content = {'str': str(resp_str)}
return {'status': resp.status, 'content': content}

Christopher Randolph Rhodes
committed
def verify_server(popup=True):
try:
resp = hit_endpoint('GET', '/')
except Exception as e:
print(e)
msg = 'Could not find server at: ' + uri
IJ.log(msg)
if popup:
IJ.error(msg)
return False
if resp['status'] != 200:
msg = 'Unknown error verifying server at: ' + uri
if popup:
IJ.error(msg)
IJ.log('Verified server is online at: ' + uri)
def run_request_sequence(imp, func, params):
"""
Execute a sequence of client requests in the ImageJ scripting environment
:param imp: (ij.ImagePlus) input image
:param func: (func) function that implements client request sequence
:param params: (dict) parameters specific to client request
:return: (ij.ImagePlus) output image
"""
in_path = imp.getProp('Location')
out_path = func(hit_endpoint, in_path, params)
return ImagePlus(out_path)