I am using Thrift for a micro-service written in python.
I am returning a dictionary in python which can contain NULL
values.
This is the code for my Python response handler:
def response(id, token):
user_record = usertable.objects.get(uid = id)
if user_record.token == token:
response = dict(
pa_uid = user_record.pa_uid,
pa_token = user_record.pa_token,
dev_id = user.dev_id
)
return response
The response
function is the returning a dictionary and the dev_id
key has a NULL
value in many cases.
How can I to handle this in Thrift?
This is the code in my Thrift file:
service Calculator extends shared.SharedService {
map<string,string> response(1:string id, 2:string token),
}
When the dev_id
key has a NULL
value Thrift does not return a dictionary and an error is thrown by the Thrift Client.
There are 2 ways you can do this:
The ternary conditional operator
You can use the ternary conditional operator in the dev_id
assignment.
dev_id = user.dev_id if user.dev_id != None else 'not_found'
Now u can check for 'not_found' value in the dictionary and handle it appropriately.
The or
logical operator
The other option is to use or
in assignment as Tom Barron has answered
dev_id = user.dev_id or 'no_dev'
Note: The use of or
doesn't eliminate the corner case where the user.dev_id
can have a falsy value like 0
in case of number or empty string in case of strings. Such falsy values will trigger or
and assign 'no_dev'
to dev_id
. If such falsy values needs to be preserved then use the ternary conditional operator.