I want to save the string data into object. But I am getting error. Moreover, json.loads(st)
not working for me.
import boto3
import os
import json
def handler(event,context):
client = boto3.client('s3')
bucketname = os.getenv('bucketname')
response = client.get_object (
Bucket = bucketname,
Key = 'constants.py')
text = response['Body'].read()
st = text.decode('utf-8').replace("'",'"')
return st
This is the output I want it in an object so that I can treat it as contants file and use it in other files.
"NAME_SPACE = \"S2MohammadHassanNS\"\nURL_AVAILABILITY = \"Availability\"\nURL_LATENCY = \"Latency\"\nURLs = [\"google.com\",\"pahe.li\",\"bbc.com\"]\nAVAILABILITY_THRESHOLD = 1\nLATENCY_THRESHOLD = 0.22"
CodePudding user response:
The format is quite easy for you to just manually split the values. I'm using ast.literal_eval
to convert to Python objects as it's safer than just the plain eval
.
from ast import literal_eval
output = {}
for line in st.splitlines():
var, value = line.split(' = ', 1)
output[var] = literal_eval(value)
Gives the output:
{'NAME_SPACE': 'S2MohammadHassanNS', 'URL_AVAILABILITY': 'Availability', 'URL_LATENCY': 'Latency', 'URLs': ['google.com', 'pahe.li', 'bbc.com'], 'AVAILABILITY_THRESHOLD': 1, 'LATENCY_THRESHOLD': 0.22}