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.

Settings.

host = '127.0.0.1'
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
sys.path.append(r'{0}')
""".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):
    os.mkdir(dest)
code_file = os.path.join(dest, "_start_server.py")
print("Write file '{0}'.".format(code_file))
with open(code_file, "w") as f:
    f.write(code)

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)
else:
    cmd = [sys.executable, '-u', code_file]
    print("Running '{0}'".format(cmd))
    proc = Popen(cmd)
print('Start server, process id', proc.pid)

Out:

Write file 'somewhere/workspace/lightmlrestapi/lightmlrestapi_UT_39_std/_doc/examples/temp_scripts/_start_server.py'.
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.py']'
Start server, process id 32383

Let’s wait.

from time import sleep
sleep(3)

Let’s query the server.

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

Out:

ERROR: ConnectionError(MaxRetryError("HTTPConnectionPool(host='127.0.0.1', 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={proc.pid}, fLOG=print)

Out:

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

{32383}

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

Gallery generated by Sphinx-Gallery