def devices(): if request.method == "GET": devices = models.Device.get_all() results = [] for device in devices: obj = { 'id': device.id, 'name_owner': device.name_owner, 'date_buy': device.date_buy, 'version': device.version_po, 'comment': device.comment, 'sensors': [] } for sensor in device.sensors: obj['sensors'].append({'id': sensor.id, 'name': sensor.name}) results.append(obj) response = jsonify(results) response.status_code = 200 return response else: device = models.Device() device.name_owner = 'newCreate' device.version_po = '0.0001' device.save() return jsonify({ 'message': 'create Device', 'id': device.id, 'version': '0.0001' })
def _collectData(self): date_receive = None is_received = self._ui.in_ChkReceived.isChecked() if is_received: date_receive = datetime.datetime.now().date() with pony.db_session: batch = models.Batch[self._ui.in_ComboBatch.currentData( mytools.const.RoleNodeId)] chip = models.Chip[self._ui.in_ComboChip.currentData( mytools.const.RoleNodeId)] if self._currentItem is not None: device = models.Device[self._currentItem.id] device.set(name=self._ui.in_EditName.text(), description=self._ui.in_TextNote.toPlainText(), date_receive=date_receive, batch=batch, chip=chip, is_needed=self._ui.in_ChkNeeded.isChecked(), is_received=is_received) else: device = models.Device( name=self._ui.in_EditName.text(), description=self._ui.in_TextNote.toPlainText(), date_receive=date_receive, date_create=datetime.datetime.now().date(), batch=batch, chip=chip, is_needed=self._ui.in_ChkNeeded.isChecked(), is_received=is_received) pony.flush() self._newItem = device
def adddevice(): form = forms.AddDevice() if form.validate_on_submit(): mom = models.Device(name=request.form['name']) mom.put() models.Visit(user_ip=request.remote_addr, action='PUT DEVICE ' + str(mom.key.integer_id())).put() flash('added ' + str(mom.key.integer_id())) return redirect('/admin/devices') return render_template('adddevice.html', form=form)
def deviceUpdate(device_id): if (not device_id == 0 and request.method == "POST"): data = json.loads(request.data.decode('utf-8')) device = models.Device().get(device_id) if ('comment' in data and not data['comment'] == ''): device.comment = data['comment'] if ('name' in data and not data['name'] == ''): device.name_owner = data['name'] device.save() return jsonify({'message': 'update', 'code': 200}) else: return jsonify({'message': 'error update', 'code': 500})
def init_db(): # import all modules here that might define models so that # they will be registered properly on the metadata. Otherwise # you will have to import them first before calling init_db() import models Base.metadata.create_all(bind=engine) # add all devices to the database db.session.query(models.Device).delete() db.session.commit() for hostname, (IP, OS) in napalm_dispatcher.items(): device = models.Device(hostname, IP, OS) db.session.add(device) db.session.commit()
def create_device_record(model, manufacturerID, userRecord): ''' options for create device require model, manufacturerID and user_id ''' print('Device Created: ', model, manufacturerID, userRecord.id) deviceVars = { 'model': model, 'manufacturerID': manufacturerID, 'user_id': userRecord.id } try: return s.query(m.Device).filter_by(**deviceVars).one() except NoResultFound: deviceRecord = m.Device(**deviceVars) print("Device Record record: ", deviceRecord.id, userRecord.id) return deviceRecord
def add(sqlsession): error = False if not error: device = models.Device(name=request.form['add_device_name'], pubkey=request.form['add_device_pubkey'], creation_date=helpers.today()) sqlsession.add(device) sqlsession.commit() flash('New device was created successfully', 'success') return redirect(url_for('device.view', id=device.id)) else: return redirect( url_for('device.view', device_name=request.form['add_device_name'], device_pubkey=request.form['add_device_pubkey']))
def post(self): user = users.get_current_user() registration_id = self.request.get('registration_id') brand = self.request.get('brand') device = self.request.get('device') manufacturer = self.request.get('manufacturer') model = self.request.get('model') if registration_id is None: self.response.out.write('No registration id') self.error(400) return d = models.Device(registration_id=registration_id, user=user, brand=brand, device=device, manufacturer=manufacturer, model=model) d.put() self.response.out.write('OK')
def main(): p1 = models.Device("hey", "link") model = cp_model.CpModel() return p1.name
level=9999, name='Noah Huesser', email='*****@*****.**', nethzid='nhuesser') s.add(u1) password = hashlib.sha256(b'2') u2 = models.User(username='******', password=password.hexdigest(), level=9999, name='Dominik Boehi', email='*****@*****.**', nethzid='dboehi') s.add(u2) d = models.Device(name='Der Testgeraet', pubkey='alfonso', creation_date=datetime.date.today(), is_online=False, is_enabled=True) s.add(d) data = '2015-12-01'.split('-') date = datetime.date(int(data[0]), int(data[1]), int(data[2])) t = models.Token(name='Testtoken Yatekii', value='migros', description='Bla', owner=u1, flashed=False, expiry_date=date, creation_date=datetime.date.today()) d.tokens.append(t) s.add(t) t = models.Token(name='Testtoken Tiwalun',
def import_data(): filepath = os.path.join(current_app.config.get('BASEDIR'), 'uploads') import_source = request.form.get('import_source') if not import_source == None: import_source = import_source.replace( '/', os.sep ) # Let's be OS independent! Maybe we switch on Windows server one day :) filepath = os.path.join(filepath, import_source) delimiter = request.form.get('csv_separator') if delimiter == None: delimiter = current_app.config.get('DEFAULT_CSV_SEPARATOR') if delimiter == None: delimiter = ',' schema = { 'id': { 'type': 'integer', 'required': True }, 'name': { 'type': 'string', 'required': True, 'maxlength': 32 }, 'description': { 'type': 'string', 'required': False }, 'code': { 'type': 'string', 'required': True, 'maxlength': 30 }, 'status': { 'type': 'string', 'allowed': ['enabled', 'disabled', 'deleted'] } } lookup_indexes = { 0: { 'name': 'id', 'convert_function': utility.int_convert }, 1: { 'name': 'name' }, 2: { 'name': 'description' }, 3: { 'name': 'code' }, 5: { 'name': 'status' } } devices_filepath = os.path.join(filepath, 'devices.csv') device_documents = utility.csv_file_parse_func( schema=schema, filepath=devices_filepath, lookup_indexes=lookup_indexes, delimiter=delimiter, logger=current_app.logger) if device_documents == False: current_app.logger.error( 'Invalid configuration provided for parsing content csv file, filepath: "%s"' % devices_filepath) return jsonify({ 'success': False, 'msg': 'Invalid configuration provided for parsing devices csv file' }) # content schema = { 'name': { 'type': 'string', 'required': True, 'maxlength': 32 }, 'description': { 'type': 'string', 'required': False }, 'device': { 'type': 'integer', 'required': True }, 'expire_date': { 'type': 'datetime' }, 'status': { 'type': 'string', 'allowed': ['enabled', 'disabled', 'deleted'] } } lookup_indexes = { 1: { 'name': 'name' }, 2: { 'name': 'description' }, 3: { 'name': 'device', 'convert_function': utility.int_convert }, 4: { 'name': 'expire_date', 'convert_function': utility.date_convert }, 5: { 'name': 'status' } } content_filepath = os.path.join(filepath, 'content.csv') content_documents = utility.csv_file_parse_func( schema=schema, filepath=content_filepath, lookup_indexes=lookup_indexes, delimiter=delimiter, logger=current_app.logger) if content_documents == False: current_app.logger.error( 'Invalid configuration provided for parsing content csv file, filepath: "%s"' % content_filepath) return jsonify({ 'success': False, 'msg': 'Invalid configuration provided for parsing content csv file' }) try: found_codes = [] for device in device_documents: if device['code'] in found_codes: current_app.logger.error( 'Duplicate code: "%s" was found while parsing content csv file, filepath: "%s"' % (device['code'], content_filepath)) continue found_codes.append(device['code']) existing_device = db_session.query(models.Device) \ .filter(models.Device.code == device['code']). \ first() if existing_device: device = existing_device device.date_updated = datetime.datetime.utcnow().replace( microsecond=0).isoformat() else: device = models.Device(**device) current_time = datetime.datetime.utcnow().replace( microsecond=0).isoformat() device.date_created = current_time device.date_updated = current_time db_session.add(device) db_session.commit() for content in content_documents: content = models.Content(**content) current_time = datetime.datetime.utcnow().replace( microsecond=0).isoformat() content.date_created = current_time content.date_updated = current_time db_session.add(content) db_session.commit() output = {'success': True, 'msg': 'Successfully imported!'} except AssertionError as e: current_app.logger.error( 'Data error! Cannot import csv files to database, error: ' % str(e)) output = { 'success': False, 'msg': 'There was an error during the operation! Please check CSV files that you are sending.' } except exc.SQLAlchemyError as e: current_app.logger.error( 'Database error! Cannot import csv files to database, error: %s' % str(e)) output = {'success': False, 'msg': 'Database error!'} return jsonify(output)
def update_pog(session, company_id, store_id, device_id, df, operation=False): company_pkey = session.query( models.Company.company_pkey).filter_by(company_id=company_id).first() assert company_pkey, f'company_id: {company_id}, 해당 정보가 존재하지 않습니다.' company_pkey = company_pkey.company_pkey store_pkey = session.query(models.Store.store_pkey).filter_by( company_pkey=company_pkey, store_id=store_id).first() assert store_pkey, f'company_id: {company_id}, store_id: {store_id}, 해당 정보가 존재하지 않습니다.' store_pkey = store_pkey.store_pkey try: # insert device device = session.query(models.Device).filter_by(store_pkey=store_pkey, device_id=device_id) if device.first() is None: print( f'company_id: {company_id}, store_id: {store_id}, device_id: {device_id}, 해당 정보가 존재하지 않습니다.' ) print( f'company_id: {company_id}, store_id: {store_id}, device_id: {device_id}, 해당 정보를 추가합니다.' ) if device_id[0] == 's': device_install_type = 'S' elif device_id[0] == 'w': device_install_type = 'W' else: raise ValueError('device_id의 첫 글자는 "s" 또는 "w" 이어야 합니다.') session.add( models.Device(device_id=device_id, store_pkey=store_pkey, device_install_type=device_install_type, operation=operation)) # session.commit() # get device_pkey device_pkey = device.first().device_pkey # insert model model_pkeys = [] change = False for d in df[['model_name', 'model_address']].itertuples(): model = session.query( models.Model).filter_by(model_name=d.model_name).first() if model is None: print(f'model {d.model_name} 이 존재하지 않습니다. model 정보를 추가합니다.') model = models.Model(model_name=d.model_name, model_address=None if np.isnan( d.model_address) else d.model_address) session.add(model) change = True model_pkeys.append(model.model_pkey) df['model_pkey'] = model_pkeys # insert or update shelves for shelf_floor in set(df.shelf_floor): shelf = session.query(models.Shelf).filter_by( device_pkey=device_pkey, shelf_floor=shelf_floor) sub_df = df[df['shelf_floor'] == shelf_floor] model_pkey = sub_df['model_pkey'].iloc[0] if shelf.first() is None: print('shelf_floor가 존재하지 않습니다. shelf 정보를 추가합니다.') session.add( models.Shelf(device_pkey=int(device_pkey), shelf_floor=int(shelf_floor), model_pkey=int(model_pkey))) else: if shelf.first().model_pkey != model_pkey: print( f'경고! shelf_floor: {shelf_floor} 자리의 model_pkey가 {shelf.first().model_pkey} 에서 {model_pkey} 로 변경됩니다.' ) shelf.update({'model_pkey': int(model_pkey)}) # get shelf_pkeys shelf_pkeys = [] df2 = df.drop(['loadcell_column'], axis=1).drop_duplicates() for d in df2.itertuples(): shelf_pkey = session.query(models.Shelf.shelf_pkey)\ .select_from(models.Shelf)\ .join(models.Device, models.Device.device_pkey == models.Shelf.device_pkey)\ .filter(models.Device.store_pkey == store_pkey, models.Device.device_id == device_id, models.Shelf.shelf_floor == d.shelf_floor)\ .first().shelf_pkey shelf_pkeys.append(shelf_pkey) # cells for d, shelf_pkey in zip(df2.itertuples(), shelf_pkeys): try: # get design_pkey design_pkey = session.query( models.Design.design_pkey).filter_by( design_infer_label=d.design_infer_label).all( )[-1].design_pkey except IndexError as index_error: print(f'goods_id({d.goods_id})에 해당하는 데이터가 존재하지 않습니다.') raise index_error # get cells cell = session.query(models.Cell).filter_by( shelf_pkey=shelf_pkey, cell_column=d.cell_column) if cell.first() is None: # if the cell isn't exist, insert the cell print( f'floor: {d.shelf_floor}, column: {d.cell_column} 에 해당하는 데이터가 존재하지 않습니다. 해당 cell을 추가합니다.' ) session.add( models.Cell(shelf_pkey=int(shelf_pkey), design_pkey_master=int(design_pkey), cell_column=int(d.cell_column), stock_count_max=int(d.stock_count_max), stock_count_low_alert_limit=None if np.isnan(d.stock_count_low_alert_limit) else int(d.stock_count_low_alert_limit), inference_mode=d.inference_mode, load_cell_mode=d.load_cell_mode)) else: # else, update the cell cell.update({ 'design_pkey_master': int(design_pkey), 'stock_count_max': int(d.stock_count_max), 'stock_count_low_alert_limit': None if np.isnan(d.stock_count_low_alert_limit) else int( d.stock_count_low_alert_limit), 'inference_mode': d.inference_mode, 'load_cell_mode': d.load_cell_mode }) # insert init stock stock = session.query( models.Stock).filter_by(cell_pkey=cell.first().cell_pkey) if stock.first() is None: print( f'stock 추가 (floor: {d.shelf_floor}, column: {d.cell_column}, goods_id: {d.goods_id}, stock_count: 0' ) session.add( models.Stock(cell_pkey=cell.first().cell_pkey, design_pkey=int(design_pkey), stock_count=0)) # insert (or update) loadcell for d in df.itertuples(): shelf_pkey = session.query(models.Shelf.shelf_pkey)\ .select_from(models.Shelf)\ .join(models.Device, models.Device.device_pkey == models.Shelf.device_pkey)\ .filter(models.Device.store_pkey == store_pkey, models.Device.device_id == device_id, models.Shelf.shelf_floor == d.shelf_floor)\ .first().shelf_pkey cell_pkey = session.query(models.Cell.cell_pkey).filter_by( shelf_pkey=shelf_pkey, cell_column=d.cell_column).first().cell_pkey # get loadcells loadcells = session.query(models.Loadcell).filter_by( shelf_pkey=shelf_pkey, loadcell_column=d.loadcell_column).first() if loadcells is None: # insert loadcell session.add( models.Loadcell(shelf_pkey=int(shelf_pkey), cell_pkey=int(cell_pkey), loadcell_column=d.loadcell_column)) else: # update loadcell loadcells.cell_pkey = cell_pkey session.commit() except Exception as e: session.rollback() raise e finally: session.close()
def addDeviceIfNecessary(self, device_id, user): # NDB's caching means this won't hit datastore very often. query = models.Device.query(models.Device.device_id == device_id) if not query.iter().has_next(): models.Device(user=user, device_id=device_id).put()