"""Get feature flags on backend.""" from owsrequest import request as requests from owsresponse import response from owsfeatures.constant import service_name ORCHARD_USER_ERROR_MESSAGE = 'Feature check requires Orchard user id' ORCHARD_USER_ERROR_CODE = 'orchard_user_id_required' def user_features(orchard_user_id): """Retrieve features for specified user. Args: orchard_user_id (str): identifier for user, e.g. alw:1234 Returns: response.Response: Contains a dictionary of the features and state. """ if not orchard_user_id: return response.create_error_response( code=ORCHARD_USER_ERROR_CODE, message=ORCHARD_USER_ERROR_MESSAGE ) url = '/features/user/{user_id}'.format(user_id=orchard_user_id) features_response = requests.get(service_name.OWS_FEATURES, url) if features_response.status_code != 200: return response.create_error_response( status=features_response.status_code, code='FEATURES_ERROR', message=features_response.reason) features_dict = features_response.json() return response.Response(message=features_dict) def general_features(): """Retrieve features without any user context. Returns: response.Response: Contains a dictionary of the features and state. """ url = '/features' features_response = requests.get(service_name.OWS_FEATURES, url) if features_response.status_code != 200: return response.create_error_response( status=features_response.status_code, code='FEATURES_ERROR', message=features_response.reason) features_dict = features_response.json() return response.Response(message=features_dict) def get_active_variant(feature_name, service, environment='qa'): """Get the active variant of a feature without user context. Args: feature_name (str): feature to check service (str): the name of the service using this package e.g.: daemon-salessheets environment (str): the process environment (dev|qa|prod) Returns: str: the active variant of the feature. """ feature_response = requests.process( service, environment, 'GET', service_name.OWS_FEATURES, '/features/{feature_name}'.format( feature_name=feature_name)) if feature_response.status_code != 200: return None return feature_response.content.decode('utf-8') def get_active_variant_with_headers( feature_name, service, headers, environment='qa'): """Get the active variant of a feature with user context headers. Args: feature_name (str): feature to check service (str): the name of the service using this package e.g.: daemon-salessheets headers (dict): context headers from the calling service. environment (str): the process environment (dev|qa|prod) Returns: str: the active variant of the feature. """ feature_response = requests.process( service, environment, 'GET', service_name.OWS_FEATURES, '/features/{feature_name}'.format( feature_name=feature_name), headers=headers, ) if feature_response.status_code != 200: return None return feature_response.content.decode('utf-8')