def __init__(self, host, cert, reason): self.host = host self.cert = cert self.reason = reason.rstrip() message = ('Host %s returned an invalid certificate (%s) %s' % (self.host, self.reason, self.cert)).rstrip() HTTPException.__init__(self, message)
def test_error_message_hidden_when_debug_is_false(self, mock_unpair, mock_status): mock_unpair.side_effect = HTTPException("HTTP Generic Exception") mock_status.side_effect = HTTPException("HTTP Generic Exception") data = {"latch_confirm": True} self.client.force_login(self.paired_user) response = self.client.post("/unpair/", data, follow=True) self.assertContains(response, "Error unpairing the account")
def test_profile_is_not_deleted_if_an_error_occurs(self, mock_unpair, mock_status): mock_unpair.side_effect = HTTPException("HTTP Generic Exception") mock_status.side_effect = HTTPException("HTTP Generic Exception") data = {"latch_confirm": True} self.client.force_login(self.paired_user) self.client.post("/unpair/", data, follow=True) self.assertEqual( UserProfile.objects.filter(user=self.paired_user).count(), 1)
def test_error_message_shown_when_debug_is_true(self, mock_pair, mock_status): mock_pair.side_effect = HTTPException("HTTP Generic Exception") mock_status.side_effect = HTTPException("HTTP Generic Exception") data = {"latch_pin": "correc"} self.client.force_login(self.unpaired_user) response = self.client.post("/pair/", data=data, follow=True) self.assertContains( response, "Error pairing the account: HTTP Generic Exception")
def uploadFile(self, fileName, url, fieldName='file1', params=[], verb='POST'): """ Upload a file with curl streaming it directly from disk """ ckey, cert = self.getKeyCert() capath = self.getCAPath() import pycurl c = pycurl.Curl() if verb == 'POST': c.setopt(c.POST, 1) elif verb == 'PUT': c.setopt(pycurl.CUSTOMREQUEST, 'PUT') else: raise HTTPException("Verb %s not sopported for upload." % verb) c.setopt(c.URL, url) fullParams = [(fieldName, (c.FORM_FILE, fileName))] fullParams.extend(params) c.setopt(c.HTTPPOST, fullParams) bbuf = BytesIO() hbuf = BytesIO() c.setopt(pycurl.WRITEFUNCTION, bbuf.write) c.setopt(pycurl.HEADERFUNCTION, hbuf.write) if capath: c.setopt(pycurl.CAPATH, capath) c.setopt(pycurl.SSL_VERIFYPEER, True) else: c.setopt(pycurl.SSL_VERIFYPEER, False) if ckey: c.setopt(pycurl.SSLKEY, ckey) if cert: c.setopt(pycurl.SSLCERT, cert) c.perform() hres = hbuf.getvalue() bres = bbuf.getvalue() rh = ResponseHeader(hres) c.close() if rh.status < 200 or rh.status >= 300: exc = HTTPException(bres) setattr(exc, 'req_data', fullParams) setattr(exc, 'url', url) setattr(exc, 'result', bres) setattr(exc, 'status', rh.status) setattr(exc, 'reason', rh.reason) setattr(exc, 'headers', rh.header) raise exc return bres
async def auth_client_side(request: Request): try: body_bytes = await request.body() auth_code = jsonable_encoder(body_bytes) idInfo = id_token.verify_oauth2_token(auth_code, requests.Request(), configuration.GOOGLE_CLIENT_ID) if idInfo["iss"] not in [ "accounts.google.com", "https://accounts.google.com" ]: raise ValueError("Wrong issuer.") accessTokenExpires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) dateExpires = datetime.utcnow() + accessTokenExpires print(idInfo) user = UserInDB( username=idInfo.get("email"), email=idInfo.get("email"), picture=idInfo.get("picture"), given_name=idInfo.get("given_name"), family_name=idInfo.get("family_name"), disabled=False, ) ret = insert_or_update_user(user) accessToken = create_access_token(data={"username": user.username}, expires_delta=accessTokenExpires, expires_date=dateExpires) return Token( access_token=accessToken, token_type="bearer", expires=accessTokenExpires, date_expires=dateExpires, ) except: return HTTPException(status.HTTP_400_BAD_REQUEST, "Unable to validate Google Login")
def create_user(self, username: str, password: str, session: str) -> str: """ Creates a user in the authentication server. --- Parameters: - username: The name string of the new user. - password: The password string of the new user. - session: The session id of the user creating the new user. Throws: - HTTPException: On an unhandled 500 error. """ form: str = urlencode({ 'username': username, 'password': password, 'session_id': session }) headers: dict = {'Content-type': 'application/x-www-form-urlencoded'} connection: HTTPConnection = self.__get_connection() connection.request('POST', '/users', form, headers) response: HTTPResponse = connection.getresponse() if response.status == 200: print("User created") if response.status == 400: raise ValueError if response.status == 401: print("You lack the rights to create a user") if response.status == 409: print("The user already exists") if response.status == 500: raise HTTPException('Server error') return ''
def revoke(self, username: str, right_name: str, session: str) -> str: """ Revokes a right from a user in the authentication server. --- Parameters: - username: The name string of the new user. - right_name: The name of the right to be revoked. - session: The session id of the user granting the right. Throws: - HTTPException: On an unhandled 500 error. """ form: str = urlencode({'session_id': session}) headers: dict = {'Content-type': 'application/x-www-form-urlencoded'} address = '/users/' + username + '/rights/' + right_name connection: HTTPConnection = self.__get_connection() connection.request('DELETE', address, form, headers) response: HTTPResponse = connection.getresponse() if response.status == 200: print("Right revoked") if response.status == 401: print("Session not found or inssuficient rights") if response.status == 404: print("User not found") if response.status == 500: raise HTTPException('Server error') return ''
def send(self, body): if self.__retry_settings.maximum_number_of_retries == 0: return self.__http_client.send_request(body) while True: wait_interval = self.__retry_settings.get_next_wait_interval( self.attempts) try: response = self.__http_client.send_request(body) if response.status in self.ErrorStatusCodes: raise HTTPException( "HttpStatusCode: {0}. Response contains server error.". format(response.status)) return response except socket.timeout: self.attempts += 1 if self.attempts > self.__retry_settings.maximum_number_of_retries: raise socket.timeout time.sleep(wait_interval.seconds) except HTTPException: self.attempts += 1 if self.attempts > self.__retry_settings.maximum_number_of_retries: raise HTTPException time.sleep(wait_interval.seconds)
def add_comment_to_alert(self, alert_id, comment='', share_irondome=False): self.logger.debug('Submitting comment: Alert ID={} Comment={} Share ' 'w/IronDome={}'.format(alert_id, comment, share_irondome)) req_body = { 'alert_id': alert_id, 'comment': comment, 'share_comment_with_irondome': share_irondome } response = self._http_request('POST', '/CommentOnAlert', body=json.dumps(req_body)) if response.status_code != 200: err_msg = self._get_error_msg_from_response(response) self.logger.error( 'Failed to add comment to alert ({}). The response failed with status code {}. The ' 'response was: {}'.format(alert_id, response.status_code, response.text)) raise HTTPException( 'Failed to add comment to alert {} ({}): {}'.format( alert_id, response.status_code, err_msg)) else: self.logger.debug( 'Successfully added comment to alert ({})'.format(alert_id)) return 'Submitted comment to IronDefense!'
def set_alert_status(self, alert_id, status='STATUS_NONE', comments='', share_irondome=False): self.logger.debug( 'Submitting status: Alert ID={} Status={} Comments={} Share ' 'w/IronDome={}'.format(alert_id, status, comments, share_irondome)) req_body = { 'alert_id': alert_id, 'status': 'STATUS_' + status.upper().replace(" ", "_"), 'comment': comments, 'share_comment_with_irondome': share_irondome } response = self._http_request('POST', '/SetAlertStatus', body=json.dumps(req_body)) if response.status_code != 200: err_msg = self._get_error_msg_from_response(response) self.logger.error( 'Failed to set status for alert ({}). The response failed with status code {}. The ' 'response was: {}'.format(alert_id, response.status_code, response.text)) raise HTTPException( 'Failed to set status for alert {} ({}): {}'.format( alert_id, response.status_code, err_msg)) else: self.logger.debug( 'Successfully submitted status for alert ({})'.format( alert_id)) return 'Submitted status to IronDefense!'
def test_shows_error_message_when_cant_connect_to_latch(self, mock_status): mock_status.side_effect = HTTPException("HTTP Generic Exception") self.client.force_login(self.paired_user) response = self.client.get("/status/") self.assertContains(response, "Latch connection error")
def __init__(self, status, reason, msg, sock, length, lengths): HTTPResponse.__init__(self, status, reason, msg) self.sock = sock self.size = int(length) for dupe in lengths: if int(dupe) != self.size: raise HTTPException("Conflicting Content-Length values")
def post(self, entity, name): jsonData = request.get_json(cache=False) attr = {} for key in jsonData: attr[key] = jsonData[key] print(key, ' = ', jsonData[key]) if (entity == 'person'): startNode = searchPerson.searchPerson(name) if (attr['entity_type'] == 'movie'): endNode = searchMovie.searchMovie(attr['movie.movieName']) createOperation.createHasRatedRelationship( startNode[0], endNode[0], attr['relationship.ratings']) createOperation.save('person', startNode[0]) elif (attr['entity_type'] == 'person' and attr['relationship'] == 'FRIEND'): endNode = searchPerson.searchPerson(attr['person.name']) createOperation.createFriendRelationship( startNode[0], endNode[0]) createOperation.save('person', startNode[0]) elif (attr['entity_type'] == 'person' and attr['relationship'] == 'TEACHES'): endNode = searchPerson.searchPerson(attr['person.name']) createOperation.createTeachesRelationship( startNode[0], endNode[0]) createOperation.save('person', startNode[0]) else: raise HTTPException("Value is not Valid") return jsonify(result='success')
def index(): form = LineConfigForm() configs_lines_api_url = os.path.join( current_app.config['DAC_HOST_URL'], current_app.config['DAC_API_CONFIGS_LINES_URL']) try: conn = HTTPConnection(current_app.config['DAC_HOST_URL']) conn.request("GET", configs_lines_api_url) resp = conn.getresponse() if resp.code == 200: data = json.loads(resp.read().decode()) else: raise HTTPException() except HTTPException: data = {} flash(_("Can not connect to DAC server.")) except ConnectionError: data = {} flash(_("Can not connect to DAC server.")) finally: conn.close() if data != {}: lines = [line for line in data['data']['configs'].keys()] configs = data['data']['configs'] else: lines = [] configs = {} return render_template('config_view.html', form=form, data=configs, lines=lines, totail_lines=form.line_no.choices)
def handler(event, _context): url = event.get('url') # read from environment variable if not present in event if not url: url = environ.get('URL') # if still not present, bail if not url: raise ValueError( f"Missing URL in environment variable or event: {event}") method = event.get('method', 'head').upper() timeout = float(event.get('timeout', 30.0)) # split URL by spaces and repeat checks url = sorted(url.split(' ')) for u in url: try: response = request(method, u, timeout=timeout) if response.status not in (200, 204): raise HTTPException() except Exception as e: _add_error(u, e) continue print(f"HTTP success code {response.status} contacting URL {u} " f"(headers: {response.headers})") if ERRORS: _publish_errors()
def call_url(url, method=HTTP_GET): response = getattr(requests, method)(url) if response.status_code != 200: raise HTTPException( f"External API responded with {response.status_code}") data_dict = json.loads(response.content) return data_dict
def get_replay_by_id(self, replay_id, battletag=None, hero=None, hero_level=None, team=None, winner=None, region=None, blizz_id=None): params = self.config.ReplayParams(battletag=battletag, hero=hero, hero_level=hero_level, team=team, winner=winner, region=region, blizz_id=blizz_id) response = requests.get( self.config.get_replay_url(replay_id), params={k: v for k, v in params._asdict().items() if v}) if response.status_code == 429: logger.info('') raise RateLimitExceeded elif response.status_code >= 300: msg = 'Received HTTP error {} when trying to retrieve Replay {}'.format( response.status_code, replay_id) logger.error(msg) raise HTTPException(msg) return response.json()
def request(self, path, post_data=None): """ Send a request for the path 'path'. Does a POST of post_data if given, else a GET of the given path. """ if not self._is_open: self.open() headers = {'Content-Type': 'application/json; charset=utf-8'} if type(post_data) == dict: post = json.dumps(post_data) else: post = post_data self._httpconn.request("GET" if post is None else "POST", path, post, headers) response = self._httpconn.getresponse() if response.status != 200: # Make sure we read the response body, or we won't be able to # re-use the connection for following request. response.read() self._log.write("{} request failed: {}: {}" \ .format(path, response.status, response.reason)) raise HTTPException(response.status, response.reason) return response
def update_analyst_ratings(self, alert_id, severity='SEVERITY_UNDECIDED', expectation='EXP_UNKNOWN', comments='', share_irondome=False): self.logger.debug( 'Submitting analyst rating: Alert ID={} Severity={} Expected={} Comments={} Share ' 'w/IronDome={}'.format(alert_id, severity, expectation, comments, share_irondome)) req_body = { 'alert_id': alert_id, 'analyst_severity': 'SEVERITY_' + severity.upper(), 'analyst_expectation': 'EXP_' + expectation.upper(), 'comment': comments, 'share_comment_with_irondome': share_irondome } response = self._http_request('POST', '/RateAlert', body=json.dumps(req_body)) if response.status_code != 200: err_msg = self._get_error_msg_from_response(response) self.logger.error( 'Failed to rate alert ({}). The response failed with status code {}. The response was: ' '{}'.format(alert_id, response.status_code, response.text)) raise HTTPException('Failed to rate alert {} ({}): {}'.format( alert_id, response.status_code, err_msg)) else: self.logger.debug( 'Successfully submitted rating for alert ({})'.format( alert_id)) return 'Submitted analyst rating to IronDefense!'
def create_user(self, username: str, passwd: str, session_id: str): """ Creates a user in the authentication server. --- Parameters: - username: The username string. - password: The password string. - session_id: The session id string. Throws: - BadRequestError: if the request is malformed. - UnauthorizedError: if the requestor does not meet the security requirements. - ConflictError: if a user with the given username already exists. - HTTPException: On an unhandled 500 error. """ form: str = urlencode({ 'username': username, 'password': passwd, 'session_id': session_id }) headers: dict = {'Content-type': 'application/x-www-form-urlencoded'} connection: HTTPConnection = self.__get_connection() connection.request('POST', '/users', form, headers) response: HTTPResponse = connection.getresponse() if response.status == 200: return if response.status == 400: raise BadRequestError() if response.status == 401: raise UnauthorizedError() if response.status == 409: raise ConflictError() if response.status == 500: raise HTTPException('Server error')
def _request(self, command, request_type='get', **kwargs): """ Send all requests to API """ # Add timeouts if were not set if not kwargs.get('timeout', None): kwargs['timeout'] = (self.connect_timeout, self.read_timeout) # Trying make request try: url = self.api_url + command if request_type == 'get': response = requests.get(url, **kwargs) elif request_type == 'post': response = requests.post(url, **kwargs) # If everything is ok, API return 200 with response data in json if response.ok: return response.json() # It response is not ok raise HTTPException('HTTP error (code: {})'.format(response.status_code)) except requests.exceptions.ReadTimeout: raise except requests.exceptions.ConnectTimeout: raise except requests.exceptions.ConnectionError: raise except requests.exceptions.HTTPError: raise except ValueError: raise
def get_response(self, url): """Grab the http.client response from a request. :param url: The URL of the page. """ # Enclose our file gathering process in a try-catch condition. try: # Split our URL into the three distinct portions. urlsplices = url_split(url) # Make a connection to the URL. conn = HTTPSConnection(urlsplices.domain) if urlsplices.scheme == 'https' \ else HTTPConnection(urlsplices.domain) # Make a simple request. conn.request('GET', urlsplices.path, headers=self.headers) # Gather our response. resp = conn.getresponse() # Return our data if we receive an HTTP 2XX or 3XX response code. if 199 < resp.status < 400: return resp # Otherwise raise an exception for anything else. raise HTTPException(f'HTTP {resp.code} {resp.reason}') except HTTPException as httpex: # Return an error message if we catch an exception. error(f'Unknown exception: {httpex}') return None
def revoke(self, username: str, right: str, session_id: str): """ Revoke a right to a user from the authentication server. --- Parameters: - username: The username string. - right: The right string. - session_id: The session id string. Throws: - UnauthorizedError: if the requestor does not meet the security requirements or no session was provided. - NotFoundError: if the user does not exist or the right does not exist. - HTTPException: On an unhandled 500 error. """ form: str = urlencode({ 'username': username, 'right': right, 'session_id': session_id }) headers: dict = {'Content-type': 'application/x-www-form-urlencoded'} connection: HTTPConnection = self.__get_connection() connection.request('DELETE', '/users/' + str(username) + '/rights/' + str(right), form, headers) response: HTTPResponse = connection.getresponse() if response.status == 200: return if response.status == 401: raise UnauthorizedError() if response.status == 404: raise NotFoundError() if response.status == 500: raise HTTPException('Server error')
def get_events(self, alert_id, limit=None, offset=None): self.logger.debug('Retrieving Events: Alert ID={}, Limit={} Offset={}'.format(alert_id, limit, offset)) req_body = { 'alert_id': alert_id } constraint = {} if limit is not None and limit != "": constraint['limit'] = int(limit) if offset is not None and offset != "": constraint['offset'] = int(offset) req_body['constraint'] = constraint response = self._http_request('POST', '/GetEvents', body=json.dumps(req_body)) if response.status_code != 200: err_msg = self._get_error_msg_from_response(response) self.logger.error('Failed to retrieve events with alert ID ({}). The response failed with status code {}. ' 'The response was: {}'.format(alert_id, response.status_code, response.text)) raise HTTPException('Failed to retrieve event with ID {} ({}): {}'.format(alert_id, response.status_code, err_msg)) else: self.logger.debug('Successfully retrieved events for alert ({})'.format(alert_id)) events = response.json() return events
def request(method, url, *, read_limit=None, **kwargs): """request performs an HTTP request and reads the entire response body. :param str method: HTTP method to request (e.g. 'GET', 'POST') :param str url: URL to request :param read_limit: maximum number of bytes to read from the body, or None for no limit :type read_limit: int or None :param kwargs: optional arguments defined by yield_response :return: Response object :rtype: Response :raises: HTTPException """ with yield_response(method, url, **kwargs) as response: try: body = response.read(read_limit) except HTTPException: raise except IOError as e: raise HTTPException(str(e)) from e return Response( response.url, response.status, _prepare_incoming_headers(response.headers), body, )
def report_observed_bad_activity(self, name, description='', ip='', domain='', activity_start_time='1970-01-01T00:00:00Z', activity_end_time='1970-01-01T00:00:00Z'): self.logger.debug('Submitting observed bad activity: Name={} Description={} IP={} Domain={} ' 'Activity Start Time={} Activity End Time={}'.format(name, description, ip, domain, activity_start_time, activity_end_time)) req_body = { 'name': name, 'description': description, 'ip': ip, 'domain': domain, 'activity_start_time': activity_start_time, 'activity_end_time': activity_end_time } response = self._http_request('POST', '/ReportObservedBadActivity', body=json.dumps(req_body)) if response.ok: self.logger.debug('Successfully submitted observed bad activity for IP={} and Domain={}'.format(ip, domain)) return 'Submitted observed bad activity to IronDefense!' else: err_msg = self._get_error_msg_from_response(response) self.logger.error('Failed to submit observed bad activity for IP={} and Domain={}. The response failed with' ' status code {}. The response was: {}' .format(ip, domain, response.status_code, response.text)) raise HTTPException('Failed to submit observed bad activity for IP={} and Domain={} ({}): {}' .format(ip, domain, response.status_code, err_msg))
def login(self, username: str, password: str) -> str: """ Logs in a user in the authentication server. --- Parameters: - username: The user name string. - password: The user password string. Returns: The session id string. Throws: - InvalidCredentialsError: If the credentials provided are not correct. - HTTPException: On an unhandled 500 error. """ form: str = urlencode({'username': username, 'password': password}) headers: dict = {'Content-type': 'application/x-www-form-urlencoded'} connection: HTTPConnection = self.__get_connection() connection.request('POST', '/sessions', form, headers) response: HTTPResponse = connection.getresponse() if response.status == 200: response_data_json = response.read() response_data = json.loads(response_data_json) return response_data['session_id'] if response.status == 401: raise InvalidCredentialsError() if response.status == 500: raise HTTPException('Server error') return ''
def has_right(self, username: str, right: str) -> bool: """ Determines whether a given user from the authentication server has a certain right or not. --- Parameters: - username: The user name string. - right: The right name. Returns: True if the user has the given right, False if not. Throws: - HTTPException: On an unhandled 500 error. """ form: str = urlencode({'username': username, 'right': right}) headers: dict = {'Content-type': 'application/x-www-form-urlencoded'} connection: HTTPConnection = self.__get_connection() connection.request('GET', '/users/' + str(username) + '/rights/' + str(right), form, headers) response: HTTPResponse = connection.getresponse() if response.status == 200: return True if response.status == 404: return False if response.status == 500: raise HTTPException('Server error') return False
async def send_data(data: Item): if not data: raise HTTPException(status_code=502, detail="数据发送错误") # return data r = base64.b64decode(data.signal) q = np.frombuffer(r, dtype=np.float32) signal = q.reshape(2, 1, 1024) signal = torch.from_numpy(signal) print(signal) total_network = TotalNetwork() feature_extractor = nn.DataParallel( total_network.feature_extractor.cuda()).train(False) classifier = nn.DataParallel( total_network.condition_classifier.cuda()).train(False) model = torch.load(os.path.join(train_config.log_dir, 'best_train.pkl'), map_location=torch.device('cpu')) feature_extractor.load_state_dict(model['feature_extractor']) classifier.load_state_dict(model['condition_class']) feature = feature_extractor.forward(signal) _, _, predict_prob = classifier.forward(feature) predict_label = np.argmax(variable_to_numpy(predict_prob), 1) return { 'predict_probability': '{}'.format(predict_prob), 'predict_label': '{}'.format(predict_label) }
def __init__(self, *args, **kwargs): HTTPException.__init__(self, *args, **kwargs) Loggable.__init__(self, self.__class__, args[0])
def __init__(self, host, limit): HTTPException.__init__(self) self.host = host self.limit = limit
def __init__(self, host, cert, reason): HTTPException.__init__(self) self.host = host self.cert = cert self.reason = reason.rstrip()