def devices_import(): try: file_prefix = 'device_import_' + g.tenant_uid file_name = excels.save(request.files['file'], name=file_prefix + '.') except UploadNotAllowed: error = {'Upload': 'Upload file format error'} raise APIException(errors=error) file_path = excels.path(file_name) import_url = current_app.config.get('IMPORT_EXCEL_TASK_URL') request_json = { 'filePath': file_path, 'tenantID': g.tenant_uid, 'userIntID': g.user_id, 'language': g.language } with SyncHttp() as sync_http: response = sync_http.post(import_url, json=request_json) handled_response = handle_task_scheduler_response(response) if handled_response.get('status') == 3: query_status_url = url_for('base.get_task_scheduler_status')[7:] task_id = handled_response['taskID'] record = { 'status': 3, 'taskID': task_id, 'message': 'Devices import is in progress', 'result': { 'statusUrl': f"{query_status_url}?taskID={task_id}" } } else: record = { 'status': 4, 'message': handled_response.get('error') or 'Devices import failed', } return jsonify(record)
def upload_file(): file_type = request.args.get('fileType', None, type=str) file_type_dict = { 'package': { 'type': 1, 'upload_set': packages }, 'image': { 'type': 2, 'upload_set': images } } if file_type not in file_type_dict.keys(): raise ParameterInvalid(field='fileType') try: unique_name = hashlib.md5((str(g.user_id) + str(time.time())).encode()).hexdigest() upload_set = file_type_dict.get(file_type).get('upload_set') request_file = request.files.get('file') file_name = upload_set.save(request_file, name=unique_name + '.') file_url = '/api/v1/download?fileType=%s&filename=%s' % (file_type, file_name) except UploadNotAllowed: raise APIException() request_dict = { 'fileName': file_name, 'displayName': request_file.filename, 'userIntID': g.user_id, 'fileType': file_type_dict.get(file_type).get('type') } upload_info = UploadInfo() created_upload = upload_info.create(request_dict) return jsonify({ 'name': created_upload.displayName, 'url': file_url, 'uploadID': created_upload.id }), 201
def validate_request(cls, request_dict=None, obj=None): request_get_json = request.get_json() if not request_get_json: raise APIException() if not request_dict: request_dict = request_get_json instance = cls() instance._obj = obj result = instance.load(request_dict) return result.data
def update_system_info(): request_dict = request.get_json() if not request_dict: raise APIException() if g.tenant_uid: raise DataNotFound(field='url') system_info_list = SystemInfo.query.all() for system_info in system_info_list: new_value = request_dict.get(system_info.key) if not new_value: continue if isinstance(new_value, bytes): new_value = new_value.decode('utf-8') system_info.value = new_value db.session.commit() return ''
def update_tenant(tenant_id): if g.role_id != 1: raise DataNotFound(field='url') tenant = Tenant.filter(Tenant.id == tenant_id).first_or_404() request_dict = request.get_json() if not request_dict: raise APIException() enable = request_dict.get('enable') if enable not in [0, 1]: raise FormInvalid(field='enable') update_dict = {'enable': enable} updated_tenant = tenant.update(update_dict) record = updated_tenant.to_dict() return jsonify(record)
def delete_messages(): try: ids = [int(i) for i in request.args.get('ids').split(',')] except ValueError: raise ParameterInvalid(field='ids') try: messages = Message.query \ .filter(Message.id.in_(ids), or_(Message.tenantID == g.tenant_uid, Message.tenantID.is_(None))) \ .all() for message in messages: if message.tenantID is None: raise APIException() db.session.delete(message) db.session.commit() except IntegrityError: raise ReferencedError() return '', 204
def handle_data(self, data): action = data.get('action') values = data.get('values') result = {} if isinstance(values, list) and len(values) > 0: result = values[0] in_data = { **action, 'alertDetail': result, "startTime": datetime.now() } topic = result.get('topic') # /$protocol/$tenant_id/$product_id/$device_id/$topic if topic: topic_info = re.split(r'/', topic[1:], 4) if len(topic_info) != 5: raise APIException() _, tenant_uid, _, device_uid, _ = topic_info in_data['tenantID'] = tenant_uid in_data['deviceID'] = device_uid return in_data
def run_code(): """ codec api response { "error": { "decode:": "error message" }, "output": { "status_code": 0, "result": { "data_type": "event", "data": { "humidity": { "time": 1547660823, "value": 34 }, "temperature": { "time": 1547660823, "value": -3.7 } } } } } """ request_json = CodeRunSchema.validate_request() analog_type = request_json.get('analogType') protocol = db.session.query(Product.cloudProtocol) \ .filter(Product.productID == request_json.get('productID')) \ .scalar() if protocol is None: raise DataNotFound(field='productID') request_url = f"http://{current_app.config['CODEC_NODE']}/api/v1/codec" with SyncHttp() as sync_http: response = sync_http.post(request_url, json=request_json) if response.responseCode != 200: try: errors = json.loads(response.responseContent) except Exception: errors = { 'codec': response.responseContent } raise APIException(errors=errors) response_json = json.loads(response.responseContent) # return response if it has error if 'error' in response_json: return jsonify(response_json) output_data = response_json.get('output') status_code = output_data.get('status_code') # If status code is 1(ERROR) # or analog type is 2(encode) # return response without validate if status_code == 1 or analog_type == 2: return jsonify(response_json) result = output_data.get('result') error_dict = {} validate_data, validate_error = DecodeSchema().load(result) for key, value in validate_error.items(): error_dict[key] = value[0][:-1] data_stream = DataStream.query \ .filter(DataStream.productID == request_json.get('productID'), DataStream.tenantID == g.tenant_uid, DataStream.topic == request_json.get('topic'), DataStream.streamID == validate_data.get('stream_id')) \ .first() if not data_stream: raise DataNotFound(field='data_stream') error, passed_data = validate_decode_response(data_stream, validate_data) error_dict.update(error) record = { 'output': { 'status_code': status_code, 'result': passed_data } } if error_dict: record['error'] = error_dict return jsonify(record)
def company_is_exist(self, value): tenant_type = request.get_json().get('tenantType') if value == '': raise APIException() if tenant_type == 2 and Tenant.query.filter_by(company=value).first(): raise DataExisted(field='company')