Beispiel #1
0
 def put(cls) -> Dict:
     '''
     Update instance and save to db.
     '''
     _lng = request.headers.get('Accept-Language')
     # print('content, resources, put, lng ->', _lng)
     fbp.set_lng(_lng)
     _user_id = get_jwt_identity()
     # print('content, resources, put, user id ->', _user_id)
     if not UserModel.find_by_id(_user_id).is_admin:
         # if not UserModel.find_by_id(get_jwt_identity()).is_admin:
         return cls.no_access()
     _request_json = {
         **request.get_json(), 'locale_id': _lng,
         'user_id': _user_id
     }
     _update_json = content_get_schema.load(_request_json)
     _content = ContentModel.find_by_identity_view_locale(
         identity=_update_json.get('identity'),
         view_id=_update_json.get('view_id'),
         locale_id=_update_json.get('locale_id'))
     if _content is None:
         return cls.not_found(identity=_update_json.get('identity'),
                              view_id=_update_json.get('view_id'),
                              locale_id=_update_json.get('locale_id'))
     _content.update(_update_json)
     return {
         'message':
         str(
             _("The content has been found and successfully updated. "
               "Details are in payload.")),
         'payload':
         content_schema.dump(_content)
     }, 200
def test_users_list_get_admin(client, access_token, user_instance, lng,
                              test_word, saved_view_instance):
    '''
    Right
    '''
    _view_gen00 = saved_view_instance()
    _view_gen01 = saved_view_instance()

    next(_view_gen00)
    next(_view_gen01)
    _admin = UserModel.find_by_id(1)
    _access_token_admin = access_token(_admin)
    headers = {
        'Authorization': f"Bearer {_access_token_admin}",
        'Accept-Language': lng
    }
    _resp = client.get(url_for('viewsglobal'), headers=headers)
    # print('\ntest_view_list_get_user, _resp ->', _resp.json.get('message'))
    assert _resp.status_code == 200
    assert isinstance(_resp.json, Dict)
    assert isinstance(_resp.json['payload'], List)
    assert len(_resp.json['payload']) >= 4
    assert _resp.json.get('message').find(test_word) != -1

    next(_view_gen00)
    next(_view_gen01)
Beispiel #3
0
 def post(cls) -> Dict:
     '''
     Create structure instance and save to db.
     '''
     _lng = request.headers.get('Accept-Language')
     fbp.set_lng(_lng)
     if not UserModel.find_by_id(get_jwt_identity()).is_admin:
         return cls.no_access()
     _request_json = request.get_json()
     # print('\nstructure resources, post, _lng ->', _lng)
     _search_json = {
         'view_id': _request_json.get('view_id'),
         'locale_id': _lng
     }
     _structure = structure_schema.load(
         {**_request_json, 'locale_id': _lng}, session=dbs_global.session)
     _structure_fm_db = StructureModel.find_by_ids(_search_json)
     if _structure_fm_db is not None:
         return cls.already_exists(**_search_json)
     error_info = _structure.save_to_db()
     if error_info is not None:
         return cls.error_message(error_info)
     return {
         'message': str(_(
             "The structure has been saved successfully. "
             "Details are in payload.")),
         'payload': structure_schema.dump(_structure)
     }, 201
Beispiel #4
0
 def put(cls) -> Dict:
     '''
     Update instance and save to db.
     '''
     _lng = request.headers.get('Accept-Language')
     fbp.set_lng(_lng)
     _user_id = get_jwt_identity()
     if not UserModel.find_by_id(_user_id).is_admin:
         return cls.no_access()
     _update_json = structure_get_schema.load(
         {**request.get_json(), 'locale_id': _lng, 'user_id': _user_id})
     _search_json = {
         'view_id': _update_json.pop('view_id'),
         'locale_id': _update_json.pop('locale_id')
     }
     _structure = StructureModel.find_by_ids(_search_json)
     # print('\nstructure, resources, put, _update_json ->', _update_json)
     if _structure is None:
         return cls.not_found(**_search_json)
     _structure.update(_update_json)
     return {
         'message': str(_(
             "The structure has been found and successfully updated. "
             "Details are in payload.")),
         'payload': structure_schema.dump(_structure)
     }, 200
