def pop(self, id): ''' Removes the record identified by id from the dataset. Returns the data (if found) or None. ''' if (not self.db_exists): return None url = self.url + '/' + self.db_name + '/' + id # first get it from the DB resp = self.ses.get(url) log.debug('ses.get(%s) => %d', url, resp.status_code) if (resp.status_code != 200): return None res = resp.json() del res['_id'] rev = res.pop('_rev', None) if rev is None: return None # now let's delete it! url = url + '?rev=' + rev resp = self.ses.delete(url) log.debug('ses.delete(%s) => %d', url, resp.status_code) log.info('pop(%s) => %s', id, str(res)) return res
def execute(self, risk_params): log.info('Executing the calculation ...') results = self.run(risk_params) log.info('Finished calculation ...') return results
def init_db(app): db.init_app(app) if not os.path.isfile("app/database.db"): with app.app_context(): db.create_all() log.warning("Created database from scratch") else: log.info("Initialized database")
def post(self): args = parser.parse_args() item = ItemModel(name=args["name"], quantity=args["quantity"], note=args["note"]) db.session.add(item) db.session.commit() log.info(f"Added item with id {item.item_id} with name {item.name}") return item, 201
def results(self, result_data): # Sort for human beings first g = self.vnq_model.getGraph() # Load it from the model ordered_results = self.graphHelper.order_results(g, result_data) # order the results to match human readability (nodes from 0 to n instead of arbitrary order) #Presentation of results vnq.VNQView.show_results(ordered_results) # console #Presentation of reports (warnings etc.) log.info("Analyzing reports ...") key_reports = reporting.ReportManager.keyReports() vnq.VNQView.displayStructuralFailures(key_reports) report_results = [r for r in reporting.ReportManager.reports.values()] vnq.VNQView.displayReports(report_results)
def init_dataset(aconfig): ''' In: aconfig is an app config dictionary. SideEffect: assigns an object to theAnimals Returns: True is succeeds ''' global theAnimals dstore = aconfig.get('DATASTORE') if (dstore == 'RAM'): log.info('DATASTORE is RAM') theAnimals = DataSetRAM('animal', AnimalSchema) return True elif (dstore == 'CouchDB'): log.info('DATASTORE is CouchDB') url = aconfig.get('COUCHDB_URL') if not url: log.info('No COUCHDB_URL') return False log.info('COUCHDB_URL=%s', str(url)) theAnimals = DataSetCouchDB('animal', AnimalSchema, url) return True # no datastore that we would understand! log.error('Unknown DATASTORE %s', dstore) return False
def create_app(): app = Flask(__name__) app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///database.db" app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False log.info("Initialized app") api = Api(app) log.info("Initialized API") init_db(app) api.add_resource(ShoppingList, "/shoppinglist") api.add_resource(Item, "/shoppinglist/<int:item_id>") return app
def set_webhook(): """ Sets the application webhook with Telegram Run with python manage.py set_webhoook """ token = os.environ.get("TOKEN") url = os.environ.get("URL") # we use the bot object to link the bot to our app which live # in the link provided by URL s = telegram_bot.setWebhook(f"{url}/api/avatar-bot/{token}") # something to let us know things work if s: app_logger.info("webhook setup ok") else: app_logger.error("webhook setup failed")
def get(self, id): ''' Access the record by id ''' if (not self.db_exists): return None url = self.url + '/' + self.db_name + '/' + id resp = self.ses.get(url) log.debug('ses.get(%s) => %d', url, resp.status_code) if (resp.status_code != 200): return None res = resp.json() del res['_id'] del res['_rev'] log.info('get(%s) => %s', id, str(res)) return res
def __init__(self, name, schema, url): ''' In: name - dataset name - e.g. 'animal' schema - dataset schema url - CouchDB URL ''' super().__init__(name, schema) # TCP session to talk to CouchDB self.ses = Session() self.url = url self.db_name = 'db_' + name self.db_exists = False # # verify that the database exists, if not - create it # url = self.url + '/' + self.db_name resp = self.ses.head(url) log.info('ses.head(%s) => %d', url, resp.status_code) if (resp.status_code == 404): # # database does not exist - create it! # resp = self.ses.put(url) log.info('ses.put(%s) => %d', url, resp.status_code) if (resp.status_code == 201): # created! self.db_exists = True pass elif (resp.status_code == 400): # bad db name pass elif (resp.status_code == 401): # unauthorized pass elif (resp.status_code == 412): # db already exists! pass elif (resp.status_code == 200): # database does exist - we're good! self.db_exists = True else: pass return
def run(self, entity_sizes): # g = self.g ineqIN = inequality.Gini(self.__g, dao.EdgeType.INCOMING) ineqOUT = inequality.Gini(self.__g, dao.EdgeType.OUTGOING) power_indicators = [] for ineq in [ineqIN, ineqOUT]: # Do hierarchical inequality measure works self.within_relationship_level( ineq ) # [1_ISL] Instance level, withinin relationship level: calc instance-utility power = self.entity_level(ineq) # [2_ESL]stop right before gini requires results from others # Calculate entity size if len(entity_sizes) > 0: # MANUAL entity size input log.warning("Entity size: Reverting to manual computation ...") # User has overwritten the automatisms entity_sizes = self.normalize_manual_entity_sizes(entity_sizes) # Make sure input sums to 1 size = entity_sizes else: log.info( "Entity size: Automatic computation..." ) # We investigate the business interaction volumes in the graph size = self.graphHelper.entity_sizes(self.__g, ineq.edgeType) # [2_ES] # Call presentation of power and entity size results # ordered_powers = self.graphHelper.order_results(self.g, power) # Order power # ordered_sizes = self.graphHelper.order_results(self.g, size) # Order entity sizes # console.displayPowerSize(ordered_powers, entity_sizes) # Present # Make it a ready to use weighted indicator power_indicator = self.dependencyIndicatorBargainingPower( power, size, ineq.edgeType ) # [2_BP] integrates entity size and scales the result to a relative indicator power_indicators.append(power_indicator) log.info("---- phase completed ----") return power_indicators # , size]
def list_routes(): """ Lists routes available in the application Run with python manage.py list_routes """ from flask import url_for import urllib output = [] for rule in app.url_map.iter_rules(): options = {} for arg in rule.arguments: options[arg] = "[{0}]".format(arg) methods = ",".join(rule.methods) url = url_for(rule.endpoint, **options) line = urllib.parse.unquote( "{:50s} {:20s} {}".format(rule.endpoint, methods, url) ) output.append(line) for line in sorted(output): app_logger.info(line)
def configure(self, file): #add parameters later log.info('Configuring the graph ...') self.setGraph(self.loader.fromJSON(file)) # self.pp.pprint(self.vnq_model.getGraph()) node_list = self.graphHelper.list_nodes(self.vnq_model.getGraph()) log.info(str(len(node_list)) + ' nodes detected (#):') for node in node_list: log.info('Node: #'+ node) #print params._VISUAL_INLINE_MARKER + params._VISUAL_INLINE_MARKER + '#' + node return
def put_(self, id, dat): ''' Stores data into the dataset Returns: True if dat is validated against schema and is added to the dataset False otherwise May throw: Error ''' if (not self.db_exists): return None url = self.url + '/' + self.db_name + '/' + id resp = self.ses.put(url, json=dat) log.debug('ses.put(%s, %s) => %d', url, str(dat), resp.status_code) if (resp.status_code == 201): log.info('put_(%s) => %s', id, str(dat)) return dat elif (resp.status_code == 202): log.info('put_(%s) => %s', id, str(dat)) return dat log.info('put_(%s) => None', id) return None
output.append(line) for line in sorted(output): app_logger.info(line) @manager.command def set_webhook(): """ Sets the application webhook with Telegram Run with python manage.py set_webhoook """ token = os.environ.get("TOKEN") url = os.environ.get("URL") # we use the bot object to link the bot to our app which live # in the link provided by URL s = telegram_bot.setWebhook(f"{url}/api/avatar-bot/{token}") # something to let us know things work if s: app_logger.info("webhook setup ok") else: app_logger.error("webhook setup failed") if __name__ == "__main__": config = os.getenv("FLASK_ENV") or "default" app_logger.info(f"Running application in {config} environment on port {port}") manager.run()