def file_download(self, request): """ Called when GET request specifies a filename to retrieve. """ logger.debug(vars(request)) response = self.session.get(request.href, params=request.params, headers=request.headers, stream=True) if response.status_code == 200: logger.debug("Streaming to file... Content length: {}".format( len(response.content))) try: path = os.path.abspath(request.filename) logger.debug("Operation: {}, saving to file: {}".format( request.href, path)) with open(path, "wb") as handle: for chunk in response.iter_content(chunk_size=1024): if chunk: handle.write(chunk) handle.flush() except IOError as e: raise IOError('Error attempting to save to file: {}'.format(e)) result = SMCResult(response) result.content = path return result else: raise SMCOperationFailure(response)
def file_upload(user_session, method, request): """ Perform a file upload PUT/POST to SMC. Request should have the files attribute set which will be an open handle to the file that will be binary transfer. :param Session user_session: session object :param str method: method to use, could be put or post :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult """ logger.debug('Upload: %s', vars(request)) http_command = getattr(user_session.session, method.lower()) try: response = http_command(request.href, params=request.params, files=request.files) except AttributeError: raise TypeError('File specified in request was not readable: %s' % request.files) else: if response.status_code in (200, 201, 202, 204): logger.debug('Success sending file in elapsed time: %s', response.elapsed) return SMCResult(response, user_session=user_session) raise SMCOperationFailure(response)
def file_upload(self, request): """ Perform a file upload POST to SMC. Request should have the files attribute set which will be an open handle to the file that will be binary transfer. """ logger.debug(vars(request)) response = self.session.post(request.href, params=request.params, files=request.files) if response.status_code == 202: logger.debug('Success sending file in elapsed time: {}'.format( response.elapsed)) return SMCResult(response) raise SMCOperationFailure(response)
def file_upload(self, method, request): """ Perform a file upload PUT/POST to SMC. Request should have the files attribute set which will be an open handle to the file that will be binary transfer. """ logger.debug('Upload: %s', vars(request)) command = getattr(self.session, method.lower()) response = command(request.href, params=request.params, files=request.files) if response.status_code in (201, 202, 204): logger.debug('Success sending file in elapsed time: %s', response.elapsed) return SMCResult(response, domain=self.session_domain) raise SMCOperationFailure(response)
def file_download(user_session, request): """ Called when GET request specifies a filename to retrieve. :param Session user_session: session object :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult """ logger.debug('Download file: %s', vars(request)) response = user_session.session.get(request.href, params=request.params, headers=request.headers, stream=True) if response.status_code == 200: logger.debug('Streaming to file... Content length: %s', len(response.content)) try: path = os.path.abspath(request.filename) logger.debug('Operation: %s, saving to file: %s', request.href, path) with open(path, "wb") as handle: for chunk in response.iter_content(chunk_size=1024): if chunk: handle.write(chunk) handle.flush() except IOError as e: raise IOError('Error attempting to save to file: {}'.format(e)) result = SMCResult(response, user_session=user_session) result.content = path return result else: raise SMCOperationFailure(response)
def send_request(self, method, request): """ Send request to SMC """ if self.session: try: method = method.upper() if method else '' if method == SMCAPIConnection.GET: if request.filename: #File download request return self.file_download(request) response = self.session.get(request.href, params=request.params, headers=request.headers, timeout=self.timeout) response.encoding = 'utf-8' logger.debug(vars(response)) counters.update(read=1) if response.status_code not in (200, 304): raise SMCOperationFailure(response) elif method == SMCAPIConnection.POST: if request.files: #File upload request return self.file_upload(request) response = self.session.post( request.href, #data=json.dumps(request.json), json=request.json, headers=request.headers, params=request.params) response.encoding = 'utf-8' logger.debug(vars(response)) counters.update(create=1) if response.status_code not in (200, 201, 202): # 202 is asynchronous response with follower link raise SMCOperationFailure(response) elif method == SMCAPIConnection.PUT: #Etag should be set in request object request.headers.update(Etag=request.etag) response = self.session.put( request.href, #data=json.dumps(request.json), json=request.json, params=request.params, headers=request.headers) logger.debug(vars(response)) counters.update(update=1) if response.status_code != 200: raise SMCOperationFailure(response) elif method == SMCAPIConnection.DELETE: response = self.session.delete(request.href) response.encoding = 'utf-8' counters.update(delete=1) if response.status_code not in (200, 204): raise SMCOperationFailure(response) else: #Unsupported method return SMCResult(msg='Unsupported method: %s' % method) except SMCOperationFailure: raise except requests.exceptions.RequestException as e: raise SMCConnectionError( "Connection problem to SMC, ensure the " "API service is running and host is correct: %s, " "exiting." % e) else: return SMCResult(response) else: raise SMCConnectionError( "No session found. Please login to continue")
def send_request(self, method, request): """ Send request to SMC """ if self.session: try: method = method.upper() if method else '' if method == SMCAPIConnection.GET: if request.filename: # File download request return self.file_download(request) response = self.session.get(request.href, params=request.params, headers=request.headers, timeout=self.timeout) response.encoding = 'utf-8' logger.debug('GET %s: %s', request.href, vars(response)) counters.update(read=1) if response.status_code not in (200, 204, 304): raise SMCOperationFailure(response) elif method == SMCAPIConnection.POST: if request.files: # File upload request return self.file_upload(method, request) response = self.session.post( request.href, json=request.json if request.json else None, headers=request.headers, params=request.params) response.encoding = 'utf-8' logger.debug('POST %s: %s', request.href, vars(response)) counters.update(create=1) if response.status_code not in (200, 201, 202): # 202 is asynchronous response with follower link raise SMCOperationFailure(response) elif method == SMCAPIConnection.PUT: if request.files: # File upload request return self.file_upload(method, request) # Etag should be set in request object request.headers.update(Etag=request.etag) logger.debug('PUT: %s', request) response = self.session.put(request.href, json=request.json, params=request.params, headers=request.headers) logger.debug(vars(response)) counters.update(update=1) if response.status_code != 200: raise SMCOperationFailure(response) elif method == SMCAPIConnection.DELETE: response = self.session.delete(request.href, headers=request.headers) counters.update(delete=1) # Conflict (409) if ETag is not current if response.status_code in (409, ): req = self.session.get(request.href) etag = req.headers.get('ETag') response = self.session.delete( request.href, headers={'if-match': etag}) response.encoding = 'utf-8' logger.debug('DELETE %s: %s', request.href, vars(response)) if response.status_code not in (200, 204): raise SMCOperationFailure(response) else: # Unsupported method return SMCResult(msg='Unsupported method: %s' % method) except SMCOperationFailure as error: if error.code in (401, ): self._session.refresh() return self.send_request(method, request) raise error except requests.exceptions.RequestException as e: raise SMCConnectionError( 'Connection problem to SMC, ensure the ' 'API service is running and host is correct: %s, ' 'exiting.' % e) else: return SMCResult(response, domain=self.session_domain) else: raise SMCConnectionError( "No session found. Please login to continue")
def send_request(user_session, method, request): """ Send request to SMC :param Session user_session: session object :param str method: method for request :param SMCRequest request: request object :raises SMCOperationFailure: failure with reason :rtype: SMCResult """ if user_session.session: session = user_session.session # requests session try: method = method.upper() if method else '' if method == GET: if request.filename: # File download request return file_download(user_session, request) response = session.get(request.href, params=request.params, headers=request.headers, timeout=user_session.timeout) response.encoding = 'utf-8' counters.update(read=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 204, 304): raise SMCOperationFailure(response) elif method == POST: if request.files: # File upload request return file_upload(user_session, method, request) response = session.post(request.href, data=json.dumps(request.json, cls=CacheEncoder), headers=request.headers, params=request.params) response.encoding = 'utf-8' counters.update(create=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 201, 202): # 202 is asynchronous response with follower link raise SMCOperationFailure(response) elif method == PUT: if request.files: # File upload request return file_upload(user_session, method, request) # Etag should be set in request object request.headers.update(Etag=request.etag) response = session.put(request.href, data=json.dumps(request.json, cls=CacheEncoder), params=request.params, headers=request.headers) counters.update(update=1) if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code != 200: raise SMCOperationFailure(response) elif method == DELETE: response = session.delete(request.href, headers=request.headers) counters.update(delete=1) # Conflict (409) if ETag is not current if response.status_code in (409, ): req = session.get(request.href) etag = req.headers.get('ETag') response = session.delete(request.href, headers={'if-match': etag}) response.encoding = 'utf-8' if logger.isEnabledFor(logging.DEBUG): debug(response) if response.status_code not in (200, 204): raise SMCOperationFailure(response) else: # Unsupported method return SMCResult(msg='Unsupported method: %s' % method, user_session=user_session) except SMCOperationFailure as error: if error.code in (401, ): user_session.refresh() return send_request(user_session, method, request) raise error except requests.exceptions.RequestException as e: raise SMCConnectionError( 'Connection problem to SMC, ensure the API ' 'service is running and host is correct: %s, exiting.' % e) else: return SMCResult(response, user_session=user_session) else: raise SMCConnectionError('No session found. Please login to continue')