-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.py
142 lines (117 loc) · 2.87 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
from flask import Flask
from flask import request
import json
import os
import requests
app = Flask(__name__)
SIDECAR_ADDRESS = os.getenv('SIDECAR_ADDRESS')
if SIDECAR_ADDRESS is None:
SIDECAR_ADDRESS = 'http://localhost:5103'
'''
Generate JSON responsefor actions
'''
def generate_json_response(content):
return json.dumps({'response': content })
'''
Simple action handler
'''
@app.route("/actions/hello", methods=["POST"])
def hello():
app.logger.info("Hello action called.")
return generate_json_response("Hello from Python!"), 200, {'Content-Type':'application/json'}
'''
Action handler with params
'''
@app.route("/actions/welcome", methods=["POST"])
def welcome():
app.logger.info("Welcome action called.")
body = request.get_json()
params = body.get('params')
# meta = body.get('meta')
return generate_json_response('Hello {} from Python!'.format(params['name'])), 200, {'Content-Type':'application/json'}
'''
Event handler
'''
@app.route("/events/sample.event", methods=["POST"])
def sampleEvent():
# body = request.get_json()
# params = body['params']
# meta = body['meta']
app.logger.info("Sample event happened.")
return "OK"
'''
Send a POST request to the Sidecar
'''
def POST(url, content):
return requests.post(url = SIDECAR_ADDRESS + url, json = content)
'''
Register the service to the Sidecar
'''
def register_service_schema():
schema = {
'name': "python-demo",
'settings': {
'baseUrl': 'http://python-demo:5000'
},
'actions': {
'hello': '/actions/hello',
'welcome': {
'params': {
'name': 'string|no-empty|trim'
},
'handler': '/actions/welcome'
}
},
'events': {
'sample.event': '/events/sample.event'
}
}
# Register schema
rsp = POST('/v1/registry/services', schema)
print("Response: " + rsp.text)
'''
Call an action
Example:
callAction("posts.list", params = { 'limit: 5, 'offset: 0 }, meta = { 'from': 'python' })
'''
def callAction(action, **kwargs):
content = {
'params': kwargs.get('params'),
'meta': kwargs.get('meta'),
'options': kwargs.get('options')
}
print("Calling '{}' action...".format(action))
rsp = POST('/v1/call/' + action, content)
return rsp
'''
Emit an event
'''
def emitEvent(event, **kwargs):
content = {
'params': kwargs.get('params'),
'meta': kwargs.get('meta'),
'options': kwargs.get('options')
}
print("Emitting '{}' event...".format(event))
POST('/v1/emit/' + event, content)
'''
Get services list from Sidecar
'''
def getServiceList():
rsp = callAction("$node.services")
json = rsp.json()
print("Services:")
for item in json.get("response"):
print(" {}".format(item.get("fullName")))
print("")
'''
Start registration
'''
def start():
print("Registering service to the Sidecar ({})...".format(SIDECAR_ADDRESS))
register_service_schema()
getServiceList()
emitEvent("python-service.started")
start()
if __name__ == "__main__":
app.run(host='0.0.0.0', port= 5000, debug=True)