How to dynamically create a JSON string? - python

I am trying to create a JSON string that I can send in a PUT request but build it dynamically. For example, once I am done, I'd like the string to look like this:
{
"request-id": 1045058,
"db-connections":
[
{
"db-name":"Sales",
"table-name":"customer"
}
]
}
I'd like to use constants for the keys, for example, for request-id, I'd like to use CONST_REQUEST_ID. So the keys will be,
CONST_REQUEST_ID = "request-id"
CONST_DB_CONNECTIONS = "db_connections"
CONST_DB_NAME = "db-name"
CONST_TABLE_NAME = "table-name"
The values for the keys will be taken from various variables. For example we can take value "Sales" from a var called dbname with the value "Sales".
I have tried json.load and getting exception.
Help would be appreciated please as I am a bit new to Python.

Create a normal python dictionary, then convert it to JSON.
raw_data = {
CONST_DB_NAME: getDbNameValue()
}
# ...
json_data = json.dumps(raw_data)
# Use json_data in your PUT request.

You can concat the string using + with variables.
CONST_REQUEST_ID = "request-id"
CONST_DB_CONNECTIONS = "db_connections"
CONST_DB_NAME = "db-name"
CONST_TABLE_NAME = "table-name"
request_id = "1045058"
db_name = "Sales"
table_name = 'customer'
json_string = '{' + \
'"' + CONST_REQUEST_ID + '": ' + request_id \
+ ',' + \
'"db-connections":' \
+ '[' \
+ '{' \
+ '"' + CONST_DB_NAME +'":"' + db_name + '",' \
+ '"' + CONST_TABLE_NAME + '":"' + table_name + '"' \
+ '}' \
+ ']' \
+ '}'
print json_string
And this is the result
python st_ans.py
{"request-id": 1045058,"db-connections":[{"db-name":"Sales","table-name":"customer"}]}

Related

authHash from another language to python

The following is the api guide from bold360 website
accountId=[your account id]
apiSettingId=[your API setting id]
apiKey=[your API key]
auth="$accountId:$apiSettingId:$( date +"%s" )000"
authHash="$auth:$( echo -n "$auth$apiKey" | openssl dgst -sha512 | sed 's/^.* //')"
Questions: I don't really understand the last two lines of code mean.
$( date +"%s" )000
2.( echo -n "$auth$apiKey" | openssl dgst -sha512 | sed 's/^.* //')
what does it look like if this is in Python?
I wrote this in python
def millsecond(dt):
epoch = dt.utcfromtimestamp(0)
return (dt-epoch).total_seconds() * 1000.0
def makeAuth():
# seconds = time.time()
timestamp = int(millsecond(dt.now()))
token = str(accountId) + ":" + str(settingID) + ":" + str(timestamp) + api_key
hash = hashlib.sha512(token.encode('utf-8')).hexdigest()
auth = str(accountId) + ":" + str(settingID) + ":" + str(timestamp) + ":" + str(hash)
return auth
authHash = makeAuth()
url_runReport = "https://api.boldchat.com/aid/[AccountID]/data/rest/json/v1/runReport?auth=[auth]&ReportType=0&Grouping=chat_type&FromDate=2023-01-27T00:00:00-08:00&ToDate=2023-01-27T23:59:59-08:00"
response_runReport = requests.get(url_runReport)
runReport_data = response_runReport.json()
my result always shows
{'Status': 'error', 'Message': 'Expired authorization'}
My guess is authhash is not correct. Can someone teach me how to code the authHash in python? Thanks

Casting result of an F function to an int

I have a simple Django application were I try to aggregate multiple values into an annotation for easier processing on the client side.
Basically, I need to sum the values of multiple columns into one.
For this I'm trying to use annotate with F functions:
qs = TimeReport.objects \
.filter(year=year, term=term) \
.annotate(
created_by_first_name=F('created_by__first_name'),
created_by_last_name=F('created_by__last_name'),
total_hours = F('master_thesis_supervision_hours')
+ F('semester_project_supervision_hours')
+ F('other_job_hours')
+ F('MAN_hours')
+ F('exam_proctoring_and_grading_hours')
+ F('class_teaching_exam_hours')
+ F('class_teaching_practical_work_hours')
+ F('class_teaching_preparation_hours')
+ F('class_teaching_teaching_hours'),
) \
.all().values()
Suprisingly, when I inspect the content of the calculated field, it does not contain anything:
list(qs)[0]['total_hours']
None
Trying to cast the result of the F function does not either:
...
total_hours = int(F('master_thesis_supervision_hours'))
+int(F('semester_project_supervision_hours'))
+ ...
I also tried to update the models.py to add a property:
#property
def total_hours(self):
return self.master_thesis_supervision_hours + self.class_teaching_total_hours + self.semester_project_supervision_hours + self.other_job_hours + self.MAN_hours + self.exam_proctoring_and_grading_hours
and update the views.py accordingly:
qs = TimeReport.objects \
.filter(year=year, term=term) \
.annotate(
created_by_first_name=F('created_by__first_name'),
created_by_last_name=F('created_by__last_name'),
total_hours = F('total_hours'),
) \
.all().values()
But I get the following error:
django.core.exceptions.FieldError: Cannot resolve keyword 'total_hours' into field.
What would be the correct way to do this?

The python operation database error

