def get(cls) -> Dict: ''' Get instance from db. ''' # print('cls, resources, _requested_dict ->', _requested_dict) _lng = request.headers.get('Accept-Language') fbp.set_lng(_lng) if not sessions.is_valid(get_jwt_identity()): return { 'message': str( _("Something went wrong. Check tech_token and sessions " "set up.")) }, 500 _requested_dict = { 'view_id': request.args.get('view_id'), 'identity': request.args.get('identity'), 'locale_id': _lng, } _search_json = content_get_schema.load(_requested_dict) _content = ContentModel.find_by_identity_view_locale(**_search_json) if _content is None: return cls.not_found(**_search_json) return { 'message': str(_("The content has been found. " "Details are in payload.")), 'payload': content_schema.dump(_content) }, 200
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
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
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 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 get(cls) -> Dict: ''' Get instance from db. ''' _lng = request.headers.get('Accept-Language') fbp.set_lng(_lng) print('structure, resources, get:\n _lng ->', _lng) if not sessions.is_valid(get_jwt_identity()): return { 'message': str(_( "Something went wrong. Sorry we'll reverting.")) }, 500 _requested_dict = { 'view_id': request.args.get('view_id'), 'locale_id': _lng } _search_json = structure_get_schema.load(_requested_dict) # print('\ncls, resources, _search_json ->', _search_json) _structure = StructureModel.find_by_ids(_search_json) if _structure is None: return cls.not_found(**_search_json) return { 'message': str(_( "The structure has been found. " "Details are in payload.")), 'payload': structure_schema.dump(_structure) }, 200
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
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 get(cls) -> Dict: """ Recieve file name (structure table identity) and view_id. Look respective and return it if exists. """ fbp.set_lng(request.headers.get('Accept-Language')) '''check tech_token''' if not sessions.is_valid(get_jwt_identity()): return { 'message': str(_("Something went wrong. Sorry we'll reverting.")) }, 500 _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)) _image_id = _requested_dict.get('image_id') _view_id = _requested_dict.get('view_id') '''Testing whether file has been exists''' 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, _image_id) # print('images, resource, _found_image ->', _found_image) return send_file(_found_image) except FileNotFoundError: return cls.not_found(_image_id)
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 put(cls): ''' Token refresh ''' # print('users, resources, userlogin, put') fbp.set_lng(request.headers.get('Accept-Language')) _user = UserModel.find_by_id(get_jwt_identity()) _json = request.get_json() # print('users, resources, userlogin, put, _user ->', _user) # print('users, resources, userlogin, put, _json ->', _json) if _user is None: return { 'message': str( _('Something wrong with token refreshing. Try to log in again.' )), }, 500 if not _user.check_password(_json.get('password')): return { 'message': str(_('Wrong password.')), }, 401 return { 'message': str(_('Token successfully refreshed.')), 'payload': { 'access_token': _user.get_fresh_token() } }, 200
def get(cls): fbp.set_lng(request.headers.get('Accept-Language')) _id_json = {'tech_id': request.args.get('tech_id')} # _id_json = request.get_json(silent=True) # print('\ntech_auth get, request _id_json ->', _id_json) if _id_json.get('tech_id') is None: return { 'message': str( _('Something went wrong, there is not valid JSON in the request.' )) }, 400 if 'tech_id' not in _id_json.keys(): return { 'message': str( _('Something went wrong, there is not proper key in the JSON.' )) }, 400 _tech_token = create_access_token(_id_json.get('tech_id'), expires_delta=False) sessions.setter(_id_json.get('tech_id')) return { 'message': str(_("TechAuth reporing! Tech token is in payload.")), 'payload': _tech_token }, 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
def delete(cls) -> Dict: ''' LogOut ''' fbp.set_lng(request.headers.get('Accept-Language')) jti = get_jwt()[ 'jti'] # jti is "JWT ID", a unique identifier for a JWT. # get_raw_jwt()['jti'] BLACKLIST.add(jti) return {"message": str(_("Successfully logged out."))}, 200
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 post(cls) -> Dict: ''' LogIn ''' # print(request.headers.get('Accept-Language')) fbp.set_lng(request.headers.get('Accept-Language')) _json = request.get_json() _user = UserModel.find_by_email(_json['email']) # print('UserLogin.post', _json) if _user is None: return { 'message': str( _("User with email '%(email)s' has not been found.", email=_json['email'])), }, 404 else: if not _user.check_password(_json.get('password')): return { 'message': str( _("Wrong password for user with email '%(email)s'.", email=_json['email'])), }, 400 # print('UserLogin.post user.role_id -', _user.role_id) else: if not _user.is_valid: return { 'message': str( _( "It seems you have not confirm your account. " "Check email stated - '%(email)s'.", email=_json['email'])), }, 400 _user.set_accessed() _user_info = _user.get_tokens() return { 'message': str( _( # "Hi! You are welcome.")), "Hi '%(user_name)s'! You are welcome.", user_name=_user_info['user_name'])), 'payload': _user_info }, 200
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)
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: ''' Creates user based on json. ''' fbp.set_lng(request.headers.get('Accept-Language')) # _json = request.get_json() # print('users.resources.users.User.post _json -', _json) _user = user_schema.load(request.get_json()) if UserModel.find_by_email(_user.email): return { 'message': str( _("User with email '%(email)s' already exists.", email=_user.email)), }, 400 else: try: _user.save_to_db() _confirmation = ConfirmationModel(_user.id) _confirmation.save_to_db() _user.send_confirmation_request() _created_user = UserModel.find_by_email(_user.email) # print('users.resources.User.post, user_schema.dump(_created_user) ->', # user_schema.dump(_created_user)) return { 'message': str( _( "User with email '%(email)s' created. " "We have sent your email, please visit " "your mailer and finish registration.", email=_user.email)), 'payload': user_schema.dump(_created_user) }, 201 except Exception as err: print('users.resources.User.post error:\n', err) return { 'message': str( _("While creating user somthing went wrong. Error - %(err)s.", err=err)) }, 500
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
def get(cls) -> Dict: ''' List of structure loaded once upon inititaion. tech_token is reauired. ''' _lng = request.headers.get('Accept-Language') fbp.set_lng(_lng) if not sessions.is_valid(get_jwt_identity()): return { 'message': str(_( "Something went wrong. Check tech_token and sessions set up.")) }, 500 payload = [structure_schema.dump(_structure) for _structure in StructureModel.find({'locale_id': _lng})] count = len(payload) return { 'message': str(_( "There are %(count)s structures in our database as follows:", count=count)), 'payload': payload }, 200
def post(cls): test_json = request.get_json() fbp.set_lng(request.headers.get('Accept-Language')) if test_json['what'] == 'date': payload = str( _('Date now is ') + format_datetime(datetime.now(), "dd LLL Y")) message = str(_('You asked about date')) elif test_json['what'] == 'time': payload = str( _('Time is ') + format_datetime(datetime.now(), 'HH:mm:ss Z')) message = str(_('You asked about time')) else: message = str( _('Not clear what do you want. ' 'I know date and time only. Please specify.')) payload = None output = {"message": message, "payload": payload} return output
def get(cls) -> Dict: ''' Get all user details by email in json. Allowd for owner or admin. ''' _email = request.args['email'] fbp.set_lng(request.headers.get('Accept-Language')) # Below is for validation only. user_update_schema.load({'email': _email}) _user_logged = UserModel.find_by_id(get_jwt_identity()) if not (_user_logged.is_admin or _user_logged.is_own_email(_email)): return { 'message': str( _("Admins or account owner are allowed to see details " "by email. You neither are admin no own this account.")) }, 401 _user = UserModel.find_by_email(_email) if _user: # print('users.resources.users.User.get _user -', user_schema.dump(_user)) return { 'message': str( _( "User with email '%(email)s' found, details are " "in payload.", email=_email)), 'payload': user_schema.dump(_user) }, 200 else: return { 'message': str( _("Sorry but user with email '%(email)s' has not been found.", email=_email)), }, 404
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
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
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()
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
def get(cls) -> Dict: ''' The resource give list of available locales in the system based on back-end info. Request should contains tech_token with valid session id. ''' fbp.set_lng(request.headers.get('Accept-Language')) if not sessions.is_valid(get_jwt_identity()): return { 'message': str(_( "Something went wrong. Check tech_token and sessions set up.")) }, 500 # print('\n application, resources, locale_global, lng ->', # request.headers.get('Accept-Language')) payload = [ locale_global_schema.dump(_view) for _view in LocaleGlobalModel.find() ] count = len(payload) return { 'message': str(_( "There are %(count)s locales in our database as follows:", count=count)), 'payload': payload }, 200