def get_all_devices(tenant): model = Device(tenant) results = model.get_devices() return [ device for device in results if device.get("isActive") or ( device.get("mobility") and device.get("powerType")) ]
def index(): index_form = request.form current_app.logger.info(request.form) search = False q = request.args.get('q') if q: search = True try: page = int(request.args.get('page', 1)) except ValueError: page = 1 device_obj = Device() total = device_obj.get_count() devices = device_obj.paginate(page, 8).items pagination = Pagination(css_framework='bootstrap3', link_size='sm', show_single_page=False, page=page, per_page=8, total=total, search=search, record_name='devices', format_total=True, format_number=True) template_data = { 'form': index_form, 'devices': devices, 'pagination': pagination } return render_template("/device/index.html", **template_data)
def register_device(request): """ Request handler when a new device installs the app We will need: 1. Device id 2. Device type 3. Push notification id these will ensure proper communication with the device """ if request.method == 'POST': json_data = json.loads(request.body) try: device_id = json_data['device_id'] device_model = json_data['model'] device_os = json_data['os'] except KeyError: print "Error: A posted question did not have a JSON object with the required properties" else: # See if the device id already exists try: device = Device.objects.get(device_id=device_id) except Device.DoesNotExist: device = None if device: return HttpResponse(json.dumps({ 'valid_id' : False }), content_type="application/json") else: device = Device(device_id=device_id, model=device_model, os=device_os) device.save() return HttpResponse(json.dumps({ 'valid_id' : True }), content_type="application/json")
def button_pressed(device_id, button_id): Device.button_pressed_on_device(device_id, button_id) device = Device.get_device_by_id(device_id) button = Button.get_button_by_id(device_id, button_id) rest_action.CallHipchatRestApi(device, button) rest_action.CallSlackRestApi(device, button) return Device.get_device_by_id(device_id).status
def edit(device_id): edit_form = request.form current_app.logger.info(request.form) if device_id == 0: return device_obj = Device() device = device_obj.get_by_id(device_id) if device is None: return if request.method == 'POST': try: device.hospital = request.form['hospital'] device.device_model = request.form['device_model'] device.device_index = request.form['device_index'] device.owner = request.form['owner'] device.status = request.form['status'] device.update_user = request.form['update_user'] print device device.save() return redirect('/device/index') except Exception, e: print e flash(u'编辑维修部品失败') current_app.logger.error(u'编辑维修部品失败')
def test_relationship(self): """Test relationships between users, devices, and statuses""" u = User('user1', 'user1_guid', 'Jon Doe', 'Jon', 'Doe', 'Department', '*****@*****.**') d = Device('device1', 'aa:bb:cc:dd:ee') s = Status('status-provider', 'in', dt.now()) self.session.add(s) self.session.add(u) self.session.add(d) d.user = u s.user = u self.session.commit() pprint(u) pprint(d) pprint(s) pprint(u.devices) pprint(u.statuses) assert d.user == u assert d in u.devices assert s.user == u assert s in u.statuses assert u.devices[0] == d assert u.statuses[0] == s
def report_metrics(request): # default failure response = HttpResponse("{success:false}", content_type='application/json') if request.method == 'POST': payload = request.body if request.META.get('HTTP_CONTENT_ENCODING', 'None') == 'gzip': payload = zlib.decompress(payload, zlib.MAX_WBITS | 32) data = json.loads(payload) device_name = data["log"]["hardware"]["deviceName"] test_time = data["log"]["session"]["reportTime"] try: device = Device.objects.get(pk=device_name) except Device.DoesNotExist: # catch the DoesNotExist error device = Device(name=device_name) device.last_update = test_time device.save() metric = PerformanceMetrics.objects.create(device=device, time=test_time, data=payload) metric.save() response = HttpResponse('{success:true}', content_type='application/json') return response
def save_device_uptime(tenant): device_model = Device(tenant) devices = device_model.get_all_devices() records = [] futures = [] executor = ThreadPoolExecutor() active_device_count = 0 for device in devices: if device.get('isActive'): active_device_count += 1 channel_id = device["device_number"] device_name = device["name"] if not (channel_id and device_name): print("this device could not be processed", device_name) continue futures.append( executor.submit(get_device_records, tenant, channel_id, device_name, device.get('isActive'))) for future in futures: try: records.append(future.result()) except Exception as e: import sys from traceback import print_tb, print_exc from colored import fg, attr color_warning = fg('#FF6600') reset = attr('reset') print("error occurred while fetching data -", e) print(color_warning) print_exc(file=sys.stdout) print(reset) network_uptime = 0.0 if records: network_uptime = (sum( record.get("uptime", 0.0) for record in records if record.get('is_active')) / active_device_count) device_uptime_model = DeviceUptime(tenant) device_uptime_model.save_device_uptime(records) created_at = datetime.utcnow() created_at = created_at.replace(tzinfo=UTC) network_uptime_record = { "network_name": tenant, "uptime": network_uptime, "created_at": created_at } print("network uptime", network_uptime_record) network_uptime_model = NetworkUptime(tenant) network_uptime_model.save_network_uptime([network_uptime_record])
def delete(self, id_): if id_: device = Device.get_by_id(id_) if device: Device.delete(device.id_) return jsonify({ "error": False, "message": 'Device ID ' + str(id_) + ' Deleted'}) else: return jsonify({"error": True, "message": f'Device ID {id_} Not Found'}) return 'Not Found'
def setUp(self): scheduler.start() self.app = create_app('testing') self.client = self.app.test_client self.devices = {'name': 'test'} with self.app.app_context(): db.create_all() db.session.add(Device(name='Test Fan', device_id='L-20', device_type=DeviceType.FAN)) db.session.add(Device(name='Test RF', device_id='101-1', device_type=DeviceType.RF)) db.session.commit()
def delete(device_id): #delete_form = request.form current_app.logger.info(request.form) if device_id == 0: return device_obj = Device() result = device_obj.delete(device_id) if not result: return return redirect('/device/index')
def get(self): query = self.request.get("q") device = Device(name = "Nokia", user_agent = "Some_UserAgent") device.put() productInfo = ProductInfo(device = device, mobile_browser = "Qix40", device_os = "Symbian") productInfo.put() template_values = { "device": device, "productInfo": productInfo } path = os.path.join(os.path.dirname(__file__), "templates/device.html") page = template.render(path, template_values) self.response.out.write(page)
def upload(self): """ uploads the given file of device readings to the database """ if request.method == "POST": data = request.files["data"] device = request.form["dev"] if device == "infer": device = data.filename.split("_")[0] Device.add_from_file(data.stream.read(), device) flash("Successfully uploaded data!") return redirect (url_for('uploadview.index', self=self)) return redirect (url_for('uploadview.index', self=self))
def update(self, request): d = Device( id_=request['id'], name=request['name'], user=request['user'], ip=request['ip'], instance_id=request['instanceId'], model=request['model'] ) Device.update(d) return jsonify(d.to_json())
def create(self, request): d = Device( name=request['name'], user=request['user'], ip=request['ip'], instance_id=request['instanceId'], model=request['model']) d.save() return jsonify(d.to_json())
def cpanel_open(request): user = request.user device_choices = Device.get_device_choices(Device()) os_choices = Device.get_os_choices(Device()) problem_choices = Report.get_problem_choices(Report()) return render_to_response('cpanel/open.html', { 'user' : user, 'device_choices' : device_choices, 'os_choices' : os_choices, 'problem_choices' : problem_choices }, context_instance=RequestContext(request))
def cpanel_open(request): user = request.user device_choices = Device.get_device_choices(Device()) os_choices = Device.get_os_choices(Device()) problem_choices = Report.get_problem_choices(Report()) return render_to_response('cpanel/open.html', { 'user': user, 'device_choices': device_choices, 'os_choices': os_choices, 'problem_choices': problem_choices }, context_instance=RequestContext(request))
def get_device(addr): try: device = Device.objects.get(mac=addr) except DoesNotExist: # Create the entry device = Device(mac=addr) try: vendor = EUI(addr).oui.registration().org except NotRegisteredError: vendor = "Unknown" device.vendor = vendor return device
def create(): devices = db.session.query(Device).all() """View for create devices""" if request.method == 'POST': tag = request.form['tag'] name = request.form['name'] is_gateway = request.form.get('is_gateway', False) description = request.form['description'] ip = request.form['ip'] device_parent = request.form['device_parent'] error = None if is_gateway: is_gateway = True if not tag or not name: error = 'No mandatory property is set.' else: device = Device.query.filter_by(tag=tag).first() if device is not None: error = "The tag is already exist." if error is not None: flash(error) else: try: directory = "device_data/" + tag if not os.path.exists(directory): os.makedirs(directory) if device_parent != "null": device = Device(tag=tag, name=name, description=description, is_gateway=is_gateway, ipv4_address=ip, device_parent=device_parent) else: device = Device(tag=tag, name=name, is_gateway=is_gateway, ipv4_address=ip, description=description) db.session.add(device) db.session.commit() return redirect(url_for('device.device_index')) except OSError as e: flash("Creation of the directory %s failed" % tag) except Exception as e: flash("DB Creation Failed") return render_template('device/create.html', devices=devices)
def testDeviceValidation(self): """ Test Device Validations """ numDevices = len(Device.objects.all()) # device = random.choice(Device.objects.all()) device = Device(registrationid=1234) device.identifier = '0' try: device.save() except: pass newNumDevices = len(Device.objects.all()) self.assertEqual(numDevices + 1, newNumDevices, "Device Model Validation is not working.")
def show(device_id): show_form = request.form current_app.logger.info(request.form) if device_id == 0: return device_obj = Device() device = device_obj.get_by_id(device_id) if device is None: return template_data = {'form': show_form, 'current_device': device} return render_template("/device/show.html", **template_data)
def parse_obj(self, obj): d = Device() d.id_ = obj[0] d.name = obj[1] d.user = obj[2] d.ip = obj[3] d.model = obj[4] d.created_at = obj[5] d.instance_id = obj[6] return d
def update_device(): if request.method == 'POST': info = request.json if not info['sn']: abort(400) device = Device.query.filter(Device.sn == info['sn']).scalar() if device: app.logger.debug("Device already exists!") if info.get('brand'): device.brand = info.get('brand') if info.get('model'): device.model = info.get('model') device.latitude = info.get('latitude') device.longitude = info.get('longitude') device.timestamp = datetime.now() else: app.logger.debug("Device doesn't exist!") device = Device(sn=info['sn']) device.brand = info.get('brand') device.model = info.get('model') device.latitude = info.get('latitude') device.longitude = info.get('longitude') device.timestamp = datetime.now() db.session.add(device) db.session.commit() return jsonify(device.to_json()) else: return "Please use 'post' method!"
def login(): identifier = request.form['device'] user_email = request.form['email'] if not Device.query.filter_by(identifier=identifier).count(): device = Device(identifier) try: device.user = User.query.filter_by(email=user_email).one() except NoResultFound: return jsonify(error="No user found with email {}".format(user_email)), 400 db.session.add(device) db.session.commit() return jsonify(error=None), 200 else: return jsonify(error="A user is already logged in on device {}".format(identifier)), 400
def setUp(self): self.full = Policy.objects.get(name = "full") self.blocked = Policy.objects.get(name = 'blocked') self.device_1 = Device(mac_address="58:94:6B:A4:DA:BC", ip_address="192.168.10.2") self.device_1.policy = self.full self.device_1.save() self.device_2 = Device(mac_address="48:5B:39:F8:5D:F9", ip_address="192.168.10.3") self.device_2.policy = self.full self.device_2.save() self.device_3 = Device(mac_address="58:94:6B:A4:D7:BC", ip_address="192.168.10.4") self.device_3.policy = self.blocked self.device_3.save() self.device_4 = Device(mac_address="8C:58:77:02:8E:5D", ip_address="192.168.11.125") self.device_4.policy = self.blocked self.device_4.save()
def addDevice(): form = DeviceForm() devices = Device.get_by_user(current_user.id) if form.validate_on_submit(): name = form.name.data tipodispositivo = form.tipodispositivo.data macaddress = form.macaddress.data id = current_user.get_id() device = Device(user_id=id, name=name, tipodispositivo=tipodispositivo, macaddress=macaddress) device.save() return redirect(url_for('index')) return render_template('addDevice_form.html', form=form, devices=devices)
def _save_device(cd): device = Device() device.id = cd['id'] or None device.description = cd['description'] device.patrimony_number = cd['patrimony_number'] device.category = cd['category'] device.save() return device
def show(device_id): show_form = request.form current_app.logger.info(request.form) if device_id == 0: return device_obj = Device() device = device_obj.get_by_id(device_id) if device is None: return template_data = { 'form': show_form, 'current_device': device } return render_template("/device/show.html", **template_data)
def get(self): logged = False devices = [x.nome for x in Device.query()] user = users.get_current_user() conversas = False plus_btn_url = '' if user: logged = True plus_btn_url = users.create_logout_url('/gcm_server') model_pessoa = ModelPessoa(user.user_id()) pessoa = model_pessoa.getPessoa() if pessoa != False: conversas = \ Conversa.query(Conversa.owner == pessoa.key).__iter__() if not conversas.has_next(): conversas = False else: pessoa = Pessoa(nome=user.nickname(),user_id=user.user_id()) pessoa.put() else: plus_btn_url = users.create_login_url('/gcm_server') path = os.path.join(os.path.dirname(__file__), \ 'templates/index.html') template_values = { "devices":devices, "logged":logged, "plus_btn_url":plus_btn_url, "user":user, "conversas":conversas } self.response.out.write(template.render(path,template_values))
def api_device(method, id, payload=None): """Retrieve device info, update its attributes, or delete a device for the current user.""" device = Device.load(id) app.logger.debug(device) if (device is None or device.uid != g.user.id ): abort(404) if method == 'GET': return device elif method == 'POST': if 'name' in payload: device.name = payload['name'] if 'push_id' in payload: device.push_id = payload['push_id'] try: db.add(device) db.commit() except IntegrityError: abort(400, 'Device name already exists') return device elif method == 'DELETE': db.delete(device) db.commit() return True
def show_histogram(): device_type = request.args.get("device_type", "") if device_type == "": return "{}" # 按照设备类型查询该类型下所有的设备,保留设备id和设备名称 device_metas = [{ "id": d.id, "name": d.name } for d in Device.select().where(Device.type == device_type)] # 构建response response = [] for d_meta in device_metas: if device_type == "temperature": week_values = [random.randrange(190, 325, 1) / 10.0 for i in range(7)] else: week_values = [random.randrange(200, 900, 1) / 10.0 for i in range(7)] # 获取最新的设备状态,对齐设备名称与最新值 latest_status = Status.select().where(Status.device_id == d_meta["id"]).order_by(Status.time.desc()) if len(latest_status) == 0: continue response.append({ "id": d_meta["id"], "name": d_meta["name"], "value": latest_status[0].value, "week_val": week_values }) return json.dumps(response, ensure_ascii=False)
def parse_data(dtg, addr, bssid): device = get_device(addr) recent = Device.objects(Q(events__timestamp__gte=datetime.utcnow() - timedelta(minutes=10)) | Q(events__dest__ne=bssid), mac=addr) if len(recent) == 0: event = Data() event.timestamp = datetime.utcnow() event.dest = bssid device.events.append(event) device.save() dev = selector.select('Device', mac=addr).first() if dev == None: dev = Node('Device', mac=addr, last_seen=str(datetime.utcnow()), vendor=device.vendor) graph.create(dev) bs = selector.select('Device', mac=bssid).first() if bs == None: bs = Node('Device', mac=bssid, vendor=device.vendor, last_seen=str(datetime.utcnow())) graph.create(bs) if len(list(graph.match(start_node=dev, rel_type='data', end_node=bs))) == 0: rel = Relationship(dev, 'data', bs) graph.create(rel) print("%s[+] (%s) Data: %s (%s) -> %s" % (Term.BLUE, dtg, addr, device.vendor, bssid))
def parse_response(dtg, addr, dest, ssid): device = get_device(addr) recent = Device.objects(Q(events__timestamp__gte=datetime.utcnow() - timedelta(minutes=10)) | Q(events__dest__ne=ssid), mac=addr) if len(recent) == 0: event = Beacon() event.timestamp = datetime.utcnow() event.ssid = ssid device.events.append(event) device.save() dev = selector.select('Device', mac=dest).first() if dev == None: dev = Node('Device', mac=dest, last_seen=str(datetime.utcnow()), vendor=device.vendor) graph.create(dev) ss = selector.select('SSID', ssid=ssid).first() if ss == None: ss = Node('SSID', ssid=ssid, timestamp=str(datetime.utcnow())) graph.create(ss) if len(list(graph.match(start_node=dev, rel_type='probe', end_node=ss))) == 0: rel = Relationship(dev, 'response', ss) graph.create(rel) print('Hidden SSID Discovered %s -> %s' % (dest, ssid))
def parse_probe(dtg, addr, ssid): device = get_device(addr) recent = Device.objects(Q(events__timestamp__gte=datetime.utcnow() - timedelta(minutes=10)) | Q(events__ssid__ne=ssid), mac=addr) if len(recent) == 0: event = Probe() event.ssid = ssid event.timestamp = datetime.utcnow() device.events.append(event) device.save() dev = selector.select('Device', mac=addr).first() if dev == None: dev = Node('Device', mac=addr, last_seen=str(datetime.utcnow()), vendor=device.vendor) graph.create(dev) ss = selector.select('SSID', ssid=ssid).first() if ss == None: ss = Node('SSID', ssid=ssid, timestamp=str(datetime.utcnow())) graph.create(ss) if len(list(graph.match(start_node=dev, rel_type='probe', end_node=ss))) == 0: rel = Relationship(dev, 'probe', ss) graph.create(rel) print("%s[+] (%s) Probe: %s (%s) -> '%s'" % (Term.CYAN, dtg, addr, device.vendor, ssid))
def decorated_function(*args, **kwargs): authenticated = False if g.user.id is not None: authenticated = True elif request.authorization is not None: user = User.authenticate(request.authorization['username'], request.authorization['password']) if user is not None: g.user = user authenticated=True elif 'authorization' in request.headers: match = api_key_re.match(request.headers['authorization']) if match: user, device = Device.authenticate(match.group(1)) if user is not None: g.user = user g.device = device authenticated = True if authenticated: return f(*args, **kwargs) abort(403)
def plant_full_setup(app): testPlantType = PlantType(plantName, requiredWater, waterFrequency, minTemp, maxTemp, minHumidity, maxHumidity, minMoisture, maxMoisture, idealMoistureLevel, minLightIntensity, maxLightIntensity) device = Device(testMACAddress, testTime) client = app.test_client() db.session.add(device) db.session.add(testPlantType) db.session.commit() testPlant = Plant(type=testPlantType.id, level=testLevel, location=testLocation) print(testPlantType.id) db.session.add(testPlant) db.session.commit() yield "" db.session.delete(testPlant) db.session.delete(testPlantType) db.session.delete(device) # num_rows_deleted = db.session.query(Plant).delete() db.session.commit()
def login(): form = LoginForm(request.form) if request.method == 'POST': username = request.form['username'] password = request.form['password'] # A complex query # SELECT * FROM Users WHERE username = ? OR email = ? user = User.query.filter( or_(User.username == username, User.email == username)).first() if user or user_email: if user.check_password(password): active_user = ActiveUser.query.filter_by( user_id=user.id).first() if not active_user: active = ActiveUser(user_id=user.id) db.session.add(active) db.session.commit() client_UUID = str(uuid.uuid4()) device = Device(uuid=client_UUID, user_id=user.id) db.session.add(device) db.session.commit() session['device_uuid'] = client_UUID session['device_id'] = device.id session['logged_in'] = True session['user_id'] = user.id session['user_username'] = user.username flash("Log in successful", "success") return redirect(url_for('chat')) flash("Passwords do not match!", "error") return render_template('login.html', form=form) flash("Username not found, consider registering?", "error") return render_template('login.html', form=form) return render_template('login.html', form=form)
def device_record(db): device = Device(**device_mock) db.session.add(device) db.session.commit() return device
def get(self): # get recent status updates and filter by device ID if specified device_id = int(self.request.path.split("/")[1]) device = Device.get_by_key_name(str(device_id)) if not device: logging.info("Unknown device") self.redirect("/") return # expire status updates that are 30 minutes old expire_at = datetime.datetime.now() - datetime.timedelta(minutes=30) current_state = device.state if current_state: # device has status history if expire_at > device.updated: current_state = "unknown" else: # device status is unknown (has this device not come online yet?) current_state = "unknown" ready = device.ready subscriber_list = device.subscriber_set # only select those with active triggers subscriber_list.filter("trigger_state = ", "ready") template = template_env.get_template("device.html") context = { "device": device, "current_state": current_state, "ready": ready, "subscriber_list": subscriber_list, "datetime": datetime.datetime.now(), } self.response.out.write(template.render(context))
def add_device(request): render_dict = {} success = False if request.method == 'POST': form = AddDeviceForm(request.POST) if form.is_valid(): dev = Device(uid= form.cleaned_data["uid"], owner=request.user, nickname= form.cleaned_data["nickname"]) dev.save() success = True form = AddDeviceForm() render_dict['success'] = success else: form = AddDeviceForm() render_dict["form"] = form return render_to_response("add_device.html", render_dict, context_instance=RequestContext(request))
def check_stockout(self, trigger=None): """ 检查设备缺货情况 """ device = self.device category = device.category meta_list = json.loads(category.road_meta_list) is_stockout = False for road in device.road_set: meta_info = meta_list[int(road.no) - 1] if road.amount <= meta_info["lower_limit"]: is_stockout = True break if trigger: meta_info = meta_list[int(trigger.no) - 1] if trigger.amount <= meta_info["lower_limit"]: helper = SMSHelper() helper.send_lack_warning(device) stockout_at = dte.now() if is_stockout == device.is_stockout: return qs = Device.update(is_stockout=is_stockout, stockout_at=stockout_at) \ .where(Device.id == device.id) qs.execute() if is_stockout: logger.info("[device](%s) 标记为缺货", device.no) else: logger.info("[device](%s) 取消缺货标记", device.no)
def create(self, **kwargs): """ 新建设备 """ assert self.device is None if "category" not in kwargs: cat = self.choose_device_category(kwargs["no"]) if not cat: logger.error("[device](%s) 未找到对应型号", kwargs["no"]) raise Exception("未找到对应型号") kwargs["category"] = cat if "name" not in kwargs: kwargs["name"] = kwargs["no"] category = kwargs["category"] device = Device.create(**kwargs) device.save() for i in range(category.road_count): road = Road.create( device=device, no="%02d" % (i + 1), ) road.save() self.device = device logger.info("[device](%s) 创建设备并初始化货道", device.no) return device
def ping(request): gw_id = request.GET.get('gw_id',"") sys_uptime = request.GET.get('sys_uptime',"") sys_memfree = request.GET.get('sys_memfree',"") sys_load= request.GET.get('sys_load',"") wifidog_uptime= request.GET.get('wifidog_uptime',"") gw_address = request.GET.get('gw_address',"") gw_port = request.GET.get('gw_port',"") try: device = Device.objects.get(Gw_Id = gw_id) except Device.DoesNotExist: device = Device(Gw_Id = gw_id,Gw_Address = gw_address, Gw_Port = gw_port) device.save() else: pass apd = APDevice(device = device, Sys_Uptime=sys_uptime,Sys_Memfree=sys_memfree, Sys_Load=sys_load, Wifidog_Uptime=wifidog_uptime) apd.save() return HttpResponse("Pong")
def update_account(id, username, password): manager = FindMyI(username, password) if manager.get_partition(): manager.update_devices() for device in manager.devices: device_obj = Device.query.filter_by(aid=device['aid']).first() if device_obj is None: device_obj = Device() device_obj.user_id = id device_obj.aid = device['aid'] device_obj.name = device['name'] device_obj.device_name = device['device_display_name'] db.session.add(device_obj) db.session.commit() if 'located' in device: print device location = Location(device_obj.id, device['longitude'], device['latitude'], device['accuracy'], datetime.datetime.fromtimestamp(device['timestamp']/1000.0)) db.session.add(location) db.session.commit()
def api_devices_register(method, payload): """Register a new device.""" if 'name' in payload: try: device = Device(g.user, payload['name']) if 'push_id' in payload: device.push_id = payload['push_id'] db.add(device) db.commit() return { 'api_key': device.api_key, 'device': device, } except IntegrityError: abort(400, 'Device name already exists') abort(400, 'Missing payload parameters')
def post(self): # Check arguments args = user_parser.parse_args() if not args["email"] or not args["password"]: abort(406) # Check for duplicate emails if User.query.filter(User.email == args["email"]).first() is not None: abort(409) # Add user user = User(args["email"], args["password"]) if args["phone"]: user.phone = args["phone"] db.session.add(user) db.session.commit() # Add current device for the user device = Device(user.id, get_device()) device.active = True db.session.add(device) db.session.commit() return user, 201
def _process_arp_entry(arp_match_sets): """ We received a line of data from the ARP system on a remote router """ logger = logging.getLogger('dri.custom') for match_set in arp_match_sets: #logger.info( ">>> UPLOAD: processing data: %s" % str(match_set)) ip_address, mac_address = match_set if ip_address == "<incomplete>": logger.info( ">>> UPLOAD: Ignoring incomplete-data for: %s" % mac_address) continue records = Device.objects.filter(mac_address = mac_address) if len(records) == 0: device = Device() else: if len(records) > 1: logger.error("Too many records for %s" % mac_address) device = records[0] device.mac_address = mac_address device.ip_address = ip_address device.save()
def clean(self): cleaned_data = super(FwProfileCommon, self).clean() devices = cleaned_data.get("devices") if not all(map(lambda x: x.isalnum(), devices)): raise forms.ValidationError(self.ERROR_ALPHANUMERIC) for device in devices: if not Device.exists(device): raise forms.ValidationError(self.ERROR_NONEXISTENT_DEVICE % device) cleaned_data["devices"] = " ".join(devices) return cleaned_data
def post(self): device_id = self.request.get('device_id') device = Device.get_by_key_name(device_id) if not device: self.response.out.write('<p>Device does not exist</p>') return email = self.request.get('email') subscriber = Subscriber(device=device, email=email) subscriber.trigger_state = "Ready" subscriber.put() self.response.out.write('<p>Subscribed</p>')
def check_device(request, allow_create=True): ''' 根据设备的http请求 检查设备的注册情况返回有效设备对象 涉及http参数 HITACDMFun、SN ''' # try: #---参数 HITACDMFun 必须为 ['HIT','HIT Corporation','iCON','Rentris','Secure'] 成员 # re_device = request.GET["HITACDMFun"] # if re_device: # if re_device not in ['HIT','HIT Corporation','iCON','Rentris','Secure']: # return None # else: # return None # except: # return None try: sn = request.GET["SN"] except: sn = request.raw_post_data.split("SN=")[1].split("&")[0] try: device=get_device(sn) except ObjectDoesNotExist: #---正在请求服务器的设备没有登记过 if "mysite.att" in settings.INSTALLED_APPS and allow_create and not request.REQUEST.has_key('PIN') and ( #没有查询用户信息的话,可以注册该考勤机 len(sn) >= 6 and settings.ICLOCK_AUTO_REG): #若SN正确,且设置可以自动注册 from mysite.personnel.models.model_area import Area device = Device( sn=sn, alias="auto_add", #---设备别名 last_activity=datetime.datetime.now(), area=Area.objects.all()[0], #---默认设在第一个考勤区域 ipaddress=request.META["REMOTE_ADDR"]) device.save(force_insert=True, log_msg=False) append_dev_cmd(device, "INFO") #---添加设备请求命令 定义此为 INFO 操作 else: return None if device.status in (STATUS_STOP, STATUS_PAUSED): #--- 设备处于暂停或者停止状态 return None device.last_activity=datetime.datetime.now() return device
def addDevice(request): res={'code':1,'message':'错误,请重试'} try: reg_uid=request.GET['uid'] reg_uname=request.GET['uname'] reg_upwd=request.GET['upwd'] reg_father=request.GET['father'] except: return HttpResponse(json.dumps(res)) reged=False try: device=Device.objects.get(uid=reg_uid) except Device.DoesNotExist: reged=False else: reged=True if(reged): res['code']=0 res['message']='设备曾经注册,可直接使用' return HttpResponse(json.dumps(res)) else: reged=False try: user=Device.objects.get(uname=reg_uname) except Device.DoesNotExist: reged=False else: reged=True if reged: res['message']='用户名已被注册' return HttpResponse(json.dumps(res)) else: device=Device() device.uid=reg_uid device.uname=reg_uname try: sp=spread.objects.get(fid=reg_father) device.fathername=sp.uid fdev=Device.objects.get(uid=sp.uid) fdev.spreadnum+=1 fdev.save() except: pass device.money=0 user=Muser() user.uname=reg_uname user.upwd=reg_upwd device.save() user.save() res['code']=0 res['message']='注册成功' return HttpResponse(json.dumps(res))
def subscribe(request): # POST CHECKINGS: if request.method != 'POST': return HttpResponseNotAllowed('POST') token_r = None type_r = None try: token_r = request.POST['token'] type_r = request.POST['type'] except MultiValueDictKeyError: return HttpResponseBadRequest('POST must contain "token" and "type"') # END OF POST CHECKINGS: device = None try: device = Device( user=request.user, token=token_r, type=type_r) with transaction.atomic(): device.save() except IntegrityError: try: device = request.user.devices.get(token=token_r, type=type_r) print "Device already registered, ok. %s" % str(device) except ObjectDoesNotExist: return HttpResponseBadRequest("A device with that token is already used by other user.") except FieldError: return HttpResponseBadRequest('Incorrect "type" value.') else: print "New device registered. %s" % str(device) return HttpResponse(json.dumps(device.preview(user=request.user)), mimetype='application/json')
def create(): create_form = request.form current_app.logger.info(request.form) if request.method == 'POST': hospital = request.form['hospital'] device_model = request.form['device_model'] device_index = request.form['device_index'] owner = request.form['owner'] # prepare Device device = Device(hospital, device_model, device_index, owner) device.status = request.form['status'] device.update_user = current_user.name print device try: device.save() return redirect('/device/index') except Exception, e: print e flash(u'添加维修部品失败') current_app.logger.error(u'添加维修部品失败')
def get(self, account_id): self.response.headers['Content-Type'] = 'application/json' try: account = Account.get_by_id(int(account_id)) devices = Device.query(ancestor=account.key).order(-Device.created) device_array = [] for device in devices: device_dict = device.to_dict(exclude=['created', 'updated']) device_dict['id'] = device.key.id() device_array.append(device_dict) result = {'devices': device_array} self.response.out.write(json.dumps(result)) except Exception as e: result = {'error': 'Unexpected error has occurred', 'message': e.message} self.response.set_status(500, json.dumps(result)) self.response.out.write(json.dumps(result))
def get(self): """Renders a set of forms to change a device's name""" user_id = users.get_current_user().user_id() group_key = memcache.get('group_key_%s' % user_id) error = self.request.get('error') if not group_key: query = Group.query(Group.owner_id == user_id) group_keys = query.fetch(1, keys_only=True) if not group_keys: self.redirect('/settings/enroll') return group_key = group_keys[0] memcache.set('group_key_%s' % user_id, group_key) devices = Device.query(ancestor=group_key) template_values = {'devices': devices, 'error': error} self.render_template('settings.html', template_values)