Beispiel #5
0
 def delete(cls):
     '''
     Delete instance from db.
     '''
     _lng = request.headers.get('Accept-Language')
     fbp.set_lng(_lng)
     # print('cls, resources, view_id ->', request.args['view_id'])
     if not UserModel.find_by_id(get_jwt_identity()).is_admin:
         return cls.no_access()
     fbp.set_lng(request.headers.get('Accept-Language'))
     _requested_dict = {
         'view_id': request.args.get('view_id'),
         'locale_id': _lng
     }
     # testing fields
     _delete_json = structure_get_schema.load(_requested_dict)
     _structure = StructureModel.find_by_ids(_delete_json)
     if _structure is None:
         return cls.not_found(**_delete_json)
     _structure.delete_fm_db()
     return {
         'message': str(_(
             "The structure for view '%(view_id)s' locale "
             "'%(locale_id)s' has been found and "
             "successfully deleted.",
             view_id=_delete_json.get('view_id'),
             locale_id=_delete_json.get('locale_id')))}, 200
    def delete(cls) -> Dict:
        fbp.set_lng(request.headers.get('Accept-Language'))
        if not UserModel.find_by_id(get_jwt_identity()).is_admin:
            return cls.no_access()  # reject not admin to upload images
        _requested_dict = {
            'view_id': request.args.get('view_id'),
            'image_id': request.args.get('identity')
        }
        # print('\n_requested_dict ->', _requested_dict)
        for key in _requested_dict.keys():
            if not is_value_safe(_requested_dict.get(key)):
                return cls.illigal_simbols(_requested_dict.get(key))
        _view_id = _requested_dict.get('view_id')
        _image_id = _requested_dict.get('image_id')
        try:
            _found_image = find_image_any_format(
                _image_id, f'for_{_requested_dict.get("view_id")}')
            if not _found_image:
                return cls.not_found(view_id=_view_id, image_id=_image_id)
            os.remove(_found_image)
            return {
                'message':
                str(
                    _(
                        "An image for view '%(view_id)s' with identity "
                        "'%(image_id)s' successfully deleted.",
                        view_id=_view_id,
                        image_id=_image_id)),
            }, 200

        except FileNotFoundError:
            return cls.not_found(view_id=_view_id, image_id=_image_id)
 def patch(cls) -> Dict:
     '''
     Delete upper level element.
     json
         "view_id": "landing",
         "identity": "01",
     header
         Accept-Language: locale
     '''
     _lng = request.headers.get('Accept-Language')
     fbp.set_lng(_lng)
     _user_id = get_jwt_identity()
     if not UserModel.find_by_id(_user_id).is_admin:
         return cls.no_access()
     '''join values into one variable'''
     _kwargs = {**request.get_json(), 'locale_id': _lng}
     try:
         _index = int(_kwargs.pop('identity'))
         _page_instance = PageView.load_fm_db(ids=_kwargs)
         if _page_instance is None:
             return cls.not_found(
                 **_kwargs, identity=str(_index).zfill(2))
         _page_instance.remove_vals(index=_index)
         result = _page_instance.save_to_db(user_id=_user_id)
         if result is None:
             '''report success'''
             return cls.success(**{**_kwargs, 'identity': _index})
         else:
             return cls.error_message(error_info=result, status=500)
     except (WrongIndexError, WrongElementTypeError,
             WrongValueError, KeyError, IndexError) as e:
         '''report errors'''
         return cls.error_message(error_info=str(e), status=400)
     except Exception as e:
         raise e
