Externalizing medians

This was quite a simple script so far, but you probably would want to update the JSON constantly—without needing to re-deploy the function every time. Let's do exactly that. We'll move the JSON to some public bucket (or not a public bucket—just make sure to use credentials with the rights to access it), and let a function download it upon request or upon deployment. We'll use the built-in urllib package, not requests, as we don't want to spend our 50 MB memory on one more dependency package. Delete the local JSON to keep the code slim, and add this code:

import json, urllib.request
url = 'https://raw.githubusercontent.com/PacktPublishing/Python-Programming-Projects-Learn-Python-3.7-by-building-applications/master/Chapter18/data/model.json'

obj = urllib.request.urlopen(url).read()
model = json.loads(obj)

Here, we have a choice: we could load json outside the function, which means it will be pre-loaded on spawn and update ever so often. Alternatively, we could load the measurements within the request function, meaning values will be updated via the API the second we override the file on S3. This would, however, affect the execution time of the function, so it's up to you to decide.

If everything works locally, let's deploy it! For that, just type this:

chalice deploy

It may take a few seconds to prepare the package, and does require AWS credentials to be set up. Once done, Chalice will print out the name of the function and the URL to hit. Once deployed, our function is publicly available for everyone! See here:

$ curl -X GET https://<unique_aws_id>.execute-api.us-east-1.amazonaws.com/api/predict/appliance
{"status":"success","complaint_type":"appliance","estimated_time":63.53}

In this section, we were able to deploy a basic prediction model API endpoint that reads values from a JSON file stored on GitHub but is accessible for everyone on the web. Now let's go one step further and set up an actual ML model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.227.92