View Project in Designer

In this exercise, we will create a simple web service which streams data to the client. The projects main node is the server_http node which listens for incoming HTTP requests. It accepts an authentication node and needs to be terminated by a response node.

Begin by dragging the following nodes onto the workspace:

  • miranda.server_http
  • Allow all
  • miranda.http_response

Then create a new node by right clicking on the workspace and selecting Create Node. This node will be used to generate the data that will be streamed to the client. Rename the new code and call it Hello, world.

Connect them according to the image below:

Right click on the Hello, world-node and commit the following code to the execute function:

@wob.execute()
def execute(self):
  payload = self.value["payload"]
  response_queue = self.value["response_queue"]
  response_queue.put({"message": "Hello, world!"})

Before you can run the program there are two things you need to do:

  1. You need to build a custom image.
  2. Switch the bind_http switch to on before starting the processor.

When this is done you can click run and the HTTP server will start listening on port 443 on the following address: https://<job id>.p.mainly.cloud

The <job id> you find if you click the job indocator in the top right of the workspace screen:

Here we see that the ID is 01hwawbp7aam0cx8jcwzt38vtj and if we go to https://01hwawbp7aam0cx8jcwzt38vtj.p.mainly.cloud/docs we can verify that the service is running. Next we need to write the client code. For this we need Visual Studio code or similar and an installed python environment on our desktop.

This is the client code we’re going to use:

import requests
import json
def run_mainly_task(pod_id : str, payload = None, auth= None):
    # Create a new cookie with the desired domain
    sess = requests.Session()
    r = sess.post(f"https://{pod_id}/stream_run_payload", data= { "payload" : json.dumps(payload) }, headers={"authorization" : json.dumps(auth)} , verify=False, stream=True)
    for i in  r.iter_lines(1,decode_unicode=True, delimiter='\xb6'):
        yield i

We call the function like this:

for i in  run_mainly_task("01hwawbp7aam0cx8jcwzt38vtj.p.mainly.cloud", payload= { "a" : 1, "b" : 2 }):
  print (i)

We should expect to see the following output:

{"message": "Hello, world!"}