Warning
This documentation does not refer to the most recent version of Pylons. Current Documentation
0001"""Custom Decorators, currently ``jsonify``, ``validate``, and 2 REST decorators"""
0002import types
0003import simplejson as json
0004import formencode.api as api
0005from formencode import htmlfill
0006import pylons
0007from pylons.decorator import decorator
0008import rest
0009
0010def jsonify(func, *args, **kw):
0011 """Action decorator that formats output for JSON
0012
0013 Given a function that will return content, this decorator will
0014 turn the result into JSON, with a content-type of 'text/javascript'
0015 and output it.
0016
0017 """
0018 response = pylons.Response()
0019 response.headers['Content-Type'] = 'text/javascript'
0020 response.content.append(json.dumps(func(*args, **kw)))
0021 return response
0022jsonify = decorator(jsonify)
0023
0024def validate(schema=None, validators=None, form=None):
0025 """Validate input either for a FormEncode schema, or individual validators
0026
0027 Given a form schema or dict of validators, validate will attempt to validate
0028 the schema or validator list.
0029
0030 If validation was succesfull, the valid result dict will be saved as
0031 ``self.form_results``. Otherwise, the action will be re-run as if it was a
0032 GET, and the output will be filled by FormEncode's htmlfill to fill in the
0033 form field errors.
0034
0035 Example::
0036
0037 class SomeController(BaseController):
0038
0039 def create(self, id):
0040 return render_response('/myform.myt')
0041
0042 @validate(schema=model.forms.myshema(), form='create')
0043 def update(self, id):
0044 # Do something with self.form_results
0045 pass
0046
0047 """
0048 def validate(func, self, *args, **kwargs):
0049 defaults, errors = {}, {}
0050 if not pylons.request.method == 'POST':
0051 return func(self, *args, **kwargs)
0052 defaults.update(pylons.request.POST)
0053 if schema:
0054 try:
0055 self.form_result = schema.to_python(defaults)
0056 except api.Invalid, e:
0057 errors = e.unpack_errors()
0058 if validators:
0059 if isinstance(validators, dict):
0060 for field, validator in validators.iteritems():
0061 try:
0062 self.form_result[field] = validator.to_python(defaults[field] or None)
0064 except api.Invalid, error:
0065 errors[field] = error
0066 if errors:
0067 pylons.request.environ['REQUEST_METHOD'] = 'GET'
0068 pylons.request.environ['pylons.routes_dict']['action'] = form
0069 response = self._dispatch_call()
0070 form_content = "".join(response.content)
0071 response.content = [htmlfill.render(form_content, defaults, errors)]
0072 return response
0073 return func(self, *args, **kwargs)
0074 return decorator(validate)
0075
0076__all__ = ['jsonify', 'validate', 'rest']