Starts and queries a REST API

This example starts a waitress server, creates a WSGI application based on falcon and queries the REST API. This application returns the prediction from a model trained on Iris dataset.


host = ''
port = 8096

Creates a dummy application and starts a server in a different process. See dummy_application.

def process_server(host, port):
    from lightmlrestapi.testing import dummy_application
    app = dummy_application()

    from waitress import serve
    serve(app, host=host, port=port)

Saves this code into a file and we start it from a different process.

import os
import lightmlrestapi

header = """
import sys
""".format(os.path.join(os.path.dirname(lightmlrestapi.__file__), '..'))

import inspect
code = "".join(inspect.getsourcelines(process_server)[0])
code = header + code + "\nprocess_server('{0}', {1})\n".format(host, port)
dest = os.path.abspath('temp_scripts')
if not os.path.exists(dest):
code_file = os.path.join(dest, "")
print("Write file '{0}'.".format(code_file))
with open(code_file, "w") as f:

import sys
from subprocess import Popen
if sys.platform.startswith('win'):
    cmd = '{0} -u "{1}"'.format(sys.executable, code_file)
    print("Running '{0}'".format(cmd))
    proc = Popen(cmd)
    cmd = [sys.executable, '-u', code_file]
    print("Running '{0}'".format(cmd))
    proc = Popen(cmd)
print('Start server, process id',


Write file 'somewhere/workspace/lightmlrestapi/lightmlrestapi_UT_39_std/_doc/examples/temp_scripts/'.
Running '['somewhere/workspace/lightmlrestapi/lightmlrestapi_UT_39_std/_venv/bin/python3.9', '-u', 'somewhere/workspace/lightmlrestapi/lightmlrestapi_UT_39_std/_doc/examples/temp_scripts/']'
Start server, process id 32383

Let’s wait.

from time import sleep

Let’s query the server.

import requests
import ujson
features = ujson.dumps({'X': [0.1, 0.2]})
    r ='http://%s:%d' % (host, port), data=features)
except Exception as e:
    print("ERROR: %r" % e)


ERROR: ConnectionError(MaxRetryError("HTTPConnectionPool(host='', port=8096): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fdc2e80e340>: Failed to establish a new connection: [Errno 111] Connection refused'))"))

Let’s stop the server.

from pyquickhelper.loghelper import reap_children
reap_children(subset={}, fLOG=print)


process psutil.Process(pid=32383, status='terminated', exitcode=<Negsignal.SIGTERM: -15>, started='07:17:18') terminated with exit code -15


Total running time of the script: ( 0 minutes 3.083 seconds)

Gallery generated by Sphinx-Gallery