Thanks to visit codestin.com
Credit goes to github.com

Skip to content
This repository was archived by the owner on Aug 26, 2022. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
# Changelog

### #148 Story CORE-593 | [BETA] Python client SendRequest / [BETA] Python client HandleRoute
- feature:
- added send new request function to python rest package. Now you can pass the method as a parameter.
- created send request method in python client
- created handle route method in python client
- created a full route demo example
- fix:
- update lb sidecar to not crash when not finding the route env variables (added a return statement when an error occured)
---

### #147 Story CORE-591 | Implement benchmarking dapp out of Inspr Stack
- features:
- implemented k8s job for creating "kafka-test" topic on kafka
Expand All @@ -10,7 +20,7 @@
---

### #145 Story CORE-585 | [BETA] Document the BETA-Routes feature
- doc
- doc:
- described how to use the routes on Inspr (beta)
---

Expand Down
23 changes: 23 additions & 0 deletions clients/python/inspr/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,23 @@ def route_func():
self.app.add_url_rule("/channel/" + channel, endpoint = channel, view_func = route_func, methods=["POST"])
return handle_func
return wrapper

def handle_route(self, path:str) -> Callable[[Callable[[Any], Any]], Callable[[Any], Any]]:
def wrapper(handle_func: Callable[[Any], Any]):
route = remove_prefix(path, '/')
self.app.add_url_rule("/route/" + route, endpoint = "/route/" + route, view_func = handle_func, methods=["GET", "DELETE", "POST", "PUT"])
return handle_func
return wrapper

def send_request(self, node_name:str, path:str, method:str, body) -> Response:
try:
url = self.write_address + "/route/" + node_name + "/" + path
resp = send_new_request(url, method, body)
return resp

except Exception as e:
print(f"Error while trying to send request: {e}")
raise Exception("failed to deliver message: route: {}".format(url))

def run(self) -> None:
links = []
Expand All @@ -48,3 +65,9 @@ def run(self) -> None:
print("registered routes =", links, file=sys.stderr)

self.app.run(port=self.read_port)


def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
20 changes: 17 additions & 3 deletions clients/python/inspr/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ def send_post_request(url:str, body = {}, headers = {}) -> Response:
try:
resp = requests.post(url, data = json.dumps(body), headers=headers)
resp.raise_for_status()

return resp

except requests.exceptions.RequestException as e:
print(e, file=sys.stderr)
raise HTTPError

return resp


def send_update_request(url:str, body = {}, headers = {}) -> Response:
try:
Expand Down Expand Up @@ -47,3 +47,17 @@ def send_delete_request(url:str, body = {}, headers = {}) -> Response:
raise HTTPError

return resp


def send_new_request(url:str, method:str, body = {}, headers = {}) -> Response:
if method == 'POST':
return send_post_request(url,body,headers)
elif method == 'GET':
return send_get_request(url,body,headers)
elif method == 'PUT':
return send_update_request(url,body,headers)
elif method == 'DELETE':
return send_delete_request(url,body,headers)
else:
raise Exception(f"Error while send request: Method '{method}' not allowed. The allowed methods are POST,GET,UPDATE,DELETE.")

2 changes: 1 addition & 1 deletion clients/python/setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="inspr",
version="0.0.11",
version="0.0.17",
author="Inspr LLC",
description="This module define APIs to interact with the Inspr environment",
long_description=long_description, # Long description read from the the readme file
Expand Down
6 changes: 6 additions & 0 deletions examples/python/route_demo/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
build:
docker build --no-cache -t gcr.io/insprlabs/inspr/example/python/client:latest -f client/client.Dockerfile .
docker push gcr.io/insprlabs/inspr/example/python/client:latest

docker build --no-cache -t gcr.io/insprlabs/inspr/example/python/api:latest -f api/api.Dockerfile .
docker push gcr.io/insprlabs/inspr/example/python/api:latest
25 changes: 25 additions & 0 deletions examples/python/route_demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Inspr Routes Example

## Description

This folder contains the files necessary to run the routes example in your cluster. This example consists of 2 dApps:

1. client -> sends requests to the api's route.
2. api -> receives request from the client and performs a simple operation dictate by the endpoint reached (*add*, *sub* or *mul*).

## How to run it:

Make sure the latest Inspr CLI version is installed.

