This repository has been archived by the owner on Feb 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhello-atlas-cf.py
77 lines (68 loc) · 2.19 KB
/
hello-atlas-cf.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
"""
A first simple Cloud Foundry Flask app
Author: Ian Huston
License: See LICENSE.txt
"""
from flask import Flask
import os
import pprint
import json
from pymongo import MongoClient
from vcap_services import load_from_vcap_services
app = Flask(__name__)
# Get port from environment variable or choose 9099 as local default
port = int(os.getenv("PORT", 9099))
def try_atlas():
""" For Cloud Foundry, we need to look in the VCAP_SERVICES environment
this is a json doc like this:
{ <service-name> : [ { name:, credentials:, .. }, .. ], .. }
"""
result = {}
try:
vcap_services = os.getenv('VCAP_SERVICES')
services = json.loads(vcap_services)
for service_name in services.keys():
print(f'service_name={service_name}')
if service_name == "_":
continue
credentials = load_from_vcap_services(service_name)
result.update(credentials)
except Exception as err:
print( f'Error looking for VCAP_SERVICES {err}')
result['error']=err
return result
mongo_results = {}
try:
db = MongoClient( result['connectionString'] )
mongo_results["MongoClient"]= f'{db}'
mongo_results["server_info"]=db.server_info()
except Exception as err:
print( f'Error trying connection to Atlas: {err}')
result['atlas-error']=err
finally:
result['mongo']=mongo_results
return result
@app.route('/')
def hello_world():
print("Hello dare!")
pprint.PrettyPrinter().pprint( dict(os.environ))
#'Hello World! I am instance ' + str(os.getenv("CF_INSTANCE_INDEX", 0))
try_atlas_result = try_atlas()
return '''
<html>
<head>
<title>atlas-osb hello-mongo-env</title>
</head>
<body>
<h1>atlas-osb hello-mongo-env</h1>
<hr/>
<h3>try_atlas_result</h3>
<pre>''' + pprint.pformat(try_atlas_result,indent = 2) + '''</pre>
<hr/>
<h3>os.environ</h3>
<pre>''' + pprint.pformat(dict(os.environ),indent = 2) + '''</pre>
</body>
</html>'''
if __name__ == '__main__':
# Run the app, listening on all IPs with our chosen port number
app.run(host='0.0.0.0', port=port)