class UserRecipeListResource(Resource): decorators = [ limiter.limit('3/minute;30/hour;300/day', methods=['GET'], error_message='Too many requests') ] @jwt_optional @use_kwargs({ 'visibility': fields.Str(missing='public'), 'page': fields.Int(missing=1), 'per_page': fields.Int(missing=20) }) def get(self, page, per_page, username, visibility): user = User.get_by_username(username) if user is None: return {'message': 'User not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if user.id == current_user and visibility in ['all', 'private']: pass else: visibility = 'public' recipes = Recipe.get_all_by_user(user_id=user.id, visibility=visibility, page=page, per_page=per_page) return recipe_pagination_schema.dump(recipes).data, HTTPStatus.OK
class UserPoliticianListResource(Resource): decorators = [ limiter.limit('3/minute;30/hour;300/day', methods=['GET'], error_message='Too Many Requests') ] @jwt_optional @use_kwargs({ 'page': fields.Int(missing=1), 'per_page': fields.Int(missing=10), 'visibility': fields.Str(missing='public') }) def get(self, username, page, per_page, visibility): user = User.get_by_username(username=username) if user is None: return {'message': 'User not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if current_user == user.id and visibility in ['all', 'private']: pass else: visibility = 'public' paginated_politicians = Politician.get_all_by_user( user_id=user.id, page=page, per_page=per_page, visibility=visibility) return politician_pagination_schema.dump( paginated_politicians).data, HTTPStatus.OK
class UserRecipeListResource(Resource): decorators = [ limiter.limit( "3/minute;30/hour;300/day", methods=["GET"], error_message="Too many requests", ) ] @jwt_optional def get(self, username): page = int(request.args.get("page", 1)) per_page = int(request.args.get("per_page", 10)) visibility = request.args.get("visibility", "public") user = User.get_by_username(username=username) if user is None: return {"message": "user not found"}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if current_user == user.id and visibility in ["all", "private"]: pass else: visibility = "public" paginated_recipes = Recipe.get_all_by_user( user_id=user.id, page=page, per_page=per_page, visibility=visibility ) return recipe_pagination_schema.dump(paginated_recipes), HTTPStatus.OK
class RecipeListResource(Resource): decorators = [limiter.limit('2 per minute', methods=['GET'], error_message='Too Many Requests')] kwargs = {'q': fields.Str(missing=''), 'page': fields.Int(missing=1), 'per_page': fields.Int(missing=20), 'sort': fields.Str(missing='created_at'), 'order': fields.Str(missing='desc')} @use_kwargs(kwargs, location='query') @cache.cached(timeout=60, query_string=True) def get(self, q, page, per_page, sort, order): # get all recipes (that published) print('Quering the database..') if sort not in ['created_at', 'cook_time', 'num_of_servings']: sort = 'created_at' if order not in ['asc', 'desc']: order = 'desc' paginated_recipes = Recipe.get_all_published(q, page, per_page, sort, order) return recipe_pagination_schema.dump(paginated_recipes), HTTPStatus.OK @jwt_required def post(self): # create recipe json_data = request.get_json() current_user = get_jwt_identity() try: data = recipe_schema.load(data=json_data) except ValidationError as error: errors = list(error.messages.values()) return {'message': 'Validation errors', 'errors': [x[0] for x in errors]}, HTTPStatus.BAD_REQUEST recipe = Recipe(**data) recipe.user_id = current_user recipe.save() return recipe_schema.dump(recipe), HTTPStatus.CREATED
class UserRecipeListResource(Resource): decorators = [limiter.limit('3/minute; 30/hour; 300/day', methods=['GET'], error_message='Too Many Request')] @jwt_optional @use_kwargs(pages) def get(self, username, page, per_page, visibility): """This method has the logic to retrieve all recipes published by a user.""" user = User.get_by_username(username=username) if user is None: return {'message': 'User not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() # If the username is the currently authenticated user, then they can # see all the recipes if current_user == user.id and visibility in ['all', 'private']: pass else: visibility = 'public' # Gets the paginated recipes by a particular author paginated_recipes = Recipe.get_all_by_user(user_id=user.id, page=page, per_page=per_page, visibility=visibility) # Serialize the paginated object and return HTTP Status Code return recipe_pagination_schema.dump(paginated_recipes).data, HTTPStatus.OK
class RecipeListResource(Resource): decorators = [ limiter.limit('2 per minute', methods=['GET'], error_message='Too Many Requests') ] # Default value for the page parameter is 1 # Default value for the per_page parameter is 20. # If nothing is passed we will be getting the first page # with the first 20 records @use_kwargs({ 'q': fields.Str(missing=''), 'page': fields.Int(missing=1), 'per_page': fields.Int(missing=20), 'sort': fields.Str(missing='created_at'), 'order': fields.Str(missing='desc') }) @cache.cached(timeout=60, query_string=True ) # True means that it allows passing in of arguments def get(self, q, page, per_page, sort, order): """ Passes three arguments in the get_all_published method and gets the pagination object back. returns the paginated recipes as serialized and back to front end client. The q parameter passed the search string into the API """ print('Querying database') if sort not in ['created_at', 'cook_time', 'num_of_servings']: sort = 'created_at' if order not in ['asc', 'desc']: order = 'desc' paginated_recipes = Recipe.get_all_published(q, page, per_page, sort, order) return recipe_pagination_schema.dump( paginated_recipes).data, HTTPStatus.OK @jwt_required def post(self): """:param """ json_data = request.get_json() current_user = get_jwt_identity() data, errors = recipe_schema.load(data=json_data) if errors: return { 'message': "Validation Errors", 'errors': errors }, HTTPStatus.BAD_REQUEST recipe = Recipe(**data) recipe.user_id = current_user recipe.save() return recipe_schema.dump(recipe), HTTPStatus.CREATED
class RecipeListResource(Resource): decorators = [ limiter.limit('2 per minute', methods=['GET'], error_message='Too Many Requests') ] @use_kwargs({ 'q': fields.Str(missing=''), 'page': fields.Int(missing=1), 'per_page': fields.Int(missing=20), 'sort': fields.Str(missing='created_at'), 'order': fields.Str(missing='desc') }) @cache.cached(timeout=60, query_string=True) def get(self, q, page, per_page, sort, order): print('Querying database...') if sort not in ['created_at', 'cook_time', 'num_of_servings']: sort = 'created_at' if order not in ['asc', 'desc']: order = 'desc' paginated_recipes = Recipe.get_all_published(q, page, per_page, sort, order) return recipe_pagination_schema.dump( paginated_recipes).data, HTTPStatus.OK @jwt_required def post(self): json_data = request.get_json() current_user = get_jwt_identity() data, errors = recipe_schema.load(data=json_data) if errors: return { 'message': 'Validation errors', 'errors': errors }, HTTPStatus.BAD_REQUEST recipe = Recipe(**data) recipe.user_id = current_user recipe.save() return recipe_schema.dump(recipe).data, HTTPStatus.CREATED
class RecipeListResource(Resource): # Setting the number of requests to our RESTful APIs decorators = [limiter.limit('3/minute; 30/hour; 300/day', methods=['GET'], error_message='Too Many Requests')] @use_kwargs(pages) @cache.cached(timeout=60, query_string=True) def get(self, q, page, per_page, sort, order): """This method have the logic to retrieve all recipes, paginate, sort results and search for recipes""" # Accept only the created_at, cook_time, and num_of_servings values if sort not in ['created_at', 'cook_time', 'num_of_servings']: sort = 'created_at' # Accept only the asc and desc values if order not in ['asc', 'desc']: order = 'desc' paginated_recipes = Recipe.get_all_published(q, page, per_page, sort, order) return recipe_pagination_schema.dump(paginated_recipes).data, HTTPStatus.OK @jwt_required def post(self): """This method has got the logic to add a new recipe""" json_data = request.get_json() current_user = get_jwt_identity() # Verify data received data, errors = recipe_schema.load(data=json_data) if errors: return {'message': 'Validation errors', 'errors': errors}, HTTPStatus.BAD_REQUEST # If verification passes, create a Recipe object recipe = Recipe(**data) # ... Then save the recipe recipe.user_id = current_user recipe.save() # Finally, return the recipe in a JSON format and with status code HTTP 201 CREATED return recipe_schema.dump(recipe).data, HTTPStatus.CREATED
class UserListResource(Resource): decorators = [ limiter.limit('3/minute;30/hour;300/day', methods=['GET'], error_message='Too Many Requests') ] def post(self): json_data = request.get_json() data, errors = user_schema.load(data=json_data) if errors: return { 'message': 'Validation Errors', 'Errors': errors }, HTTPStatus.BAD_REQUEST if User.get_by_username(data.get('username')): return {'message': 'username already used'}, HTTPStatus.BAD_REQUEST if User.get_by_email(data.get('email')): return {'message': 'email aready used'}, HTTPStatus.BAD_REQUEST user = User(**data) user.save() token = generate_token( user.email, salt='activate') # Token is used to activate the account subject = 'Please confirm your registration' link = url_for( 'useractivateresource', token=token, _external=True) # Convert the default relative URL to absolute text = f'Hi,Thanks for using The Daily Cook! Please confirm your registration by clicking on the link:{link}' mailgun.send_email(to=user.email, subject=subject, text=text, html=render_template('email/confirmation.html', link=link)) return user_schema.dump(user).data, HTTPStatus.CREATED
class RecipeListResource(Resource): decorators = [ limiter.limit("3 per minute", methods=["GET"], error_message="Too many requests") ] @cache.cached(timeout=60, query_string=True) def get(self): sort = request.args.get("sort", "created_at") order = request.args.get("order", "desc") q = request.args.get("q", "") per_page = int(request.args.get("per_page", 10)) page = int(request.args.get("page", 1)) if sort not in ["created_at", "cook_time", "num_of_servings"]: sort = "created_at" if order not in ["asc", "desc"]: order = "desc" paginated_recipes = Recipe.get_all_published(q, page, per_page, order, sort) return recipe_pagination_schema.dump(paginated_recipes), HTTPStatus.OK @jwt_required def post(self): json_data = request.get_json() current_user = get_jwt_identity() try: data = recipe_schema.load(data=json_data) except Exception as errors: return ( { "message": "Validation error", "errors": errors.messages }, HTTPStatus.BAD_REQUEST, ) recipe = Recipe(**data) recipe.user_id = current_user recipe.save() return recipe_schema.dump(recipe), HTTPStatus.CREATED
class UserRecipeListResource(Resource): decorators = [limiter.limit('3/minute; 30/hour; 300/day', methods=['GET'], error_message='Too Many Requests')] @jwt_required(optional=True) @use_kwargs({'visibility': fields.Str(missing='public'), 'page': fields.Int(missing=1), 'per_page': fields.Int(missing=20)}, location="query") def get(self, username, page, per_page, visibility): user = User.get_by_username(username=username) if not user: return {'message': 'User not found'}, HTTPStatus.NOT_FOUND current_user = get_jwt_identity() if current_user != user.id and visibility != 'public': visibility = 'public' if visibility not in ['public', 'all', 'private']: return {'message': 'Nothing matches the given URI'}, HTTPStatus.NOT_FOUND paginated_recipes = Recipe.get_all_by_user(user_id=user.id, page=page, per_page=per_page, visibility=visibility) return recipe_pagination_schema.dump(paginated_recipes), HTTPStatus.OK
class PoliticianListResource(Resource): decorators = [limiter.limit('10 per minute', methods=['GET'], error_message='Too Many Requests, Retry After 1 minute')] @use_kwargs({'q': fields.Str(missing=''), 'page': fields.Int(missing=1), 'per_page': fields.Int(missing=20), 'sort': fields.Str(missing='created_at'), 'order': fields.Str(missing='desc') }) @cache.cached(timeout=60, query_string=True) def get(self, q, page, per_page, sort, order): print('Querying database...') if sort not in['created_at', 'county', 'constituency']: sort = 'created_at' if order not in ['asc', 'desc']: order = 'desc' paginated_politicians = Politician.get_all_published(q, page, per_page, sort, order) return politician_pagination_schema.dump(paginated_politicians).data, HTTPStatus.OK @jwt_required def post(self): json_data = request.get_json() current_user = get_jwt_identity() data, errors = politician_schema.load(data=json_data) if errors: return {'message': 'Validation errors', 'errors': errors}, HTTPStatus.BAD_REQUEST politician = Politician(**data) politician.user_id = current_user politician.save() return politician_schema.dump(politician).data, HTTPStatus.CREATED