class Worker(QObject): def __init__(self, parent=None): QObject.__init__(self, parent) @pyqtSlot() def setupDatabase(self): from collections import OrderedDict self.db = Database('chat-advance.db') if not self.db.createConnection(): EventManager.trigger(Event('Database.databaseConnectionFail')) return if not self.db.isTableExist(DataCenter.TABLE_FRIENDS): self.db.createTable(DataCenter.TABLE_SERVERS, OrderedDict([('name', Database.TYPE_TEXT), ('url', Database.TYPE_TEXT), ('port', Database.TYPE_TEXT)])) @pyqtSlot(str, str) def addServer(self, name, desc): self.db.addRecord(DataCenter.TABLE_VMS, name=name, desc=desc) index = self.db.lastInsertRowId() EventManager.trigger(Event('DataCenter.ServerAdded', index, (name, desc))) @pyqtSlot(int) def delServer(self, index): self.db.delRecord(DataCenter.TABLE_VMS, id=index) @pyqtSlot() def loadAllServers(self): items = self.db.load(DataCenter.TABLE_VMS) EventManager.trigger(Event('DataCenter.allServersLoaded', items))
def register(): db = Database() if request.method == 'POST': form = request.form email1 = form['email'] email2 = form['email2'] if email1 != email2: flash('Emails do not match', 'info') return redirect(url_for('views.register')) user = create_database_user(form['email'], form['password'], form['username']) if validateCharacters(user): if db.check_existing_users(user['name'], user['email']): flash('Invalid Username/Email', 'info') return redirect(url_for('views.register')) else: db.insert_new_user(user) session[USERKEY] = user['name'] return redirect(url_for('views.home')) else: return redirect(url_for('views.register')) return render_template('register.html')
def create(): form = WorkoutForm() if form.validate_on_submit(): flash('Your workout has been added.') # session['workout_content'] = [form.exercise1.data, form.num_sets1, form.num_reps1.data] if request.method == "POST": # save to mongodb database name = form.name.data num_rounds = form.num_rounds.data # workout_content = form.workout_content.data workout_content = { 'exercise': form.exercise1.data, 'num_sets': form.num_sets1.data, 'num_reps': form.num_reps1.data } scored = form.scored_checkbox.data formatted_date = datetime.datetime.today().strftime("%Y-%m-%d") # new_workout = Workout(name, num_rounds, workout_content, scored, formatted_date) Database.insert( 'workouts', { 'name': name, 'num_rounds': num_rounds, 'scored': scored, 'content': workout_content, 'date': formatted_date }) # placeholder - will eventually redirect somewhere else # that make sense return redirect(url_for('workouts.create')) return render_template('creation.html', form=form)
def add(): form = ExerciseForm() if form.validate_on_submit(): flash('Your workout has been added.') session['exercise_name'] = form.name.data session['exercise_description'] = form.description.data if request.method == "POST": # save to mongodb database name = form.name.data description = form.description.data # muscles = form.muscles.data video_link = form.video_link.data images = form.photo.data formatted_date = datetime.datetime.today().strftime("%Y-%m-%d") Database.insert( 'exercises', { 'name': name, 'description': description, # 'muscles': muscles, 'video_link': video_link, 'images': images, 'date': formatted_date }) return redirect(url_for('exercises.add')) return render_template('add.html', form=form)
def setupDatabase(self): from collections import OrderedDict self.db = Database('chat-advance.db') if not self.db.createConnection(): EventManager.trigger(Event('Database.databaseConnectionFail')) return if not self.db.isTableExist(DataCenter.TABLE_FRIENDS): self.db.createTable(DataCenter.TABLE_SERVERS, OrderedDict([('name', Database.TYPE_TEXT), ('url', Database.TYPE_TEXT), ('port', Database.TYPE_TEXT)]))
def setUp(self): application.app.testing = True self.app = application.app.test_client() self.students_score_cache = Database(index=1, redis_host='localhost') self.exams_cache = Database(index=2, redis_host='localhost') self.students_score_cache.save_entry('test_student_id', 'exam_01', '9.0') self.students_score_cache.save_entry('test_student_id', 'exam_02', '7.0') self.exams_cache.save_entry('exam_01', 'test_student_id', '9.0') self.exams_cache.save_entry('exam_01', 'test_student_id_2', '7.0') self.exams_cache.save_entry('exam_02', 'test_student_id', '7.0')
def view(): workouts_with_date = [ (workout["name"], workout["num_rounds"], workout["scored"], workout["content"], workout["date"], datetime.datetime.strptime(workout["date"], "%Y-%m-%d").strftime("%b %d")) for workout in Database.find_all('workouts').sort("date", -1) ] return render_template("recent.html", workouts=workouts_with_date)
def create_app(): # create and configure the app app = Flask(__name__) Database.initialize() app.config['SECRET_KEY'] = 'bingers' @app.route("/") def index(): return render_template("index.html") # register Blueprints (after defining db) from application.workouts.views import workouts_blueprint app.register_blueprint(workouts_blueprint, url_prefix='/workouts') from application.exercises.views import exercises_blueprint app.register_blueprint(exercises_blueprint, url_prefix='/exercises') return app
def login(): db = Database() current_user = session.get(USERKEY, None) if request.method == 'POST': loginValues = request.form user = create_database_user(loginValues['emailInput'], loginValues['passwordInput']) isValid = db.validate_user(user) if isValid: session[USERKEY] = db.get_user_info(user)['name'] return redirect(url_for('views.home')) else: flash('Invalid email/password') return redirect(url_for('views.login', user=current_user)) return render_template('login.html', user=current_user)
def create_app(): global app, db app = Flask(__name__) setup_logging(app.logger) banner(app.logger, ' web ') app.config['SECRET_KEY'] = os.getenv('SECRET_KEY').encode() db = Database() @app.teardown_appcontext def shutdown_session(exception=None): db.session.remove()
def setupDatabase(self): from collections import OrderedDict self.db = Database('server.db') if not self.db.createConnection(): EventManager.trigger(Event('Database.databaseConnectionFail')) return if not self.db.isTableExist(DataCenter.TABLE_GPS): self.db.createTable( DataCenter.TABLE_GPS, OrderedDict( [('uuid', Database.TYPE_TEXT), ('desc', Database.TYPE_TEXT), ('lng', Database.TYPE_TEXT), ('lat', Database.TYPE_TEXT)] ) ) if not self.db.isTableExist(DataCenter.TABLE_ACCOUNT): self.db.createTable( DataCenter.TABLE_ACCOUNT, OrderedDict( [('uuid', Database.TYPE_TEXT), ('desc', Database.TYPE_TEXT), ('username', Database.TYPE_TEXT), ('password', Database.TYPE_TEXT)] ) )
def db(): """A test database that is clean at the start of each test. You'll probably also want to patch the db object that the code under test is using, such as by making another fixture like so: @pytest.fixture(name='db_') def web_user_db(db): web.user.db = db yield db """ database = Database('postgres:///lds-callings-test', echo=False) # Drop and recreate all of the tables. If the schema changes enough, this # might not work (some leftover tables?). Worst case, just recreate it: # $ dropdb lds-callings-test # $ createdb lds-callings-test database.drop_all() database.create_all() try: yield database finally: database.cleanup()
def collection_timer_handler(self): Log.debug("collection_timer_handler enter") # setup the list of deferred deferreds = [] # collect for each pack for pack in self.packs: # schedule the collection in a thread deferreds.append(threads.deferToThread(self.pack_collection_handler, pack)) # wait for all of the collection to finish d = defer.DeferredList(deferreds) results = yield d Log.info("measurements collected") # create list of measurements measurements = [] # go through the results for result in results: # get the pack pack = result[1]['pack'] for circuit in range(pack.get_num_circuits()): # create the measurement circuit_id = str(pack.get_index()) + "-" + str(circuit) value = result[1][circuit] measurement = Measurement(circuit=circuit_id, amperage=value, voltage=pack.get_voltage()) # store it in the record measurements.append(measurement) # create the record to be written to the database record = Record(uuid=str(uuid.uuid1()), duration=10.0, timestamp=datetime.utcnow().replace(microsecond=0).isoformat() + "Z") # write the record yield Database.write_record(record, measurements) # poke the uploader to tell it records are ready self.uploader.upload() # done Log.debug("collection_timer_handler exit")
parser.add_argument('--ca-cert', help="root CA certificate", required=True) parser.add_argument('--device-cert', help="device certificate", required=True) parser.add_argument('--device-key', help="device private key file", required=True) parser.add_argument('--debug', help="enable debug logging", action="store_true") args = parser.parse_args() # configure logging Log.setup() if args.debug: Log.enable_debug() # initialize the pack module Pack.setup() # initialize the database layer Database.setup(args.database) # create the uploader uploader = Uploader(args.device, args.host, args.port, args.ca_cert, args.device_key, args.device_cert) # create the collector collector = Collector(uploader) # TBD: probe the GPIO pins to detect the presence of pack modules pack1 = Pack(0, "AIN0", 800, 15.0, 120.0) collector.add_pack(pack1) pack2 = Pack(1, "AIN1", 800, 15.0, 120.0) collector.add_pack(pack2) pack3 = Pack(2, "AIN2", 800, 15.0, 120.0) collector.add_pack(pack3) pack4 = Pack(3, "AIN3", 3000, 21.0, 240.0)
if __name__ == '__main__': import sys import logging from optparse import OptionParser from twisted.python import log from twisted.internet import reactor from application.database import Database Log.setup() parser = OptionParser() parser.add_option("--database", dest="database", help="database location") parser.add_option("--host", dest="host", help="MQTT server") parser.add_option("--port", dest="port", help="MQTT port") parser.add_option("--ca-cert", dest="cacert", help="CA certificate") parser.add_option("--device-key", dest="devicekey", help="device key") parser.add_option("--device-cert", dest="devicecert", help="device cert") (options, args) = parser.parse_args() if options.database is None or options.host is None or options.port is None or options.cacert is None or options.devicekey is None or options.devicecert is None: raise Exception("missing argument") Database.setup(options.database) uploader = Uploader(options.host, int(options.port), options.cacert, options.devicekey, options.devicecert) uploader.start() reactor.run()
class IntegrationTest(unittest.TestCase): def setUp(self): application.app.testing = True self.app = application.app.test_client() self.students_score_cache = Database(index=1, redis_host='localhost') self.exams_cache = Database(index=2, redis_host='localhost') self.students_score_cache.save_entry('test_student_id', 'exam_01', '9.0') self.students_score_cache.save_entry('test_student_id', 'exam_02', '7.0') self.exams_cache.save_entry('exam_01', 'test_student_id', '9.0') self.exams_cache.save_entry('exam_01', 'test_student_id_2', '7.0') self.exams_cache.save_entry('exam_02', 'test_student_id', '7.0') def tearDown(self): self.students_score_cache.delete('test_student_id') self.exams_cache.delete('exam_01') self.exams_cache.delete('exam_02') def test_ping(self): res = self.app.get('/ping') self.assertEqual(res.data, '{"hello": "world"}') def test_student_profile(self): res = self.app.get('students/test_student_id') assert "exam_02" in res.data assert "7.0" in res.data assert "exam_01" in res.data assert "9.0" in res.data assert "8.0" in res.data def test_student_profile_with_param_filter(self): res = self.app.get('students/test_student_id?exam_id=exam_01') assert "exam_01" in res.data assert "9.0" in res.data assert "8.0" in res.data # average_score assert "exam_02" not in res.data def test_student(self): res = self.app.get('students') assert "test_student_id" in res.data def test_exams(self): res = self.app.get('exams') assert "exam_01" in res.data assert "exam_02" in res.data def test_exams_id(self): res = self.app.get('exams/exam_01') assert "test_student_id" in res.data assert "test_student_id_2" in res.data assert "7.0" in res.data assert "9.0" in res.data assert "8.0" in res.data def test_exams_id_with_param(self): res = self.app.get('exams/exam_01?student_name=test_student_id') assert "test_student_id" in res.data assert "9.0" in res.data assert "test_student_id_2" not in res.data
import os from flask import Flask app = Flask(__name__, static_url_path='/static') from flask_restful import Api api = Api(app) prod = os.getenv('PROD_MODE', default='false') PROD_MODE = prod.lower() in (1, 't', 'true') print('Production mode:', PROD_MODE) import application.config if PROD_MODE: print('Load production configuration') app.config.from_object(config.Production()) else: print('Load development configuration') app.config.from_object(config.Development()) from application.database import Database db = Database(app) import application.routes
from flask import request, flash, redirect, render_template import argparse parser = argparse.ArgumentParser() parser.add_argument('--num_to_render', default=150, help="Number of records to render", type=int) parser.add_argument('--save', default=True, help="True or False, save database", type=bool) args = vars(parser.parse_args()) print('args are : {}'.format(args)) db = Database() def export_data(): if args['save']: print('Saving apartment data...') db.export_to_csv(db.data) db.export_to_json(db.data) else: print("'Saving option is turned off. Run script with '--save=True'") @app.route('/', methods=['GET', 'POST']) def main(): db.read() b = min(args['num_to_render'], db.data.shape[0])
class Worker(QObject): def __init__(self, parent=None): QObject.__init__(self, parent) @pyqtSlot() def setupDatabase(self): from collections import OrderedDict self.db = Database('server.db') if not self.db.createConnection(): EventManager.trigger(Event('Database.databaseConnectionFail')) return if not self.db.isTableExist(DataCenter.TABLE_GPS): self.db.createTable( DataCenter.TABLE_GPS, OrderedDict( [('uuid', Database.TYPE_TEXT), ('desc', Database.TYPE_TEXT), ('lng', Database.TYPE_TEXT), ('lat', Database.TYPE_TEXT)] ) ) if not self.db.isTableExist(DataCenter.TABLE_ACCOUNT): self.db.createTable( DataCenter.TABLE_ACCOUNT, OrderedDict( [('uuid', Database.TYPE_TEXT), ('desc', Database.TYPE_TEXT), ('username', Database.TYPE_TEXT), ('password', Database.TYPE_TEXT)] ) ) @pyqtSlot(str, str, str, str, str) def addGps(self, uuid_, desc, lng, lat, clientId): self.db.addRecord(DataCenter.TABLE_GPS, uuid=uuid_, desc=desc, lng=lng, lat=lat) EventManager.trigger(Event('DataCenter.gpsAdded', {'id': uuid_, 'desc': desc, 'lng': lng, 'lat': lat}, clientId)) @pyqtSlot(str, str, str, str, str) def addAccount(self, id_, desc, username, password, clientId): self.db.addRecord(DataCenter.TABLE_ACCOUNT, uuid=id_, desc=desc, username=username, password=password) EventManager.trigger(Event('DataCenter.accountAdded', {'id': id_, 'desc': desc, 'username': username, 'password': password}, clientId)) @pyqtSlot(str) def loadAllGps(self, clientId): gps = self.db.load(DataCenter.TABLE_GPS) EventManager.trigger(Event('DataCenter.gpsLoaded', gps, clientId)) @pyqtSlot(str) def loadAllAccount(self, clientId): accounts = self.db.load(DataCenter.TABLE_ACCOUNT) EventManager.trigger(Event('DataCenter.accountLoaded', accounts, clientId)) @pyqtSlot(str, str, str) def updateGps(self, gpsId, desc, clientId): self.db.update(DataCenter.TABLE_GPS, 'desc', desc, uuid=gpsId) EventManager.trigger(Event('DataCenter.gpsUpdated', gpsId, desc, clientId)) @pyqtSlot(list, str) def deleteGps(self, ids, clientId): for id_ in ids: self.db.delRecord(DataCenter.TABLE_GPS, uuid=id_) EventManager.trigger(Event('DataCenter.gpsDeleted', ids, clientId)) @pyqtSlot(list, str) def deleteAccount(self, ids, clientId): for id_ in ids: self.db.delRecord(DataCenter.TABLE_ACCOUNT, uuid=id_) EventManager.trigger(Event('DataCenter.accountDeleted', ids, clientId))
def view(): exercises = [(exercise["name"], exercise["description"]) for exercise in Database.find_all('exercises')] return render_template("view.html", exercises=exercises)
def create_app(): global db db = Database()