- To get the latest version, run the following command:
`go install inspr.dev/inspr/cmd/inspr`

Before running the Inspr CLI command to create the app in your cluster be sure to set the [configuration](../../docs/readme.md) beforehand.


This example doesn't use brokers, therefore everything is set and ready and the simpler way to test it is to run:

```bash
insprctl apply -f yamls/route-demo.yaml
```
This will create the dApp `router` that contains all the needed structures in it (other dApps and Routes).
10 changes: 10 additions & 0 deletions examples/python/route_demo/api/api.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM python:3.8 AS build

WORKDIR /app
COPY requirements.txt .

RUN pip install -r requirements.txt

COPY api/api.py .

CMD ["python3", "-u", "./api.py"]
46 changes: 46 additions & 0 deletions examples/python/route_demo/api/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
from flask import request
import sys
from http import HTTPStatus
import inspr

def main():
client = inspr.Client()

@client.handle_route("/add")
def add_handler():
data = request.get_json(force=True)
op1 = data["op1"]
op2 = data["op2"]

total = op1 + op2
print(total, file=sys.stderr)

return str(total), HTTPStatus.OK

@client.handle_route("/sub")
def sub_handler():
data = request.get_json(force=True)
op1 = data["op1"]
op2 = data["op2"]

total = op1 - op2
print(total, file=sys.stderr)

return str(total), HTTPStatus.OK

@client.handle_route("/mul")
def sub_handler():
data = request.get_json(force=True)
op1 = data["op1"]
op2 = data["op2"]

total = op1 * op2
print(total, file=sys.stderr)

return str(total), HTTPStatus.OK

client.run()


if __name__ == "__main__":
main()
10 changes: 10 additions & 0 deletions examples/python/route_demo/client/client.Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM python:3.8 AS build

WORKDIR /app
COPY requirements.txt .

RUN pip install -r requirements.txt

COPY client/client.py .

CMD ["python3", "-u", "./client.py"]
52 changes: 52 additions & 0 deletions examples/python/route_demo/client/client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import inspr
import sys
import time

ADD_PATH = "add"
SUB_PATH = "sub"
MUL_PATH = "mul"

API_NAME = "api"

def main():
client = inspr.Client()
msg_body = {
"op1": 5,
"op2": 3,
}

print("Python Client")

while True:
try:
resp = client.send_request(API_NAME, ADD_PATH, method="POST", body=msg_body)
res = resp.json()
print("The result of 5 + 3 = ", res)
except:
print("An error has occured", file=sys.stderr)

time.sleep(3)

try:
resp = client.send_request(API_NAME, SUB_PATH, method="POST", body=msg_body)
res = resp.json()
print("The result of 5 - 3 = ", res)
except:
print("An error has occured", file=sys.stderr)

time.sleep(3)

try:
resp = client.send_request(API_NAME, MUL_PATH, method="POST", body=msg_body)
res = resp.json()
print("The result of 5 * 3 = ", res)
except:
print("An error has occured", file=sys.stderr)

time.sleep(3)




if __name__ == "__main__":
main()
2 changes: 2 additions & 0 deletions examples/python/route_demo/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
flask
inspr
32 changes: 32 additions & 0 deletions examples/python/route_demo/yamls/route-demo.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
apiVersion: v1
kind: dapp

meta:
name: router
spec:
apps:
client:
meta:
name: client
parent: router
spec:
logLevel: debug
node:
spec:
replicas: 1
image: gcr.io/insprlabs/inspr/example/python/client:latest
api:
meta:
name: api
parent: router
spec:
logLevel: debug
node:
spec:
replicas: 1
image: gcr.io/insprlabs/inspr/example/python/api:latest
endpoints:
- add
- sub
- mul

2 changes: 2 additions & 0 deletions pkg/sidecars/lbsidecar/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ func (s *Server) sendRequest() rest.Handler {
zap.Any("error", err))

rest.ERROR(w, err)
return
}

if !resolved.Endpoints.Contains(endpoint) {
Expand All @@ -118,6 +119,7 @@ func (s *Server) sendRequest() rest.Handler {
zap.Any("error", err))

rest.ERROR(w, err)
return
}
URL := fmt.Sprintf("%s/route/%s", resolved.Address, path)

Expand Down