LA_
LA_

Reputation: 20409

How to access GAE datastore property with variable usage instead of actual name?

I have a number of lines like

if last_name:
    person.last_name = hashlib.sha512(last_name + salt).hexdigest()
if first_name:
    person.first_name = hashlib.sha512(first_name + salt).hexdigest()

I would like to write a function to simplify the code. But how can I use person.<variablename>?

Upvotes: 1

Views: 78

Answers (2)

Nick Johnson
Nick Johnson

Reputation: 101139

If you're going to enumerate properties individually like in Shay's example, a much more readable solution is to just abstract your code into a function:

def poorly_salted_hash(value, salt):
  return hashlib.sha512(value + salt).hexdigest()

person.first_name = poorly_salted_hash(first_name, salt)
person.last_name = poorly_salted_hash(last_name, salt)

If you're wondering why I'm calling the function "poorly salted hash", that's because this isn't a good way to salt a hash: you should use a construct like HMAC, which is provided by the Python hmac library. It's rather odd - to say the least - to be hashing someone's first and last names, though, so I don't know what your security goals are here.

Upvotes: 0

Shay Erlichmen
Shay Erlichmen

Reputation: 31928

def set_hash(entity, name, value):
  if value:
    setattr(entity, name, hashlib.sha512(value + salt).hexdigest())


set_hash(person, "last_name", last_name)
set_hash(person, "first_name", first_name)

Upvotes: 2

Related Questions