Skip to content

Instantly share code, notes, and snippets.

@danielwatson6
Created February 4, 2014 23:29
Show Gist options
  • Save danielwatson6/8814575 to your computer and use it in GitHub Desktop.
Save danielwatson6/8814575 to your computer and use it in GitHub Desktop.
### Code for passing through edit pages
# Handle a PUT request.
def put(self, *args):
BaseController.put(self, *args)
# Form is a dictionary with elements like
# property_name: list_of_validators.
form = self.model.form
# Models must have a form. There are validators like
# required, optional, etc. so that all properties can
# be validated.
assert form is not None
# Call self.request.get() for all given inputs. Returns
# a dictionary (property_name: user_input).
data = self.get_data(*form.keys())
try:
# Get the entity, given its id.
# NOTE: The first argument is the resource id.
resource = self.get_resource(list(args)[0])
assert resource is not None
for name, value in data.items():
# The value must be different from the existing one.
if value != getattr(resource, name):
try:
# Iterate through all the validators for the given field.
for validator in form[name]:
# NOTE: Validators return a value, possibly coerced.
value = validator(value)
# If all validation passes for the given field, the new value
# will successfully replace the old one.
setattr(resource, name, value)
# If validation fails, an IOError is raised, so if the
# new value is bad, the old value remains unchanged.
except IOError: pass
resource.put()
# Resource.link() is the URL to its show page.
return self.redirect(resource.link())
# If the resource does not exist, the user probably wants
# the new page instead of this one. (Or should this be self.error(404)?)
except AssertionError:
self.redirect('/%ss/new' % self._name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment