def handle_exception(self, exception, debug): # If the exception is a HTTPException, use its error code. # Otherwise use a generic 500 error code. if isinstance(exception, webapp2.HTTPException): # Set a custom message. logging.getLogger("error").error('An error occurred %s', exception.code) try: json.loads(exception.args) self.RespondJSON(exception.args) except ValueError: self.response.write('An error occurred') self.response.set_status(exception.code) elif isinstance(exception, HttpError): try: # Load Json body. error_content = json.loads(exception.content) logging.exception("HTTP error %s %s", error_content.get('code'), error_content.get('message')) self.response.set_status(error_content.get('code', 500)) self.response.write(error_content.get('message', 'An error occurred')) except ValueError: # Could not load Json body. logging.getLogger("error").error("HTTP error %s %s", exception.resp.status, exception.resp.reason) self.response.set_status(exception.resp.status) self.response.write(exception.resp.reason) else: message = 'An error occurred' logging.getLogger("error").error('%s : %s', message, exception, exc_info=True) self.response.write(message) self.response.set_status(500)
def RequestJSON(self): """Load the request body as JSON. Returns: Request body loaded as JSON or None if there is no request body. """ if self.request.body: return json.loads(self.request.body)
def get(self): """Called when HTTP GET requests are received by the web application. Use the query parameter file_id to fetch the required file's metadata then content and return it as a JSON object. Since DrEdit deals with text files, it is safe to dump the content directly into JSON, but this is not the case with binary files, where something like Base64 encoding is more appropriate. """ # Create a Drive service service = self.CreateDrive() if service is None: return try: # Requests are expected to pass the file_id query parameter. file_id = self.request.get('file_id') logging.info('Get file %s', file_id) if file_id: # Fetch the file metadata by making the service.files().get method of # the Drive API. f = service.files().get(fileId=file_id).execute() downloadUrl = f.get('downloadUrl') # If a download URL is provided in the file metadata, use it to make an # authorized request to fetch the file ontent. Set this content in the # data to return as the 'content' field. If there is no downloadUrl, # just set empty content. if downloadUrl: logging.debug('Downloading the file from %s', downloadUrl) resp, raw_content = service._http.request(downloadUrl) logging.debug('Response status : %s', resp.status) logging.debug('Raw content : %s', raw_content) if resp and resp.status == int(200) and raw_content: try: json_content = json.loads(raw_content) f['content'] = json_content['content'] f['video'] = json_content['video'] f['syncNotesVideo'] = json_content['syncNotesVideo'] except ValueError: logging.info("ValueError when decoding raw content in JSON") self.get_empty_file(f) else: logging.debug("No content or error response") self.get_empty_file(f) else: logging.debug('No download URL') self.get_empty_file(f) else: f = None # Generate a JSON response with the file data and return to the client. self.RespondJSON(f) except AccessTokenRefreshError: # Catch AccessTokenRefreshError which occurs when the API client library # fails to refresh a token. This occurs, for example, when a refresh token # is revoked. When this happens the user is redirected to the # Authorization URL. logging.info('AccessTokenRefreshError') return self.abort(401)
def ParseJsonState(self, state): """Parse a state parameter that is JSON. Args: state: State parameter to parse """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', []))
def ServiceDecoratedView(handler, view=view): service = CreateDrive(handler) if handler.request.body: data = json.loads(handler.request.body) else: data = None response_data = json.dumps(view(handler, service, data)) handler.response.headers['Content-Type'] = 'application/json' handler.response.out.write(response_data)
def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ state_data = json.loads(state) self.action = state_data['action'] self.ids = map(str, state_data.get('ids', []))
def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ if state: state_data = json.loads(state) self.action = state_data["action"] self.ids = map(str, state_data.get("ids", [])) else: self.action = "create" self.ids = []
def __init__(self, state): """Create a new instance of drive state. Parse and load the JSON state parameter. Args: state: State query parameter as a string. """ if state: state_data = json.loads(state) self.action = state_data['action'] if 'folderId' in state_data: self.parent = state_data['folderId'] self.ids = map(str, state_data.get('ids', [])) else: self.action = 'create' self.parent = [] logging.debug('Create Drive state, parent %s, action %s', unicode(self.parent) if hasattr(self, 'parent') else None, self.action)
def get_file(self, file_id): service = self.CreateDrive() if service is None: return # Requests are expected to pass the file_id query parameter. logging.info('Get file %s', file_id) if file_id: # Fetch the file metadata by making the service.files().get method of # the Drive API. f = service.files().get(fileId=file_id).execute() downloadUrl = f.get('downloadUrl') # If a download URL is provided in the file metadata, use it to make an # authorized request to fetch the file ontent. Set this content in the # data to return as the 'content' field. If there is no downloadUrl, # just set empty content. if downloadUrl: logging.debug('Downloading the file from %s', downloadUrl) resp, raw_content = service._http.request(downloadUrl) logging.debug('Response status : %s', resp.status) logging.debug('Raw content : %s', raw_content) if resp and resp.status == int(200) and raw_content: try: json_content = json.loads(raw_content) f.update(json_content) except ValueError: logging.info( "ValueError when decoding raw content in JSON") f.update(FileUtils.get_empty_file()) else: logging.debug("No content or error response") f.update(FileUtils.get_empty_file()) else: logging.debug('No download URL') f.update(FileUtils.get_empty_file()) else: f = None # Generate a JSON response with the file data and return to the client. return f
def get_file(self, file_id): service = self.CreateDrive() if service is None: return # Requests are expected to pass the file_id query parameter. logging.info('Get file %s', file_id) if file_id: # Fetch the file metadata by making the service.files().get method of # the Drive API. f = service.files().get(fileId=file_id).execute() downloadUrl = f.get('downloadUrl') # If a download URL is provided in the file metadata, use it to make an # authorized request to fetch the file ontent. Set this content in the # data to return as the 'content' field. If there is no downloadUrl, # just set empty content. if downloadUrl: logging.debug('Downloading the file from %s', downloadUrl) resp, raw_content = service._http.request(downloadUrl) logging.debug('Response status : %s', resp.status) logging.debug('Raw content : %s', raw_content) if resp and resp.status == int(200) and raw_content: try: json_content = json.loads(raw_content) f.update(json_content) except ValueError: logging.info("ValueError when decoding raw content in JSON") f.update(FileUtils.get_empty_file()) else: logging.debug("No content or error response") f.update(FileUtils.get_empty_file()) else: logging.debug('No download URL') f.update(FileUtils.get_empty_file()) else: f = None # Generate a JSON response with the file data and return to the client. return f