Beispiel #8
0
    def delete(cls):
        '''
        Delete instance from db.
        '''
        # print('cls, resources, view_id ->', request.args['view_id'])
        _lng = request.headers.get('Accept-Language')
        fbp.set_lng(_lng)
        if not UserModel.find_by_id(get_jwt_identity()).is_admin:
            return cls.no_access()
        _requested_dict = {
            'view_id': request.args.get('view_id'),
            'identity': request.args.get('identity'),
            'locale_id': _lng,
            # 'locale_id': request.headers.get('Accept-Language')
        }
        # testing fields
        _delete_json = content_get_schema.load(_requested_dict)
        _content = ContentModel.find_by_identity_view_locale(**_delete_json)
        if _content is None:
            return cls.not_found(identity=_delete_json.get('identity'),
                                 view_id=_delete_json.get('view_id'),
                                 locale_id=_delete_json.get('locale_id'))

        _content.delete_fm_db()
        return {
            'message':
            str(
                _(
                    "The content on view '%(view_id)s' with locale '%(locale_id)s' and "
                    "identity '%(identity)s' has been found and successfully deleted.",
                    identity=_delete_json.get('identity'),
                    view_id=_delete_json.get('view_id'),
                    locale_id=_delete_json.get('locale_id')))
        }, 200
    def post(cls) -> Dict:
        """
        Used to upload an image file.
        I use params to select folder and filename to store pictures.
        File name should represent structure table identity.
        If same name used, old picture would be over written after
        notice to user.
        Admins are allowed to upload files only.
        """
        # it became by wergzeug {'image': FileStorage}, where 'image'
        # is field in our ImageSchema.
        # If everythin ok we will have data['image'] that is FileStorage
        # object

        fbp.set_lng(request.headers.get('Accept-Language'))
        if not UserModel.find_by_id(get_jwt_identity()).is_admin:
            return cls.no_access()  # reject not admin to upload images
        # print('image, resource, lng ->', request.headers.get('Accept-Language'))
        _requested_dict = {
            'view_id': request.args.get('view_id'),
            'image_id': request.args.get('identity')
        }
        for key in _requested_dict.keys():
            if not is_value_safe(_requested_dict.get(key)):
                # print('\nimage resource, params ->', _requested_dict.get(key))
                return cls.illigal_simbols(_requested_dict.get(key))
        # Testing whether file has been exists
        _image_id = _requested_dict.get('image_id')
        _view_id = _requested_dict.get('view_id')
        if find_image_any_format(_image_id,
                                 f'for_{_requested_dict.get("view_id")}'):
            return cls.already_exists(_image_id, _view_id)
        data = image_schema.load(request.files)
        _file_storage = data.get('image')
        _file_name = (f"{_image_id}{get_extention(_file_storage)}")
        _file_storage.filename = _file_name
        try:
            save_image(_file_storage,
                       folder=f'for_{_requested_dict.get("view_id")}')
            # image_path = save_image(data.get('image'), folder=_folder)
            # basename = get_basename(image_path)
            return {
                'message':
                str(
                    _(
                        "Image for view '%(view_id)s' with identity "
                        "'%(image_id)s' uploaded.",
                        view_id=_view_id,
                        image_id=_image_id))
            }, 201
        except UploadNotAllowed:
            extention = get_extention(data.get('image'))
            return {
                'message':
                str(
                    _("Extentions '%(extention)s' are not allowed",
                      extention=extention))
            }, 400
