def find_infos(self, activity_name, city): """ Shows all the installations, equipments and activities which match the given activity and city """ database = Database('data/database.db') infos = database.get_infos(activity_name, city) view = Template(filename="view/template.html", lookup=lookup) try: render = view.render( rows=[[ item[0].number, item[0].name, item[1].number, item[1].name, item[2].number, item[2].name ] for item in infos], pageTitle="Informations pour " + activity_name + " à " + city, tableTitle="Informations pour " + activity_name + " à " + city, ths=[ "Numéro d'installation", "Nom d'installation", "Numéro d'équipement", "Nom d'équipement", "Numéro d'activité", "Nom d'activité" ]) except AttributeError: render = view.render( rows=[], pageTitle="Informations pour " + activity_name + " à " + city, tableTitle="Informations pour " + activity_name + " à " + city, ths=[ "Numéro d'installation", "Nom d'installation", "Numéro d'équipement", "Nom d'équipement", "Numéro d'activité", "Nom d'activité" ]) return render
def display_Installations(self): """ Displays all installations """ html = self.add_HTML_header('Installations') css = Template(filename="include/css.html") html += (css.render()) database = Database('data/database.db') insts = database.read_Installations() html += '''<h2>Tableau des installations</h2> <table border=1> <tr> <th>Numéro</th> <th>Nom</th> <th>Adresse</th> <th>Code postal</th> <th>Ville</th> <th>Latitude</th> <th>Longitude</th> </tr>\n''' for i in insts: html += '''<tr>\n <td>''' + str(i.number) + '''</td> <td>''' + i.name + '''</td> <td>''' + i.address + '''</td> <td>''' + str(i.zipCode) + '''</td> <td>''' + i.city + '''</td> <td>''' + str(i.latitude) + '''</td> <td>''' + str(i.longitude) + '''</td> </tr>''' html += '''</table>''' return html
def display_One_Installation(self, number): """ Display one installation """ html = self.add_HTML_header('Installations ' + number) css = Template(filename="include/css.html") html += (css.render()) database = Database('data/database.db') inst = database.read_One_Installation(number) html += '''<h2>Installation n°''' + number + '''</h2> <table border=1> <tr> <th>Numéro</th> <th>Nom</th> <th>Adresse</th> <th>Code postal</th> <th>Ville</th> <th>Latitude</th> <th>Longitude</th> </tr>''' html += '''<tr> <td>''' + str(inst.number) + '''</td> <td>''' + inst.name + '''</td> <td>''' + inst.address + '''</td> <td>''' + str(inst.zipCode) + '''</td> <td>''' + inst.city + '''</td> <td>''' + str(inst.latitude) + '''</td> <td>''' + str(inst.longitude) + '''</td> </tr>''' html += '''</table>''' return html
def show_installation(self, number): """ Shows the installation which has the given number from the database """ database = Database('data/database.db') inst = database.read_installation(number) view = Template(filename="view/template.html", lookup=lookup) try: render = view.render(rows=[[ inst.number, inst.name, inst.address, inst.zip_code, inst.city, inst.latitude, inst.longitude ]], pageTitle="Installation " + number, tableTitle="Installation " + number, ths=[ "Numéro", "Nom", "Adresse", "Code postal", "Ville", "Latitude", "Longitude" ]) except AttributeError: render = view.render(rows=[], pageTitle="Installation " + number, tableTitle="Installation " + number, ths=[ "Numéro", "Nom", "Adresse", "Code postal", "Ville", "Latitude", "Longitude" ]) return render
def display_Informations(self, activity, city): """ Display informations about an activity and a city """ html = self.add_HTML_header("Recherche de l'activité " + activity + " dans " + city) css = Template(filename="include/css.html") html += (css.render()) database = Database('data/database.db') query = database.read_Informations(activity, city) html += '''<h2>Résultat de la recherche</h2> <table border=1> <tr> <th>Numéro de l'installation</th> <th>Nom de l'installation</th> <th>Numéro de l'équipement</th> <th>Nom de l'équipement</th> <th>Numéro de l'activité</th> <th>Nom de l'activité</th> </tr>''' html += '''<tr>''' for q in query: html += '''<td>''' + q[0].number + '''</td>''' html += '''<td>''' + q[1].name + '''</td>''' #<td>''' + query[0].number + '''</td> #<td>''' + query[0].name + '''</td> #<td>''' + query[1].number + '''</td> #<td>''' + query[1].name + '''</td> #<td>''' + query[2].number + '''</td> #<td>''' + query[2].name + '''</td> html += '''</tr>''' html += '''</table>''' return html
def show_activities(self): """ Shows all the activities from the database """ database = Database('data/database.db') activities = database.read_activities() view = Template(filename="view/template.html", lookup=lookup) return view.render(rows=[[item.number, item.name] for item in activities], pageTitle="Activités", tableTitle="Liste de toutes les activités", ths=["Numéro", "Nom"])
def show_equipments(self): """ Shows all the equipments from the database """ database = Database('data/database.db') equipments = database.read_equipments() view = Template(filename="view/template.html", lookup=lookup) return view.render( rows=[[item.number, item.name, item.installation_number] for item in equipments], pageTitle="Équipements", tableTitle="Liste de tous les équipements", ths=["Numéro", "Nom", "Numéro d'installation"])
def __init__(self, args): self._args = args self._logger = logging.getLogger(__name__) self._config = Configuration() self._ofx_parser = OFXParser(self._config) self._db = Database() self._fs = FileSystem()
def show_installations(self): """ Shows all the installations from the database """ database = Database('data/database.db') installations = database.read_installations() view = Template(filename="view/template.html", lookup=lookup) return view.render(rows=[[ item.number, item.name, item.address, item.zip_code, item.city, item.latitude, item.longitude ] for item in installations], pageTitle="Installations", tableTitle="Liste de toutes les installations", ths=[ "Numéro", "Nom", "Adresse", "Code postal", "Ville", "Latitude", "Longitude" ])
async def render_put(self, request): data = json.loads(request.payload)\ # TODO check if ip it's the same changed = True if data.get("brightness"): Database().influx_write_brightness(self._light.order, data.get("brightness"), datetime.utcnow()) if data.get("proximity"): Database().influx_write_proximity(self._light.order, data.get("proximity"), datetime.utcnow()) self.seen() return aiocoap.Message(code=aiocoap.CHANGED, token=request.token)
def show_activity(self, number): """ Shows the activity which has the given number from the database """ database = Database('data/database.db') activ = database.read_activity(number) view = Template(filename="view/template.html", lookup=lookup) try: render = view.render(rows=[[activ.number, activ.name]], pageTitle="Activité " + number, tableTitle="Activité " + number, ths=["Numéro", "Nom"]) except AttributeError: render = view.render(rows=[], pageTitle="Activité " + number, tableTitle="Activité " + number, ths=["Numéro", "Nom"]) return render
def init_resource_database(): from services.database import Database from resources.models import StreetLight, Mode, Range db = Database().db db.connect() db.create_tables([StreetLight, Mode, Range])
def show_equipment(self, number): """ Shows the equipment which has the given number from the database """ database = Database('data/database.db') equip = database.read_equipment(number) view = Template(filename="view/template.html", lookup=lookup) try: render = view.render( rows=[[equip.number, equip.name, equip.installation_number]], pageTitle="Équipement " + number, tableTitle="Équipement " + number, ths=["Numéro", "Nom", "Numéro d'installation"]) except AttributeError: render = view.render( rows=[], pageTitle="Équipement " + number, tableTitle="Équipement " + number, ths=["Numéro", "Nom", "Numéro d'installation"]) return render
def display_One_Activity(self, number): """ Display one activity """ html = self.add_HTML_header('Activité ' + number) css = Template(filename="include/css.html") html += (css.render()) database = Database('data/database.db') act = database.read_One_Activity(number) html += '''<h2>Activité n°''' + number + '''</h2> <table border=1> <tr> <th>Numéro</th> <th>Nom</th> </tr>''' html += '''<tr> <td>''' + str(act.number) + '''</td> <td>''' + act.name + '''</td> </tr>''' html += '''</table>''' return html
def display_Activities(self): """ Displays all activities """ html = self.add_HTML_header('Activités') css = Template(filename="include/css.html") html += (css.render()) database = Database('data/database.db') acts = database.read_Activities() html += '''<h2>Tableau des activitiés</h2> <table border=1> <tr> <th>Numéro</th> <th>Nom</th> </tr>''' for a in acts: html += '''<tr> <td>''' + str(a.number) + '''</td> <td>''' + str(a.name) + '''</td> </tr>''' html += '''</table>''' return html
def display_Equipments(self): """ Displays all equipments """ html = self.add_HTML_header('Equipements') css = Template(filename="include/css.html") html += (css.render()) database = Database('data/database.db') equips = database.read_Equipments() html += '''<h2>Tableau des équipements</h2> <table border=1> <tr> <th>Numéro</th> <th>Nom</th> <th>Numéro de l'installation</th> </tr>''' for e in equips: html += '''<tr> <td>''' + str(e.number) + '''</td> <td>''' + e.name + '''</td> <td>''' + str(e.installationNumber) + '''</td> </tr>''' html += '''</table>''' return html
def display_One_Equipment(self, number): """ Display one equipment """ html = self.add_HTML_header('Equipement ' + number) css = Template(filename="include/css.html") html += (css.render()) database = Database('data/database.db') equip = database.read_One_Equipment(number) html += '''<h2>Equipement n°''' + number + '''</h2> <table border=1> <tr> <th>Numéro</th> <th>Nom</th> <th>Numéro de l'installation</th> </tr>''' html += '''<tr> <td>''' + str(equip.number) + '''</td> <td>''' + equip.name + '''</td> <td>''' + str(equip.installationNumber) + '''</td> </tr>''' html += '''</table>''' return html
def test_when_init_then_database_service_returned(): db = Database() assert hasattr(db, "_logger") assert hasattr(db, "_config") assert hasattr(db, "_connections") assert hasattr(db, "_cursors") assert hasattr(db, "_sql") assert db._sql == { "create": "CREATE TABLE IF NOT EXISTS {table} ({col_spec}, PRIMARY KEY ({keys}));", "insert": "INSERT INTO {table}({columns}) VALUES({data});", "select": { "select_all_from": "SELECT * FROM {table};", "select_columns_from": "SELECT {columns} FROM {table};", "select_all_from_where": "SELECT * FROM {table} WHERE {where};", "select_columns_from_where": "SELECT {columns} FROM {table} WHERE {where};", }, }
def db(): db = Database() db._config.paths.db_path = os.sep.join(["C:", "base", "db", "path"]) return db
from copy import deepcopy import unittest import json import sys sys.path.append('../database') from services.database import Database data = Database() import app #BAD_ITEM_URL = '{}/5'.format(BASE_URL) #GOOD_ITEM_URL = '{}/1'.format(BASE_URL) class TestFlaskApi(unittest.TestCase): def setUp(self): self.backup_items = deepcopy(data.storage) # no references! self.app = app.app.test_client() self.app.testing = True def test_get_allUsers(self): BASE_URL = 'http://127.0.0.1:5000/rest/user' response = self.app.get(BASE_URL) data = json.loads(response.get_data()) self.assertEqual(response.status_code, 200) self.assertEqual(len(data), 2) def test_get_oneUser(self): BASE_URL = 'http://127.0.0.1:5000/rest/user/1'
#!/usr/bin/env python3.4 # -*- coding: utf-8 -*- """ This part of program is used to load JSON file in the database """ from services.readJson import ReadJSON from services.database import Database from model.activity import Activity from model.equipment import Equipment from model.installation import Installation from progressbar import * print("Creation of database...") database = Database("data/database.db") database.create_DB() print("Database created") print("Insertion in installation table...") rdI = ReadJSON("data/installations.json") rdI.readInstallation() resultI = rdI.getResult() print("File read") progressBar = ProgressBar(widgets=['Writing installations to the database: ', Percentage(), ' ', ETA()]) for i in progressBar(resultI): database.Insert_In_Installation(i) database.commit_DB() print("Insertion done")
from services.database import Database from resources.models import Range, Mode, StreetLight db = Database().db db.connect() db.create_tables([StreetLight, Mode, Range]) # Insert modes mode = Mode(lamps_after=3, illumination_duration_seconds=10, proximity_refresh=5, brigthness_refresh=5, enabled=False) mode.save() mode = Mode(lamps_after=2, illumination_duration_seconds=10, proximity_refresh=60, brigthness_refresh=60, enabled=True) mode.save() # Insert ranges ranges = [{ "min": 20, "with_movement": 70, "without_movement": 10 }, { "min": 40, "with_movement": 80, "without_movement": 20
def start_processes(config_ini): procs = [] stoplist = [] logger.info("Starting config service") conf = Config() proc = Process(target=conf.run, args=(config_ini,)) procs.append(proc) proc.start() if wait_service_up(SOCK_CONFIG) is False: stop_services(stoplist) sys.exit(1) stoplist.append(SOCK_CONFIG) logger.info("Starting service-detection service") service_detection = ServiceDetection() proc = Process(target=service_detection.run, args=()) procs.append(proc) proc.start() if wait_service_up(SOCK_SD) is False: stop_services(stoplist) sys.exit(1) stoplist.append(SOCK_SD) logger.info("Starting DNS service") dns = DNSAPI() proc = Process(target=dns.run, args=()) procs.append(proc) proc.start() if wait_service_up(SOCK_DNS) is False: stop_services(stoplist) sys.exit(1) stoplist.append(SOCK_DNS) logger.info("Starting web-server service") mgmt_server = ManageWebservers() proc = Process(target=mgmt_server.run, args=()) procs.append(proc) proc.start() if wait_service_up(SOCK_WEBSERVER) is False: stop_services(stoplist) sys.exit(1) stoplist.append(SOCK_WEBSERVER) logger.info("Starting module-loader service") module_ldr = ModuleLoader() proc = Process(target=module_ldr.run, args=()) procs.append(proc) proc.start() if wait_service_up(SOCK_MODULES) is False: stop_services(stoplist) sys.exit(1) stoplist.append(SOCK_MODULES) logger.info("Starting database service") database = Database() proc = Process(target=database.run, args=()) procs.append(proc) proc.start() if wait_service_up(SOCK_DATABASE) is False: stop_services(stoplist) sys.exit(1) stoplist.append(SOCK_DATABASE) logger.info("Starting shell-receiver service") shell = ShellReceiver() proc = Process(target=shell.run, args=()) procs.append(proc) proc.start() # No need to wait for shell-service to be up logger.info("All processes have started") return procs
class Meta: database = Database().get_db()
from flask import Flask, request, jsonify from services.service import Server from services.database import Database database = Database() server = Server(database) app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" class InvalidUsage(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['message'] = self.message return rv
# -*- coding: utf-8 -*- """ This program reads data from JSON files and writes the results to a SQLite database """ from progressbar import * from services.readjson import ReadJSON from services.database import Database from model.activity import Activity from model.installation import Installation from model.equipment import Equipment print("Creating database...", end=" ") database = Database("data/database.db") database.create_new() print("Done") rj = ReadJSON() installations = rj.read_installations("data/Installations.json") pbar = ProgressBar(widgets=[ 'Writing installations to the database: ', Percentage(), ' ', ETA() ]) for elem in pbar(installations): database.insert_installation(elem) database.commit()