The best way to learn is by doing. The only way to build a strong work ethic is getting your hands dirty.
- Alex Spanos
While working on a project that required me to connect CF and On-Premise systems, I came across two very wonderful blogs written by - Matthieu Pelatan and Marius Obert . While Matthieu's blog shows end to end connection between the two systems, he relies on JAVA to demonstrate his example. Since I am not very familiar with JAVA, I decided to follow - Marius article. Marius shows how to call destinations endpoints from Flask application, which is great but it did not solve my cross-system connectivity issue. So, I decided to write this blog to show how we can call services from different systems (on-prem) via Flask (Python) application in CF environment. I thank mariusobert#overview and matthieu.pelatan#overview for providing such wonderful resources.
// Function that return current balance ( hard coded )
function returnBalance(){
try{
var output = {
status:200,
replies:[{
'type': 'text',
'content': 'Hi, current balance is: $ 23,900'
}]
};
var body = JSON.stringify(output);
$.response.contentType = 'application/json';
$.response.setBody(body);
$.response.status = $.net.http.OK;
}
catch (e) {
var output2 = {
status:500,
replies:[{
'type': 'text',
'content': e.message
}]
};
$.response.contentType = 'application/json';
var body2 = JSON.stringify(output2);
$.response.setBody(body2);
$.response.status = $.net.http.OK;
}
}
returnBalance();
from flask import Flask, request, jsonify
import requests
import json
import base64
from cfenv import AppEnv
app = Flask(__name__)
env = AppEnv()
# Creating instances of the Destiantion, XSUAA and Connectivity service
UAA_SERVICE = env.get_service(name='uaa_service')
DESTINATION_SERVICE = env.get_service(name='destination_service')
CONNECTIVITY_SERVICE = env.get_service(name='connectivity_service')
# Destination name
DESTINATION = 'demoService'
#connectivity proxy
CONNECTIVITY_PROXY = CONNECTIVITY_SERVICE.credentials["onpremise_proxy_host"]+":"
+ CONNECTIVITY_SERVICE.credentials["onpremise_proxy_port"]
# Connectivity and Destination Authentication tokens
CONNECTIVITY_SECRET = CONNECTIVITY_SERVICE.credentials["clientid"] + \
':' + CONNECTIVITY_SERVICE.credentials["clientsecret"]
DESTINATION_SECRET = DESTINATION_SERVICE.credentials["clientid"] + \
':' + DESTINATION_SERVICE.credentials["clientsecret"]
CONNECTIVITY_CREDENTIALS = base64.b64encode(
CONNECTIVITY_SECRET.encode()).decode('ascii')
DESTINATION_CREDENTIALS = base64.b64encode(
DESTINATION_SECRET.encode()).decode('ascii')
def getAccessToken(credentials, serviceName):
#Getting access token for Connectivity service.
headers = {'Authorization': 'Basic ' + credentials,
'content-type': 'application/x-www-form-urlencoded'}
form = [('client_id', serviceName.credentials["clientid"]),
('grant_type', 'client_credentials')]
r = requests.post(
UAA_SERVICE.credentials["url"] + '/oauth/token', data=form, headers=headers)
token = r.json()['access_token']
return token
# Helper that Returns the URL of the destination.
def _getDestinationURL(token):
headers = {'Authorization': 'Bearer ' + token}
r = requests.get(DESTINATION_SERVICE.credentials["uri"] +
'/destination-configuration/v1/destinations/' + DESTINATION, headers=headers)
destination = r.json()
return destination["destinationConfiguration"]["URL"]
def getURL():
# Fetch URL of the Destination
destination_token = getAccessToken(
DESTINATION_CREDENTIALS, DESTINATION_SERVICE)
url = _getDestinationURL(destination_token)
return url
def getProxy():
data = {}
connectivity_token = getAccessToken(
CONNECTIVITY_CREDENTIALS, CONNECTIVITY_SERVICE)
# Setting proxies and header for the Destination that needs to be called.
headers = {
'Proxy-Authorization': 'Bearer ' + connectivity_token}
# connection['headers'] = str(headers)
# proxy
proxies = {
"http": CONNECTIVITY_PROXY
}
# connection['proxies'] = str(proxies)
data['headers'] = headers
data['proxies'] = proxies
return data
def makeRequest(request,endpoint):
# Get destination URL
url = getURL()
#Get proxy parameters
connection = getProxy()
# Call the on-prem process_query service.
r = requests.post(url+endpoint,
proxies=connection['proxies'], headers=connection['headers'],
verify=False, timeout=10)
return json.loads(r.text)
# Routes
@app.route('/process_query', methods=['POST', 'GET'])
def process_query():
responseText = makeRequest(request,'/process_query.xsjs')
return jsonify(responseText)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug= True)
---
applications:
- memory: 128MB
name: demo_app
disk_quota: 256MB
random-route: true
services:
- destination_service
- uaa_service
- connectivity_service
Flask
requests
cfenv
web: python app.py
python-3.6.6
cf push demo_app -u none
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
26 | |
13 | |
12 | |
11 | |
9 | |
9 | |
7 | |
5 | |
5 | |
5 |