Beispiel #10
0
    def _method(args: dict = {}):
        _user_create_json = user_create_json(args).copy()
        _user = user_schema.load(_user_create_json)
        _user.save_to_db()
        _confirmation = ConfirmationModel(_user.id)
        _confirmation.save_to_db()
        '''Get user from db:'''
        user = UserModel.find_by_id(_user.id)

        return user
 def post(cls) -> Dict:
     '''
     Used to move existing elements within a block.
     It works with blocks only.
     It does not change view structure.
     Arguments:
     body:
     {
         "view_id": "landing",
         "identity": "01_vblock_txt", - (upper level index)_
             (block type)_(block subtype)_(low level element qnt)
         "item_index": 2, - low level index, ie serial number of item
             in block
         "direction": "up" - movement directin, 'up' - reduce item
             index.
         --------------------------------------------------------
         I use identity instead of block index to avoid additinaly
             getting information from db for the sake of productivity.
     }
     header:
     'Accept-Language' - locale
     '''
     _lng = request.headers.get('Accept-Language')
     fbp.set_lng(_lng)
     _user_id = get_jwt_identity()
     if not UserModel.find_by_id(_user_id).is_admin:
         return cls.no_access()
     '''join values into one variable'''
     _kwargs = {**request.get_json(), 'locale_id': _lng}
     try:
         '''get index out of variable that one is not needed in
             load_fm_db'''
         _item_index = _kwargs.pop('item_index')
         _direction = _kwargs.pop('direction')
         '''create upper level block element instance'''
         _block_instance = ContentElementsBlock.load_fm_db(**_kwargs)
         if _block_instance is None:
             '''report if block element instance is not available'''
             return cls.not_found(**_kwargs)
         '''handle the instance'''
         _block_instance.move(index=_item_index, direction=_direction)
         '''remove not needed key: value'''
         _identity = _kwargs.pop('identity')
         result = _block_instance.save_to_db_content(**_kwargs)
         if result is not None:
             return cls.error_message(error_info=result, status=500)
         else:
             '''report success'''
             return cls.success(**{**_kwargs, 'identity': _identity})
     except (WrongIndexError, KeyError) as e:
         '''report some wrong argument errors'''
         return cls.error_message(error_info=str(e), status=400)
     except Exception as e:
         # return cls.error_message(error_info=str(e), status=400)
         raise e
 def put(cls) -> Dict:
     """
     The method used for checking whether picure for specific view element is
     available. The method should be called before POST in order to get confirmation
     to replace image.
     """
     fbp.set_lng(request.headers.get('Accept-Language'))
     if not UserModel.find_by_id(get_jwt_identity()).is_admin:
         return cls.no_access()  # reject not admin to upload images
     _view_id = request.get_json().get('view_id')
     _image_id = request.get_json().get('identity')
     # print('images resources, _image_id ->', _view_id)
     # print('images resources, _image_id ->', _image_id)
     if find_image_any_format(_image_id,
                              f'for_{request.get_json().get("view_id")}'):
         return cls.already_exists(_view_id, _image_id)
     return cls.not_found(_view_id, _image_id)
