/servicios_web/gae/django-guestbook/src/django/contrib/formtools/utils.py

https://github.com/crisbar/curso_python_dga_11 · Python · 63 lines · 38 code · 9 blank · 16 comment · 16 complexity · c824cef34e0b9aa3ee262428786a936d MD5 · raw file

  1. try:
  2. import cPickle as pickle
  3. except ImportError:
  4. import pickle
  5. from django.conf import settings
  6. from django.forms import BooleanField
  7. from django.utils.crypto import salted_hmac
  8. from django.utils.hashcompat import md5_constructor
  9. def security_hash(request, form, *args):
  10. """
  11. Calculates a security hash for the given Form instance.
  12. This creates a list of the form field names/values in a deterministic
  13. order, pickles the result with the SECRET_KEY setting, then takes an md5
  14. hash of that.
  15. """
  16. import warnings
  17. warnings.warn("security_hash is deprecated; use form_hmac instead",
  18. PendingDeprecationWarning)
  19. data = []
  20. for bf in form:
  21. # Get the value from the form data. If the form allows empty or hasn't
  22. # changed then don't call clean() to avoid trigger validation errors.
  23. if form.empty_permitted and not form.has_changed():
  24. value = bf.data or ''
  25. else:
  26. value = bf.field.clean(bf.data) or ''
  27. if isinstance(value, basestring):
  28. value = value.strip()
  29. data.append((bf.name, value))
  30. data.extend(args)
  31. data.append(settings.SECRET_KEY)
  32. # Use HIGHEST_PROTOCOL because it's the most efficient. It requires
  33. # Python 2.3, but Django requires 2.4 anyway, so that's OK.
  34. pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
  35. return md5_constructor(pickled).hexdigest()
  36. def form_hmac(form):
  37. """
  38. Calculates a security hash for the given Form instance.
  39. """
  40. data = []
  41. for bf in form:
  42. # Get the value from the form data. If the form allows empty or hasn't
  43. # changed then don't call clean() to avoid trigger validation errors.
  44. if form.empty_permitted and not form.has_changed():
  45. value = bf.data or ''
  46. else:
  47. value = bf.field.clean(bf.data) or ''
  48. if isinstance(value, basestring):
  49. value = value.strip()
  50. data.append((bf.name, value))
  51. pickled = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)
  52. key_salt = 'django.contrib.formtools'
  53. return salted_hmac(key_salt, pickled).hexdigest()