def put(self): try: validator = RequestValidator(utils.spec) validated = validator.validate(FlaskOpenAPIRequest(request)) if validated.errors: raise errors.ResourceError( msg=f'Invalid PUT data: {validated.errors}.') refresh_token = validated.body.refresh_token refresh_token_data = auth.validate_token(refresh_token) token_data = refresh_token_data['access_token'] token_data.pop('token_type') token_data['exp'] = TapisAccessToken.compute_exp(token_data['ttl']) access_token = TapisAccessToken(**token_data) access_token.sign_token() refresh_token = TokensResource.get_refresh_from_access_token_data( token_data, access_token) result = { 'access_token': access_token.serialize, 'refres_token': refresh_token.serialize } return utils.ok(result=result, msg="Token generation successful.") except Exception as e: # return utils.ok(result="Got exception", msg=f"{refresh_token.serialize}") return utils.ok(result="Got exception", msg=f"Exception: {traceback.format_exc()}")
def get(self, project_id, site_id, instrument_id): result = [] msg = "" logger.debug("top of GET /measurements") #inst_result = meta.get_instrument(project_id,site_id,instrument_id) site, msg = meta.get_site(project_id, site_id) logger.debug(site) replace_cols = {} for inst in site['instruments']: logger.debug(inst) if inst['inst_id'] == instrument_id: instrument = inst logger.debug(inst) for v in inst['variables']: logger.debug(v) replace_cols[str(v['chords_id'])] = v['var_id'] js = influx.query_measurments([{ "inst": str(instrument['chords_id']) }, { "start_date": request.args.get('start_date') }, { "end_date": request.args.get('end_date') }]) logger.debug(js) if len(js) > 1 and len(js['series']) > 0: df = pd.DataFrame(js['series'][0]['values'], columns=js['series'][0]['columns']) pv = df.pivot(index='time', columns='var', values=['value']) df1 = pv df1.columns = df1.columns.droplevel(0) df1 = df1.reset_index().rename_axis(None, axis=1) df1.rename(columns=replace_cols, inplace=True) df1.set_index('time', inplace=True) if request.args.get('format') == "csv": logger.debug("CSV") # csv_response = Response(result, mimetype="text/csv") # si = StringIO.StringIO() #cw = csv.write(si) # cw.writerows(csvList) output = make_response(df1.to_csv()) output.headers[ "Content-Disposition"] = "attachment; filename=export.csv" output.headers["Content-type"] = "text/csv" return output else: result = json.loads(df1.to_json()) result['measurements_in_file'] = len(df1.index) result['instrument'] = instrument site.pop('instruments', None) result['site'] = meta.strip_meta(site) return utils.ok(result=result, msg="Measurements Found") else: return utils.ok(result=[], msg="No Measurements Founds")
def get(self): logger.debug('top of GET /ready') try: from service import models # if the service has no models at all, we assume the service is ready -- except ImportError: return utils.ok(result='', msg="Service is ready.") # any other exception though is likely a problem with the service -- except Exception as e: logger.error( f"Got exception in ready resource trying to import models; e: {e}." ) raise errors.ResourceError(msg=f'Service not ready') return utils.ok(result='', msg="Service is ready.")
def get(self, channel_id): logger.debug("top of GET /channels/{channel_id}") channel_result, msg = kapacitor.get_channel(channel_id) logger.debug(channel_result) result = meta.strip_meta(channel_result) logger.debug(result) return utils.ok(result=result, msg=msg)
def get(self): logger.debug("top of GET /channels") channel_result, msg = kapacitor.list_channels() logger.debug(channel_result) result = meta.strip_meta_list(channel_result) logger.debug(result) return utils.ok(result=result, msg=msg)
def get(self, template_id): logger.debug("top of GET /templates/{template_id}") template_result, msg = kapacitor.get_template(template_id) logger.debug(str(template_result)) result = meta.strip_meta(template_result) logger.debug(result) return utils.ok(result=result, msg=msg)
def post(self, project_id): # validator = RequestValidator(utils.spec) # result = validator.validate(FlaskOpenAPIRequest(request)) # if result.errors: # raise errors.ResourceError(msg=f'Invalid POST data: {result.errors}.') # validated_params = result.parameters # validated_body = result.body # logger.debug(f"validated_body: {dir(validated_body)}") #need to add check for project permission & project exists before chords insertion logger.debug('omg') logger.debug(request.json) body = request.json postSite = ChordsSite("", body['site_name'], body['latitude'], body['longitude'], body['elevation'], body['description']) resp, msg = chords.create_site(postSite) if msg == "Site created": site_result, message = meta.create_site(project_id, resp['id'], body) #resp['results']=meta_resp['results'] logger.debug('success') logger.debug(site_result) result = meta.strip_meta(site_result) #meta_resp, getmsg = meta.get_site(project_id, resp['id']) else: logger.debug('failed') message = msg result = '' return utils.ok(result=result, msg=message)
def post(self): logger.debug("top of POST /tokens") # try: validator = RequestValidator(utils.spec) validated = validator.validate(FlaskOpenAPIRequest(request)) if validated.errors: raise errors.ResourceError( msg=f'Invalid POST data: {validated.errors}.') validated_body = validated.body # this raises an exception of the claims are invalid - if hasattr(validated_body, 'extra_claims'): check_extra_claims(validated_body.extra_claims) token_data = TapisAccessToken.get_derived_values(validated_body) access_token = TapisAccessToken(**token_data) access_token.sign_token() result = {} result['access_token'] = access_token.serialize # refresh token -- if hasattr(validated_body, 'generate_refresh_token' ) and validated_body.generate_refresh_token: refresh_token = TokensResource.get_refresh_from_access_token_data( token_data, access_token) result['refresh_token'] = refresh_token.serialize return utils.ok(result=result, msg="Token generation successful.")
def post(self, project_id, site_id): logger.debug(type(request.json)) logger.debug(request.json) result = {} #TODO loop through list objects to support build operations if type(request.json) is dict: body = request.json else: body = request.json[0] logger.debug('before ChordsInstrument assignment') #id, site_id, name, sensor_id, topic_category_id, description, display_points, plot_offset_value, plot_offset_units, sample_rate_seconds): site_result, site_bug = meta.get_site(project_id, site_id) if site_bug == "Site found.": postInst = ChordsIntrument("", site_result['chords_id'], body['inst_name'], "", "", body['inst_description'], "120", "1", "weeks", "60") logger.debug('after ChordsInstrument assignment') chord_result, chord_msg = chords.create_instrument(postInst) if chord_msg == "Instrument created": body['chords_id'] = chord_result['id'] #body['instrument_id'] = instrument_id inst_result, inst_msg = meta.create_instrument( project_id, site_id, body) logger.debug(inst_msg) if len(inst_result) > 0: result = inst_result message = inst_msg else: message = chord_msg else: message = "Site Failed To Create" return utils.ok(result=result, msg=message)
def post(self): logger.debug("top of POST /tempates") body = request.json #TODO need to check our permissions result, msg = kapacitor.create_template(body) logger.debug(result) return utils.ok(result=meta.strip_meta(result), msg=msg)
def get(self): logger.debug("top of GET /templates") template_result, msg = meta.list_templates() logger.debug(template_result) result = meta.strip_meta_list(template_result) logger.debug(result) return utils.ok(result=result, msg=msg)
def get(self, project_id, site_id, instrument_id): logger.debug("top of GET /measurements") inst_result = meta.get_instrument(project_id, site_id, instrument_id) logger.debug(inst_result) if len(inst_result) > 0: result, msg = chords.get_measurements( str(inst_result[0]['chords_inst_id'])) logger.debug(result) return utils.ok(result=result, msg=msg)
def put(self, project_id, site_id): body = request.json putSite = ChordsSite(site_id, body['site_name'], body['latitude'], body['longitude'], body['elevation'], body['description']) site_result, msg = meta.update_site(project_id, site_id, body) result = meta.strip_meta(site_result) chord_result, chord_msg = chords.update_site(site_id, putSite) return utils.ok(result=result, msg=msg)
def post(self): logger.debug(request.json) body = request.json proj_result, msg = meta.create_project(body) logger.debug(proj_result) result = meta.strip_meta(proj_result) #resp['status'] = result['status'] #logger.debug(meta_resp['status']) #logger.debug(resp) return utils.ok(result, msg=msg)
def get(self, client_id): client = Client.query.filter_by(tenant_id=g.tenant_id, client_id=client_id).first() if not client: raise errors.ResourceError( msg=f'No client found with id {client_id}.') if not client.username == g.username: raise errors.PermissionsError("Not authorized for this client.") return utils.ok(result=client.serialize, msg='Client object retrieved successfully.')
def get(self, channel_id): logger.debug("top of GET /channels/{channel_id}/alerts") logger.debug(channel_id) result, msg = meta.list_alerts(channel_id) logger.debug(result) result_meta = meta.strip_meta_list(result) num_of_alerts = len(result_meta) result_alerts = {} result_alerts['num_of_alerts'] = num_of_alerts result_alerts['alerts'] = result_meta return utils.ok(result=result_alerts, msg=msg)
def post(self): validator = RequestValidator(utils.spec) result = validator.validate(FlaskOpenAPIRequest(request)) if result.errors: raise errors.ResourceError( msg=f'Invalid POST data: {result.errors}.') validated_body = result.body data = Client.get_derived_values(validated_body) client = Client(**data) db.session.add(client) db.session.commit() return utils.ok(result=client.serialize, msg="Client created successfully.")
def put(self, channel_id): logger.debug("top of PUT /channels/{channel_id}") body = request.json # TODO need to check the user permission to update channel status #if body['channel_id'] != channel_id: # raise errors.ResourceError(msg=f'Invalid PUT data: {body}. You cannot change channel id') result = {} try: result, msg = kapacitor.update_channel(channel_id, body) except Exception as e: msg = f"Could not update the channel: {channel_id}; exception: {e}" logger.debug(result) return utils.ok(result=meta.strip_meta(result), msg=msg)
def get(self): try: status_kapacitor = kapacitor.ping() logger.debug('Kapacitor status') logger.debug(status_kapacitor) status_chords = chords.ping() logger.debug('Chords status') logger.debug(status_chords) status_influx = influx.ping() logger.debug('Influx status') logger.debug(status_influx) if (status_kapacitor == 204 and status_chords == 200 and status_influx == 204): return utils.ok(result='', msg=f'Service ready') except: raise errors.ResourceError(msg=f'Service not ready')
def put(self, project_id, site_id, instrument_id, variable_id): logger.debug(type(request.json)) logger.debug(request.json) #TODO loop through list objects to support buld operations if type(request.json) is dict: body = request.json else: body = request.json[0] # id, name, instrument_id, shortname, commit putInst = ChordsVariable(variable_id, instrument_id, body['var_name'], body['shortname'], "") logger.debug(putInst) chord_result, chord_msg = chords.update_variable(variable_id, putInst) result, msg = meta.update_variable(project_id, site_id, instrument_id, variable_id, body) logger.debug(result) return utils.ok(result=result, msg=msg)
def put(self, project_id, site_id, instrument_id): logger.debug(type(request.json)) logger.debug(request.json) #TODO loop through list objects to support buld operations if type(request.json) is dict: body = request.json else: body = request.json[0] result, msg = meta.update_instrument(project_id, site_id, instrument_id, body) putInst = ChordsIntrument(int(result['chords_id']), site_id, body['inst_name'], "", "", body['inst_description'], "", "", "", "") chord_result, chord_msg = chords.update_instrument( str(result['chords_id']), putInst) return utils.ok(result=result, msg=msg)
def post(self): logger.debug("top of POST /alerts") try: req_data = json.loads(request.get_data()) logger.debug(req_data) except: logger.debug('Invalid POST JSON data') raise errors.ResourceError(msg=f'Invalid POST data: {req_data}.') #parse 'id' field, first string is the channel_id channel_id = req_data['id'].split(" ")[0] # prepare request for Abaco channel, msg = kapacitor.get_channel(channel_id) logger.debug(channel) result, message = abaco.create_alert(channel, req_data) logger.debug("end of POST /alerts") return utils.ok(result=result, msg=message)
def get(self, project_id, site_id): #result,msg = chords.list_instruments() result, msg = meta.list_instruments(project_id, site_id) logger.debug(site_id) ''' #logic to filter instruments based on site id filtered_res = [] list_index = 0 logger.debug(site_id) for i in range(len(result)): if (result[i]["site_id"] == int(site_id)): filtered_res.insert(list_index, result[i]) list_index = list_index + 1 logger.debug(filtered_res) if (len(filtered_res)!=0): return utils.ok(result=filtered_res, msg=msg) else: return utils.ok(result="null", msg=f'No instruments found with this site') ''' return utils.ok(result=result, msg=msg)
def post(self, project_id, site_id, instrument_id): #logger.debug(type(request.json)) logger.debug(request.json) #TODO loop through list objects to support buld operations if type(request.json) is dict: body = request.json else: body = request.json[0] inst_result, bug = meta.get_instrument(project_id, site_id, instrument_id) # id, name, instrument_id, shortname, commit postInst = ChordsVariable("test", inst_result['chords_id'], body['var_name'], body['var_id'], "") logger.debug(postInst) chord_result, chord_msg = chords.create_variable(postInst) if chord_msg == "Variable created": body['chords_id'] = chord_result['id'] result, msg = meta.create_variable(project_id, site_id, instrument_id, body) else: message = chord_msg logger.debug(result) return utils.ok(result=result, msg=msg)
def post(self): body = request.json logger.debug(body) instrument = {} if 'inst_id' in body: result = meta.fetch_instrument_index(body['inst_id']) logger.debug(result) if len(result) > 0: logger.debug(result[0]['chords_inst_id']) #get isntrument site_result, site_msg = meta.get_site(result[0]['project_id'], result[0]['site_id']) if 'instruments' in site_result: for inst in site_result['instruments']: if inst['inst_id'] == body['inst_id']: instrument = inst logger.debug(site_result) #resp = chords.create_measurement(result[0]['chords_inst_id'], body) resp = influx.write_measurements(site_result['chords_id'], instrument, body) logger.debug(resp) return utils.ok(result=[], msg="Measurements Saved")
def post(self, channel_id): logger.debug("top of POST /channels/{channel_id}") body = request.json # TODO need to check the user permission to update channel status # TODO Convert to Status Enum if body['status'] == 'ACTIVE': body['status'] = 'enabled' elif body['status'] == 'INACTIVE': body['status'] = 'disabled' logger.debug(body) else: raise errors.ResourceError(msg=f'Invalid POST data: {body}.') result = {} try: result, msg = kapacitor.update_channel_status(channel_id, body) except Exception as e: logger.debug(type(e)) logger.debug(e.args) msg = f"Could not update the channel status: {channel_id}; exception: {e} " logger.debug(msg) logger.debug(result) if result: return utils.ok(result=meta.strip_meta(result), msg=msg) return utils.error(result=result, msg=msg)
def get(self): logger.debug('top of GET /hello') return utils.ok(result='', msg="Hello from Tapis")
def get(self, project_id): proj_result, msg = meta.get_project(project_id) result = meta.strip_meta(proj_result) logger.debug(result) return utils.ok(result=result, msg=msg)
def get(self, project_id): site_result, msg = meta.list_sites(project_id) result = meta.strip_meta_list(site_result) return utils.ok(result=result, msg=msg)
def put(self, project_id): body = request.json proj_result, msg = meta.update_project(project_id, body) result = meta.strip_meta(proj_result) return utils.ok(result=result, msg=msg)