Beispiel #13
0
    def get(cls):
        '''
        Get instance from db.
        '''
        # print('\nviews, get request arg ->', request.args.get('view_id'))

        if not UserModel.find_by_id(get_jwt_identity()).is_admin:
            return no_access()
        _search_json = view_global_get_schema.load(
            {'view_id': request.args.get('view_id')})
        _view = ViewGlobalModel.find_by_id(view_id=_search_json.get('view_id'))
        if _view is None:
            return cls.not_found(**_search_json)
        return {
            'message': str(_("Found, see payload.")),
            'payload': view_global_get_schema.dump(_view)
        }, 200
 def put(cls) -> Dict:
     '''
     Insert upper level element. It's dummy element, in case of block
         with one element inside.
     json
         "view_id": "landing",
         "identity": "01_vblock_txt",
     header
         Accept-Language: locale
     '''
     _lng = request.headers.get('Accept-Language')
     fbp.set_lng(_lng)
     _user_id = get_jwt_identity()
     if not UserModel.find_by_id(_user_id).is_admin:
         return cls.no_access()
     '''join values into one variable'''
     _kwargs = {**request.get_json(), 'locale_id': _lng}
     try:
         _identity = _kwargs.pop('identity')
         _splited_identity = _identity.split('_')
         _index = int(_splited_identity[0])
         _type = _splited_identity[1]
         if _type in ContentElementsBlock._types:
             _subtype = _splited_identity[2]
         else:
             _subtype = ''
         _page_instance = PageView.load_fm_db(ids=_kwargs)
         if _page_instance is None:
             return cls.not_found(**_kwargs, identity=_identity)
         _page_instance.insert_vals(
             index=_index, element_type=_type, subtype=_subtype,
             name=f'name of {_type}, {_subtype}')
         result = _page_instance.save_to_db(user_id=_user_id)
         if result is None:
             '''report success'''
             return cls.success(**{**_kwargs, 'identity': _identity})
         else:
             return cls.error_message(error_info=result, status=500)
     except (WrongIndexError, WrongElementTypeError,
             WrongValueError, KeyError) as e:
         '''report errors'''
         return cls.error_message(error_info=str(e), status=400)
     except Exception as e:
         raise e
 def patch(cls) -> Dict:
     '''
     Used for delete any element in a upper level block.
     Change structure withing specific block.
     Move all elements information (title and contents) accordenly.
     Arguments are {
         "view_id": "landing",
         "identity": "01_vblock_txt"  - (upper level index)_
             (block type)_(block subtype)_(low level element qnt)
         "item_index": 1, - low level index, ie serial number of item
             in block
     }
     '''
     _lng = request.headers.get('Accept-Language')
     fbp.set_lng(_lng)
     _user_id = get_jwt_identity()
     if not UserModel.find_by_id(_user_id).is_admin:
         return cls.no_access()
     _kwargs = {**request.get_json(), 'locale_id': _lng}
     try:
         _item_index = _kwargs.pop('item_index')
         _block_instance = ContentElementsBlock.load_fm_db(**_kwargs)
         if _block_instance is None:
             '''report if block element instance is not available'''
             return cls.not_found(**_kwargs)
         '''handle the instance'''
         _block_instance.remove(_item_index)
         _identity = _kwargs.pop('identity')
         result = _block_instance.save_to_db_content(
             **_kwargs, save_structure=True)
         # print('\nContentsHandling\n patch',
         #       '\n  _kwargs ->', dumps(_kwargs, indent=4),
         #       '\n  _block_instance ->', _block_instance,
         #       )
         if result is not None:
             return cls.error_message(error_info=result, status=500)
         else:
             '''report success'''
             return cls.success(**{**_kwargs, 'identity': _identity})
     except WrongIndexError as e:
         '''report some wrong argument errors'''
         return cls.error_message(error_info=str(e), status=400)
         raise e
    def post(cls) -> Dict:
        '''
        The method moves upper level element up or down.
        json
            "view_id": "landing",
            "identity": "01_vblock_txt",
            "direction": "up"
        header
            Accept-Language: locale
        '''
        _lng = request.headers.get('Accept-Language')
        fbp.set_lng(_lng)
        _user_id = get_jwt_identity()
        if not UserModel.find_by_id(_user_id).is_admin:
            return cls.no_access()
        '''join values into one variable'''
        _kwargs = {**request.get_json(), 'locale_id': _lng}
        # print('\nUpperLevelHandling:\n post'
        #       '\n  _kwargs ->', list(_kwargs.keys()).sort(),
        #       '\n  attributes ->', UpperLevelHandling._kwargs.sort())
        try:
            _identity = _kwargs.pop('identity')
            _index = int(_identity.split('_')[0])
            _direction = _kwargs.pop('direction')

            _page_instance = PageView.load_fm_db(ids=_kwargs)
            if _page_instance is None:
                return cls.not_found(**_kwargs, identity=_identity)
            _page_instance.move_element(
                index=_index, direction=_direction)
            result = _page_instance.save_to_db(user_id=_user_id)
            if result is None:
                '''report success'''
                return cls.success(**{**_kwargs, 'identity': _identity})
            else:
                return cls.error_message(error_info=result, status=500)
            # [print(element) for element in _page_instance.elements]
        except (WrongIndexError, KeyError) as e:
            '''report some wrong argument errors'''
            return cls.error_message(error_info=str(e), status=400)
        except Exception as e:
            # return cls.error_message(error_info=str(e), status=400)
            raise e
