def build_dict_from_table_details(self, table): request = {} request_detail = {} isFirstRow = True for row in table: if isFirstRow: #if creating a request for the first time request = {} request['req_id'] = row[0] request['date'] = row[1] request['requester'] = Requester().build_dict_from_row( row[2:10]) request['details'] = [] request_detail['qty'] = row[10] request_detail['resource'] = Resource( ).build_dict_from_row_category(row[11:]) isFirstRow = False else: request_detail['qty'] = row[10] request_detail['resource'] = Resource( ).build_dict_from_row_category(row[11:]) request['details'].append(request_detail) request_detail = {} return request
def build_dict_from_table_no_nid(self, table): requests = [] request = None request_detail = None isFirstRow = True for row in table: if not request or request['reqId'] != row[ 0]: #if creating a transaction for the first time if request: requests.append(request) request = {} request['reqId'] = row[0] request['reqDate'] = row[1] request['details'] = [] request_detail = {} request_detail['qty'] = row[2] request_detail['resource'] = Resource( ).build_dict_from_row_category(row[3:]) else: request_detail['qty'] = row[2] request_detail['resource'] = Resource( ).build_dict_from_row_category(row[3:]) request['details'].append(request_detail) request_detail = {} requests.append(request) return requests
def build_dict_from_table(self, table): transaction = {} transaction_detail = {} isFirstRow = True for row in table: if isFirstRow: #if creating a transaction for the first time transaction = {} transaction['transactionId'] = row[0] transaction['total'] = row[1] transaction['purchaseId'] = row[2] transaction['supplier'] = Supplier().build_dict_from_row( row[3:11]) transaction['details'] = [] transaction_detail['qty'] = row[11] transaction_detail['purchase_price'] = row[12] transaction_detail['resource'] = Resource( ).build_dict_from_row_category(row[13:]) isFirstRow = False else: transaction_detail['qty'] = row[11] transaction_detail['purchasePrice'] = row[12] transaction_detail['resource'] = Resource( ).build_dict_from_row_category(row[13:]) transaction['details'].append(transaction_detail) transaction_detail = {} return transaction
def build_dict_from_table_details(self, table): announcement = {} announcement_detail = {} isFirstRow = True for row in table: if isFirstRow: #if creating a announcement for the first time announcement = {} announcement['ann_id'] = row[0] announcement['date'] = row[1] announcement['supplier'] = Supplier().build_dict_from_row( row[2:11]) announcement['details'] = [] announcement_detail['qty'] = row[11] announcement_detail['price_at_time'] = row[12] announcement_detail['resource'] = Resource( ).build_dict_from_row_category(row[13:]) isFirstRow = False else: announcement_detail['qty'] = row[11] announcement_detail['price_at_time'] = row[12] announcement_detail['resource'] = Resource( ).build_dict_from_row_category(row[13:]) announcement['details'].append(announcement_detail) announcement_detail = {} return announcement
def create_resource(tower, lat, lon, quantity): for i in range(quantity): resource = ResourceGenerator(lat, lon) resource_db = Resource(type=str(resource.type), lat=resource.lat, lon=resource.lon, quantity=resource.quantity, name=str(resource.name), description=str(resource.description), tower_id=tower) resource_db.save() message = resource.name + " appeared (lat: " + str( resource.lat / 100000) + ", lon: " + str( resource.lon / 100000) + ") quantity: " + str( resource.quantity) send_message(resource.name + " appeared") socketio.emit('resource_spawned', { 'point': { 'lat': (resource.lat / 100000), 'lon': (resource.lon / 100000) }, 'id': str(resource_db.id), 'towerid': str(tower), 'label': resource.type[0].capitalize(), 'description': resource.description, 'title': resource.name, 'quantity': quantity }, namespace='/main')
def build_dict_from_table_no_sup(self, table): announcements = [] announcement = None announcement_detail = None isFirstRow = True for row in table: if not announcement or announcement['annId'] != row[ 0]: #if creating a transaction for the first time if announcement: announcements.append(announcement) announcement = {} announcement['annId'] = row[0] announcement['annDate'] = row[1] announcement['details'] = [] announcement_detail = {} announcement_detail['qty'] = row[2] announcement_detail['priceAtTime'] = row[3] announcement_detail['resource'] = Resource( ).build_dict_from_row_category(row[4:]) else: announcement_detail['qty'] = row[2] announcement_detail['priceAtTime'] = row[3] announcement_detail['resource'] = Resource( ).build_dict_from_row_category(row[4:]) announcement['details'].append(announcement_detail) announcement_detail = {} announcements.append(announcement) return announcements
def test_read_missing_id(self, mock_get_db_connection): """Raises an error when the id was not provided at init""" r = Resource(resource='test') with pytest.raises(OperationOutcome, match='Resource ID is required'): r = r.read() assert mock_get_db_connection.return_value.read.call_count == 0
def test_create_missing_resource(self, mock_get_db_connection): """Raises an error when the resource data was not provided at init""" r = Resource(id='id') with pytest.raises(OperationOutcome, match='Missing resource data to create \ a Resource'): r = r.create() assert mock_get_db_connection.return_value.create.call_count == 0
def decode_resource(self, type_name): with open(os.path.join(self._path, u'Resources', type_name + u'.json')) as f: data = json.load(f) if data[u'kind'] == u'Resource': res = Resource(data[u'name'], data[u'description']) for method in data[u'methods']: res.add_method(self._decode_method(method)) return res
def test_patch_missing_id(self, mock_get_db_connection): """Raises an error when the resource id was not provided at init""" r = Resource(resource='test') with pytest.raises(OperationOutcome, match='Resource ID is required to \ patch a resource'): r = r.patch({'some': 'patch'}) assert mock_get_db_connection.return_value.update.call_count == 0
def test_update_missing_resource(self, mock_get_db_connection): """Raises an error when the resource was not provided""" r = Resource(resource='test') with pytest.raises(OperationOutcome, match='Resource data is required to \ update a resource'): r = r.update(None) assert mock_get_db_connection.return_value.update.call_count == 0
def test_delete_missing_id(self, mock_get_db_connection): """Raises an error when the patch data is not provided """ r = Resource(resource='test') with pytest.raises(OperationOutcome, match='Resource ID is required to delete \ it'): r = r.delete() assert mock_get_db_connection.return_value.update.call_count == 0
def populate_resource(reg, node): res = Resource(get_complex_type_name(node), get_resource_description(node)) for ch in node.children: method = get_method(ch) res.add_method(method) reg.add_type(res)
def decode_resource(self, name): resource = Resource(name, u'') with open(os.path.join(self._path, u'Methods', name + u'.json')) as f: data = json.load(f) for method_name in data: method_data = data[method_name] fields = method_data.get(ImplMethodAttributes.FIELDS, {}) fields_validation = method_data.get( ImplMethodAttributes.FIELDS_VALIDATION, {}) private_fields = method_data.get( ImplMethodAttributes.PRIVATE_FIELDS, {}) fields_descriptions = method_data.get(ImplResourceAttributes.FIELD_DESCRIPTION, {}) method = ImplMethod(method_name) method.frequency = method_data.get(ImplMethodAttributes.FREQUENCY, None) method.auth_required = not method_data.get(ImplMethodAttributes.NO_AUTH_REQUIRED, False) method.is_private = method_data.get(ImplMethodAttributes.PRIVATE, False) method.request_limit = method_data.get(ImplMethodAttributes.REQUEST_LIMIT, None) method.request_limit = method_data.get(ImplMethodAttributes.TIME_LIMIT, None) method.result_type_name = deserialize.SchemaDeserializer._decode_type_string( method_data.get(ImplResourceAttributes.RESULT_TYPE, None)) method.deprecated = method_data.get(ImplResourceAttributes.DEPRECATED, False) method.description = method_data.get(ImplResourceAttributes.DESCRIPTION, '') for perm in self._decode_permissions(name, method_name): method.add_permission(perm) resource.add_method(method) for field_name in fields: field = Deserializer._decode_field( field_name, fields[field_name], fields_descriptions.get(field_name, '')) method.add_field(field) for field_name in private_fields: field = Deserializer._decode_field( field_name, private_fields[field_name], fields_descriptions.get(field_name, '')) method.add_private_field(field) for query_name in fields_validation: query_data = fields_validation[query_name] for field_name in query_data: field = Deserializer._decode_field( field_name, query_data[field_name], '') method.add_query_field(query_name, field) return resource
def test_patch_missing_data(self, mock_get_db_connection): """Raises an error when the patch data is not provided """ test_id = {'id': 'id'} r = Resource(id=test_id['id']) with pytest.raises(OperationOutcome, match='Patch data is required to \ patch a resource'): r = r.patch(None) assert mock_get_db_connection.return_value.update.call_count == 0
def test_create_extra_id(self, mock_get_db_connection): """Raises an error when the resource data and an id were provided""" resource_data = {'my': 'resource'} test_id = {'id': 'id'} r = Resource(id=id, resource=resource_data) with pytest.raises(OperationOutcome, match='Cannot create a resource with \ an ID'): r = r.create() assert mock_get_db_connection.return_value.create.call_count == 0
def edit(): """ 新建/编辑资源 name 文件名 file_id 上传的文件ID type 文件类型 :return: """ name = request.form.get('name') type = request.form.get('type') file_id = request.form.get('file_id') if not name or not type or not file_id: return res(code=Errors.PARAMS_REQUIRED) if type not in Resource.RESOURCE_TYPE: return res(code=Errors.UPLOAD_FORMAT_LIMITATION) r = Resource.objects(file_id=file_id).first() if not r: r = Resource() r.name = name r.type = type r.file_id = file_id r.save() return res(data=r.as_dict())
def test_delete(self, mock_get_db_connection): """Calls the delete method of the fhirbase client """ test_id = {'id': 'id'} mock_get_db_connection.return_value.delete.return_value = None r = Resource(id=test_id['id']) r = r.delete() mock_get_db_connection.return_value.delete.assert_called_once_with({ 'resourceType': 'Resource', 'id': test_id['id'] }) assert r.resource is None assert r.id is None
def test_read(self, mock_get_db_connection): """Calls the read method of the fhirbase client and registers the resource """ test_id = {'id': 'id'} read_ret_data = {'my': 'resource', **test_id} mock_get_db_connection.return_value.read.return_value = read_ret_data r = Resource(id=test_id) r = r.read() mock_get_db_connection.return_value.read.assert_called_once_with({ 'resourceType': 'Resource', 'id': r.id }) assert r.resource == read_ret_data
def upload_resource(file, uid, filepath, public_access, filename=None, file_ext=None): from models.resource import Resource from services.user_services import get_user_by_uid from models import db from os import path from os import makedirs secure_filename(file.filename) secure_filepath(filepath) # check user privilege if get_user_by_uid(uid).privilege.upload_file is False: return None if not path.exists(RESOURCE_FOLDER + filepath): makedirs(RESOURCE_FOLDER + filepath) if filename is None: filename = file.filename else: if file_ext is None: filename = filename + path.splitext(file.filename)[1] else: filename = filename + '.' + file_ext # filename clash resolve if path.exists(path.join(RESOURCE_FOLDER + filepath, file.filename)): ext = '.' + filename.split('.')[-1] name = filename[:len(filename)-len(ext)] count = 1 while path.exists(path.join(RESOURCE_FOLDER + filepath, name + '(' + str(count) + ')' + ext)): count += 1 filename = name + '(' + str(count) + ')' + ext # save file file.save(path.join(RESOURCE_FOLDER + filepath, filename)) # update database new_resource = Resource(resource_name=filename, resource_path=filepath, uploader_uid=uid, public_access=public_access) db.session.add(new_resource) db.session.commit() return new_resource
def _build_resource(self, request: Request) -> Resource: # get last el or empty string if request.url[-1:] == '/': file_url = request.url[1:] + 'index.html' else: file_url = request.url[1:] if len(file_url.split('../')) > 1: raise ForbiddenError filename = os.path.join(self._conf.document_root, file_url) try: size = os.path.getsize(filename) except OSError: raise NotFoundError try: content_type = ContentTypes[file_url.split('.')[-1]] except KeyError: content_type = ContentTypes.plain return Resource(filename=filename, file_url=file_url, content_type=content_type, size=size)
def validate(self, data: Dict): super(Policy, self).validate(data) effect = data.get('effect') action = data.get('action') resource = data.get('resource') if effect not in ['allow', 'deny']: raise ValidationError( message=f'unsupported effect "{effect}"' ) if action != '*' and int(action) not in [action.value for action in ActionTypes]: raise ValidationError( message=f'unsupported action "{action}"' ) if resource != '*': resource_obj = next( (resource for resource in Resource.get(filters={'name': [resource]})), None ) if not resource_obj: raise ValidationError( message=f'Resource Not Found "{resource}"' )
def resource_found(point): print(point) if isinstance(point, str): point = json.loads(point) idx = uuid.UUID(point['id']) tower_id = uuid.UUID(point['tower_id']) resource = None try: resource = Resource.get(tower_id=tower_id, id=idx) except DoesNotExist as e: print(e) if resource: print(resource) if not current_user.is_authenticated: user_id = uuid.UUID('5da5957c-9775-4f5f-b257-4a93a520b15c') else: user_id = current_user.id user_resource = UserFoundResource(id=resource.id, user_id=user_id, type=resource.type, lat=resource.lat, lon=resource.lon, quantity=resource.quantity, name=resource.name, description=resource.description, tower_id=resource.tower_id) user_resource.save() resource.delete() towerLocation = TowerLocation.get(lat=round(resource.lat / 1000), lon=round(resource.lon / 1000)) create_resource(str(tower_id), towerLocation.lat, towerLocation.lon, 1)
def add_resource(self, name, path, resource_type, project_id, project_path, create=False): """ Adds a resource to project Args: name (str): Name of the resource path (str): Path of the resource, relative to project resource_type (str): Type of the resource. Either 'tex' or 'config' project_id (str): Id of the project to which the resource will be added project_path (str): Path of the project create (bool, optional): Whether a file should be created to project. Defaults to False. Returns: Resource: created resource """ resource = Resource(name, path, resource_type) project_store.add_resource(resource, project_id) full_path = project_path / path / name if create and not file_system.file_exists(full_path): file_system.create_directory(Path(project_path) / path) file_system.create_file(full_path) project_store.update_timestamp(project_id) return resource
def build_dict_from_row_resource(self, row): result = {} result['req_id'] = row[0] result['date'] = row[1] result['qty'] = row[2] result['resource'] = Resource().build_dict_from_row_category(row[3:]) return result
def build_dict_from_row(self, row): result = {} result['resource'] = Resource().build_dict_from_row_category(row[0:4]) result['supplier'] = Supplier().build_dict_from_row_region(row[4:10]) result['currentPricePerItem'] = row[10] result['qty'] = row[11] return result
def test_create(self, mock_get_db_connection): """Calls the create method of the fhirbase client and registers the ID """ resource_data = {'my': 'resource'} test_id = {'id': 'id'} create_ret_data = {**resource_data, **test_id} mock_get_db_connection.return_value.create.return_value = \ create_ret_data r = Resource(resource=resource_data) r = r.create() mock_get_db_connection.return_value.create.assert_called_once_with({ 'resourceType': 'Resource', **resource_data }) assert r.id == test_id['id'] assert r.resource == create_ret_data
def getResourceById(self, rid): dao = ResourcesDAO() row = dao.getResourceById(rid) if not row: return jsonify(Error="Resource Not Found"), 404 else: resource = Resource().build_dict_from_row(row) return jsonify(resource)
def getAllResources(self): dao = ResourcesDAO() resources_list = dao.getAllResources() result_list = [] for row in resources_list: result = Resource().build_dict_from_row(row) result_list.append(result) return jsonify(result_list)
def test_update_without_id(self, mock_get_db_connection): """Calls the update method of the fhirbase client and creates the resource """ test_id = {'id': 'id'} resource_data = {'my': 'resource'} update_data = {'test': 'two'} create_ret_data = {**update_data, **test_id} mock_get_db_connection.return_value.create.return_value = \ create_ret_data r = Resource(resource=resource_data) r = r.update(update_data) mock_get_db_connection.return_value.create.assert_called_once_with({ 'resourceType': 'Resource', **update_data }) assert r.resource == create_ret_data assert r.id == test_id['id']
def build_dict_from_row_transactions(self, row): result = {} result['tid'] = row[0] result['transactionAmmount'] = row[1] result['sid'] = row[2] #Foreign Key from Supplier result['qty'] = row[3] result['transactionPrice'] = row[4] result['resource'] = Resource().build_dict_from_row_category(row[5:]) return result
def test_init_with_resource(self, mock_get_db_connection): """Initializes resource and resource_type""" resource_data = {'my': 'resource'} r = Resource(resource=resource_data) assert mock_get_db_connection.call_count == 1 assert r.db == mock_get_db_connection.return_value assert r.id is None assert r.resource == resource_data assert r.resource_type == 'Resource'
async def post_resources(resource: Resource): con = connect_db() cur = con.cursor() cur.execute( f"INSERT INTO resources {resources_columns} VALUES ('{resource.title}', {resource.amount}, '{resource.unit}'," f" {resource.price}, '{resource.date}') RETURNING *") con.commit() con.close() return resource.dict(exclude={'id', 'cost'})