def get(self): import pipeline # Break circular dependency if pipeline._ENFORCE_AUTH: if not users.is_current_user_admin(): logging.debug('User is not admin: %r', users.get_current_user()) self.response.out.write('Forbidden') self.response.set_status(403) return # XSRF protection if (not pipeline._DEBUG and self.request.headers.get('X-Requested-With') != 'XMLHttpRequest'): logging.debug('Request missing X-Requested-With header') self.response.out.write('Request missing X-Requested-With header') self.response.set_status(403) return self.json_response = {} try: self.handle() output = simplejson.dumps(self.json_response, cls=util.JsonEncoder) except Exception, e: self.json_response.clear() self.json_response['error_class'] = e.__class__.__name__ self.json_response['error_message'] = str(e) self.json_response['error_traceback'] = traceback.format_exc() output = simplejson.dumps(self.json_response, cls=util.JsonEncoder)
def to_json_str(self): """Convert data to json string representation. Returns: json representation as string. """ json = self.to_json() try: return simplejson.dumps(json, sort_keys=True, cls=JsonEncoder) except: logging.exception("Could not serialize JSON: %r", json) raise
def get_value_for_datastore(self, model_instance): """Gets value for datastore. Args: model_instance: instance of the model class. Returns: datastore-compatible value. """ value = super(JsonProperty, self).get_value_for_datastore(model_instance) if not value: return None json_value = value if not isinstance(value, dict): json_value = value.to_json() if not json_value: return None return datastore_types.Text(simplejson.dumps( json_value, sort_keys=True, cls=JsonEncoder))
def get_value_for_datastore(self, model_instance): """Gets value for datastore. Args: model_instance: instance of the model class. Returns: datastore-compatible value. """ value = super(JsonProperty, self).get_value_for_datastore(model_instance) if not value: return None json_value = value if not isinstance(value, dict): json_value = value.to_json() if not json_value: return None return datastore_types.Text( simplejson.dumps(json_value, sort_keys=True, cls=JsonEncoder))
class JsonHandler(webapp.RequestHandler): """Base class for JSON handlers for user interface. Sub-classes should implement the 'handle' method. They should put their response data in the 'self.json_response' dictionary. Any exceptions raised by the sub-class implementation will be sent in a JSON response with the name of the error_class and the error_message. """ def __init__(self, *args): """Initializer.""" super(JsonHandler, self).__init__(*args) self.json_response = {} def base_path(self): """Base path for all mapreduce-related urls. JSON handlers are mapped to /base_path/command/command_name thus they require special treatment. Raises: BadRequestPathError: if the path does not end with "/command". Returns: The base path. """ path = self.request.path base_path = path[:path.rfind("/")] if not base_path.endswith("/command"): raise BadRequestPathError( "Json handlers should have /command path prefix") return base_path[:base_path.rfind("/")] def _handle_wrapper(self): """The helper method for handling JSON Post and Get requests.""" if self.request.headers.get("X-Requested-With") != "XMLHttpRequest": logging.error("Got JSON request with no X-Requested-With header") self.response.set_status( 403, message="Got JSON request with no X-Requested-With header") return self.json_response.clear() try: self.handle() except errors.MissingYamlError: logging.debug("Could not find 'mapreduce.yaml' file.") self.json_response.clear() self.json_response["error_class"] = "Notice" self.json_response["error_message"] = "Could not find 'mapreduce.yaml'" except Exception, e: logging.exception("Error in JsonHandler, returning exception.") # TODO(user): Include full traceback here for the end-user. self.json_response.clear() self.json_response["error_class"] = e.__class__.__name__ self.json_response["error_message"] = str(e) self.response.headers["Content-Type"] = "text/javascript" try: output = simplejson.dumps(self.json_response, cls=json_util.JsonEncoder) # pylint: disable=broad-except except Exception, e: logging.exception("Could not serialize to JSON") self.response.set_status(500, message="Could not serialize to JSON") return