Beispiel #17
0
 def delete(cls):
     '''
     Delete instance from db.
     '''
     if not UserModel.find_by_id(get_jwt_identity()).is_admin:
         return no_access()
     fbp.set_lng(request.headers.get('Accept-Language'))
     _requested_dict = {'view_id': request.args.get('view_id')}
     # testing fields
     _delete_json = view_global_get_schema.load(_requested_dict)
     _view = ViewGlobalModel.find_by_id(view_id=_delete_json.get('view_id'))
     if _view is None:
         return cls.not_found(**_delete_json)
     _view.delete_fm_db()
     return {
         'message':
         str(
             _(
                 "The view with id '%(view_id)s' has been deleted "
                 "successfully.",
                 view_id=_delete_json['view_id']))
     }, 200
Beispiel #18
0
 def post(cls):
     '''
     Create content instance and save to db.
     '''
     # print('post')
     if not UserModel.find_by_id(get_jwt_identity()).is_admin:
         return no_access()
     fbp.set_lng(request.headers.get('Accept-Language'))
     _view = view_global_schema.load(request.get_json(),
                                     session=dbs_global.session)
     _view_fm_db = ViewGlobalModel.find_by_id(view_id=_view.view_id)
     if _view_fm_db is not None:
         return cls.already_exists({'view_id': _view.view_id})
     _view.save_to_db()
     return {
         'message':
         str(
             _("The view has been saved successfully. "
               "Details are in payload.")),
         'payload':
         view_global_get_schema.dump(_view)
     }, 201
Beispiel #19
0
 def put(cls):
     '''
     Update instance and save to db.
     '''
     if not UserModel.find_by_id(get_jwt_identity()).is_admin:
         return no_access()
     # print('\ncontents, resources, view, update_json ->', request.get_json())
     _update_json = view_global_get_schema.load(request.get_json())
     # print('\ncontents, resources, view, update_json ->', _update_json)
     _view = ViewGlobalModel.find_by_id(view_id=_update_json['view_id'])
     if _view is None:
         return cls.not_found(_update_json.get('view_id'))
     _view.update(_update_json)
     return {
         'message':
         str(
             _(
                 "The view with id '%(view_id)s' has been updated "
                 "successfully. Details are in payload.",
                 view_id=_update_json['view_id'])),
         'payload':
         view_global_get_schema.dump(_view)
     }, 200
Beispiel #20
0
    def get(cls) -> ['ViewGlobalModel']:
        '''
        The resource give list of available view in the system.
        User should be admin.
        '''
        fbp.set_lng(request.headers.get('Accept-Language'))

        if UserModel.find_by_id(get_jwt_identity()).is_admin:
            payload = [
                view_global_get_schema.dump(_view)
                for _view in ViewGlobalModel.find()
            ]
            count = len(payload)
            return {
                'message':
                str(
                    _("There are %(count)s views in our database as follows:",
                      count=count)),
                'payload':
                payload
            }, 200
        else:
            return no_access()
Beispiel #21
0
 def post(cls) -> Dict:
     '''
     Create content instance and save to db.
     '''
     _lng = request.headers.get('Accept-Language')
     _user_id = get_jwt_identity()
     # print('\ncontents, resources, post, lng ->', _lng)
     fbp.set_lng(_lng)
     if not UserModel.find_by_id(_user_id).is_admin:
         return cls.no_access()
     _request_json = {
         **request.get_json(), 'locale_id': _lng,
         'user_id': _user_id
     }
     _content = content_schema.load(_request_json,
                                    session=dbs_global.session)
     _content_fm_db = ContentModel.find_by_identity_view_locale(
         identity=_content.identity,
         view_id=_content.view_id,
         locale_id=_content.locale_id)
     if _content_fm_db is not None:
         return cls.already_exists(identity=_content.identity,
                                   view_id=_content.view_id,
                                   locale_id=_content.locale_id)
     error_info = _content.save_to_db()
     if error_info is not None:
         return cls.error_message(error_info)
     return {
         'message':
         str(
             _("The content has been saved successfully. "
               "Details are in payload.")),
         'payload':
         content_get_schema.dump(_content)
         # 'payload': content_schema.dump(_content)
     }, 201