I use python operation postgresql database, the implementation of sql, it removed the quotation marks, resulting in inquiries failed, how to avoid?
def build_sql(self,table_name,keys,condition):
print(condition)
# condition = {
# "os":["Linux","Windows"],
# "client_type":["ordinary"],
# "client_status":'1',
# "offset":"1",
# "limit":"8"
# }
sql_header = "SELECT %s FROM %s" % (keys,table_name)
sql_condition = []
sql_range = []
sql_sort = []
sql_orederby = []
for key in condition:
if isinstance(condition[key],list):
sql_condition.append(key+" in ("+",".join(condition[key])+")")
elif key == 'limit' or key == 'offset':
sql_range.append(key + " " + condition[key])
else:
sql_condition.append(key + " = " + condition[key])
print(sql_condition)
print(sql_range)
sql_condition = [str(i) for i in sql_condition]
if not sql_condition == []:
sql_condition = " where " + " and ".join(sql_condition) + " "
sql = sql_header + sql_condition + " ".join(sql_range)
return sql
Error:
MySQL Error Code : column "winxp" does not exist
LINE 1: ...T * FROM ksc_client_info where base_client_os in (WinXP) and...
Mind you I do not have much Python experience, but basically you don't have single quotes in that sequence, so you either need to add those before passing it to function or for example during join(), like that:
sql_condition.append(key+" in ("+"'{0}'".format("','".join(condition[key]))+")")
You can see other solutions in those questions:
Join a list of strings in python and wrap each string in quotation marks
Add quotes to every list elements

Python: Get data through Thingspeak

I want to capture the sensor data through thingspeak.
I used the url provided with the api key in the browser:
http://api.thingspeak.com/update?key=MYKEY&field1=25&field2=75
I expect it will return field1 and field2, but the result below shows only the value of field1.
"channel":{
"id":202242,
"name":"DHT11",
"latitude":"0.0",
"longitude":"0.0",
"field1":"Temperature ( degC ) 1",
"field2":"Humidity ( % )",
"created_at":"2016-12-11T17:16:21Z",
"updated_at":"2016-12-11T18:12:00Z",
"last_entry_id":12
},
"feeds":[
{
"created_at":"2016-12-11T18:12:00Z",
"entry_id":12,
"field1":25
}
]
What step have I missed?
Try this approach:
Here you make request using APIs. You will find various API requests here.
import urllib2
import json
import time
READ_API_KEY=' '
CHANNEL_ID= ' '
while True:
TS = urllib2.urlopen("http://api.thingspeak.com/channels/%s/feeds/last.json?api_key=%s" \
% (CHANNEL_ID,READ_API_KEY))
response = TS.read()
data=json.loads(response)
a = data['created_at']
b = data['field1']
c = data['field2']
d = data['field3']
print a + " " + b + " " + c + " " + d
time.sleep(5)
TS.close()

Best way to write understandable and Python-friendly code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have this code
def testing1(terms, request):
dat = datetime.now(pytz.timezone(geo_timezone(request)))
__start = terms['year']+'-'+terms['month']+'-'+terms['day']+'T'+'00:00:00'+dat.strftime('%z')[:-2]+':'+dat.strftime('%z')[-2:]
__end = terms['year']+'-'+terms['month']+'-'+terms['day']+'T'+'23:59:59'+dat.strftime('%z')[:-2]+':'+dat.strftime('%z')[-2:]
return __start, __end
testing({"month":12,"day":1, "year":"2015"}, request)
But I have a interrogant, whats is the best way to write this code, readable and friendly for the others programers?
Any suggestion for write code extensive in one line like this?
This suggestion is readable?
def testing2(terms, request):
dat = datetime.now(pytz.timezone(geo_timezone(request)))
__start = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
'T' + '00:00:00' + dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
__end = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
'T' + '23:59:59' + dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
return __start, __end
The only hard part to read is where you build your string so I would use .format(). This way you can see the resulting layout and then all of the corresponding entries.
__start = '{}-{}-{}T00:00:00{}:{}'.format(terms['year'],
terms['month'],
terms['day'],
dat.strftime('%z')[:-2],
dat.strftime('%z')[-2:])
__end = '{}-{}-{}T23:59:59{}:{}'.format(terms['year'],
terms['month'],
terms['day'],
dat.strftime('%z')[:-2],
dat.strftime('%z')[-2:])
Personally, I'd go with that second block and call it a day. If you want, you could try aligning it into groups, or messing with str.format():
__start = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
'T00:00:00' + \
dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
__end = terms['year'] + '-' + terms['month'] + '-' + terms['day'] + \
'T23:59:59' + \
dat.strftime('%z')[:-2] + ':' + dat.strftime('%z')[-2:]
__start = ('{}-{}-{}'.format(terms['year'], terms['month'], terms['day']) +
'T00:00:00' +
'{}:{}'.format(dat.strftime('%z')[:-2], dat.strftime('%z')[-2:]))
__end = ('{}-{}-{}'.format(terms['year'], terms['month'], + terms['day']) +
'T23:59:59' +
'{}:{}'.format(dat.strftime('%z')[:-2], dat.strftime('%z')[-2:]))
You can try something like :
__start = ''.join([terms['year'], '-',
terms['month'], '-',
terms['day'], 'T',
'00:00:00',
dat.strftime('%z')[:-2], ':',
dat.strftime('%z')[-2:]
])
Parenthesis, brackets and braces will help you to keep your lines of code < 80 characters
(and here the join method of string objects is more efficient than operator +)
As your post is about coding style it's hard to not mention the PEP8 if you don't know it already.

Categories