How to use get_recipe method in autotest

Best Python code snippet using autotest_python

app.py

Source:app.py Github

copy

Full Screen

1"""REST API app using "Flask + SQLAlchemy" with marshmallow. """23from flask import Flask,jsonify,request,make_response4from http import HTTPStatus5from flask_sqlalchemy import SQLAlchemy #thorugh python change is databse6from marshmallow import fields,ValidationError #handle ValidationError7from marshmallow_sqlalchemy import ModelSchema8from sqlalchemy.types import TypeDecorator910### ERRORS HANDLING ##11def page_not_found(e): # error:URL Not Found12 return jsonify({'message': 'URL not found !!'}), HTTPStatus.NOT_FOUND13def BAD_REQUEST(e): #errpr: check syntax error, Invalid Request message14 return jsonify({'message': 'BAD REQUEST !! Syntax,Invalid Request Message Framing,Or Deceptive Request Routing'}),HTTPStatus.BAD_REQUEST15def method_not_allowed(e): # error:when you pass wrong url16 return jsonify({'message': 'Method Not Allowed !!'}), HTTPStatus.METHOD_NOT_ALLOWED1718### DATABASE DEFINATION ###19app = Flask(__name__)20app.config['SQLALCHEMY_DATABASE_URI']="sqlite:///recipe.db"21app.config['SQLALCHEMY_TRACK_MODIFICATIONS']= False2223app.register_error_handler(404,page_not_found)24app.register_error_handler(400,BAD_REQUEST)25app.register_error_handler(405,method_not_allowed)26db=SQLAlchemy(app)272829##### MODELS #####30class StrippedString(TypeDecorator):3132 impl = db.String3334 def process_bind_param(self, value, dialect):35 # In case you have nullable string fields and pass None36 return value.strip() if value else value3738 def copy(self, **kw):39 return StrippedString(self.impl.length)40class recipe(db.Model):41 Recipe_ID=db.Column(db.Integer,primary_key=True)42 Recipe=db.Column(StrippedString(500),nullable=False)43 Dish=db.Column(StrippedString(20),nullable=False)4445 def create(self):46 db.session.add(self)47 db.session.commit()48 return self4950 def __init__(self,Dish,Recipe):51 self.Dish = Dish52 self.Recipe=Recipe5354 def __repr__(self):55 return f"{self.Recipe_ID}"56575859### Custom validator ###60def must_not_be_blank(data):61 if not data:62 raise ValidationError("Can't be Empty!") #raise Validation error on empty input data6364def null_and_type_check(data, recipeObject): #check for not empty-string data input65 messageString = []66 emptyVariables = [] 67 if data.get('Recipe'):68 recipeObject.Recipe = data['Recipe']69 if type(recipeObject.Recipe)!=str:70 messageString.append("Invalid data type: Recipe needs to be String")71 if type(recipeObject.Recipe)==str and data.get('Recipe').strip() == '':72 emptyVariables.append("Error: Recipe cannot be empty")73 else:74 emptyVariables.append("Error: Recipe cannot be empty")7576 if data.get('Dish'):77 recipeObject.Dish = data['Dish']78 if type(recipeObject.Dish)!=str or (recipeObject.Dish==''):79 messageString.append(" Invalid data type: Dish needs to be String")80 if type(recipeObject.Dish)==str and data.get('Dish').strip() == '' : 81 emptyVariables.append("Error: Dish cannot be empty")82 else:83 emptyVariables.append("Error: Dish cannot be empty")84 output = emptyVariables + messageString85 if output:86 return ', '.join(output)87 else:88 return '' 8990### SCHEMAS ###91class recipeSchema(ModelSchema):92 class Meta(ModelSchema.Meta):93 model = recipe94 sqla_session = db.session95 Recipe_ID = fields.Integer(dump_only=True)96 Recipe = fields.String(required=True,validate=must_not_be_blank) #custom error97 Dish = fields.String(required=True,validate=must_not_be_blank) #custom error9899##### API #####100101# Get All Recipes 102@app.route('/recipes', methods=['GET'])103def get_recipes():104 105 get_all = recipe.query.all()106 recipe_schema = recipeSchema(many=True)107 recipes = recipe_schema.dump(get_all)108 if recipes:109 return make_response(jsonify({"Recipes": recipes}),HTTPStatus.OK)110 return jsonify({'message': 'recipes not found !'}), HTTPStatus.NOT_FOUND111112# Get All Recipes By ID113@app.route('/recipes/<int:Recipe_ID>', methods=['GET'])114def get_recipe_by_id(Recipe_ID):115 get_recipe = recipe.query.get(Recipe_ID)116 recipe_schema = recipeSchema()117 recipes = recipe_schema.dump(get_recipe)118 if recipes:119 return make_response(jsonify({"Recipe": recipes}),HTTPStatus.OK)120 return jsonify({'message': 'recipe not found'}), HTTPStatus.NOT_FOUND121122#Add Recipe 123@app.route('/recipes', methods=['POST'])124def create_recipe():125 data = request.get_json()126 if not data:127 return {"message": "No input data provided"},400 #error:data is not in json format128 recipe_schema = recipeSchema()129 try:130 recipes = recipe_schema.load(data)131 except ValidationError as err:132 return err.messages, 422 #error: invalid datatype of input data133 improper_data = null_and_type_check(data, recipes)134 if improper_data:135 return {"message": improper_data}, 422136 result = recipe_schema.dump(recipes.create())137 return make_response(jsonify({"Recipe": result})),HTTPStatus.CREATED138 139#Update Recipe140@app.route('/recipes/<int:Recipe_ID>', methods=['PUT'])141def update_receipe(Recipe_ID):142 data=request.get_json()143 if not data:144 return {"message": "No input data provided"} ,400 #error:data is not in json format145 get_recipe=recipe.query.get(Recipe_ID)146 if(get_recipe == None):147 return {"message": "Recipe Id doesn't exist, can't update!"}, 404148 improperData = null_and_type_check(data, get_recipe) #error: check for not empty-string data input149 if improperData:150 return {"message": improperData}, 422151 db.session.add(get_recipe)152 db.session.commit()153 recipe_schema = recipeSchema(only=['Recipe_ID', 'Recipe', 'Dish'])154 recipes = recipe_schema.dump(get_recipe)155 if recipes:156 return make_response(jsonify({"Recipe": recipes})),HTTPStatus.OK157 return jsonify({'message': 'recipe not found'}),HTTPStatus.NOT_FOUND 158 159#Delete Recipe By ID160@app.route('/recipes/<int:Recipe_ID>', methods=['DELETE'])161def delete_recipe_by_id(Recipe_ID):162 get_recipe = recipe.query.get(Recipe_ID)163 if get_recipe:164 db.session.delete(get_recipe)165 db.session.commit()166 return make_response(jsonify({'message':'Recipe Deleted!'})),HTTPStatus.OK # recipe deleted sucessfully167 return jsonify({'message': 'recipe not found'}), HTTPStatus.NOT_FOUND #error:if recipe not found in database168169#Delete All Recipes170@app.route('/recipes',methods=['DELETE'])171def delete_all():172 db.session.query(recipe).delete()173 db.session().commit()174 return make_response(jsonify({'message':' ALL The Recipes Are Deleted!'})),HTTPStatus.OK175176177 178179if __name__=="__main__": ...

Full Screen

Full Screen

dashboard_recipe.py

Source:dashboard_recipe.py Github

copy

Full Screen

...17 def setup(self, *args, **kwargs):18 return super().setup(*args, **kwargs)19 def dispatch(self, *args, **kwargs):20 return super().dispatch(*args, **kwargs)21 def get_recipe(self, id=None):22 recipe = None23 if id is not None:24 recipe = Recipe.objects.filter(25 is_published=False,26 author=self.request.user,27 pk=id,28 ).first()29 if not recipe:30 raise Http404()31 return recipe32 def render_recipe(self, form):33 return render(34 self.request,35 'authors/pages/dashboard_recipe.html',36 context={37 'form': form38 }39 )40 def get(self, request, id=None):41 recipe = self.get_recipe(id)42 form = AuthorRecipeForm(instance=recipe)43 return self.render_recipe(form)44 def post(self, request, id=None):45 recipe = self.get_recipe(id)46 form = AuthorRecipeForm(47 data=request.POST or None,48 files=request.FILES or None,49 instance=recipe50 )51 if form.is_valid():52 # Agora, o form é válido e eu posso tentar salvar53 recipe = form.save(commit=False)54 recipe.author = request.user55 recipe.preparation_steps_is_html = False56 recipe.is_published = False57 recipe.save()58 messages.success(request, 'Sua receita foi salva com sucesso!')59 return redirect(60 reverse(61 'authors:dashboard_recipe_edit', args=(62 recipe.id,63 )64 )65 )66 return self.render_recipe(form)67@method_decorator(68 login_required(login_url='authors:login', redirect_field_name='next'),69 name='dispatch'70)71class DashboardRecipeDelete(DashboardRecipe):72 def post(self, *args, **kwargs):73 recipe = self.get_recipe(self.request.POST.get('id'))74 recipe.delete()75 messages.success(self.request, 'Deleted successfully.')...

Full Screen

Full Screen

views.py

Source:views.py Github

copy

Full Screen

...23 recipe_to_add.save()24 return Response(recipe_to_add.data, status=status.HTTP_201_CREATED)25 return Response(recipe_to_add.errors, status=status.UNPROCESSABLE_ENTITY)26class RecipeDetailView(APIView):27 def get_recipe(self, pk):28 try:29 return Recipe.objects.get(pk=pk)30 except Recipe.DoesNotExist:31 raise NotFound(detail="cannot find that recipe")32 def get(self, _request, pk):33 recipe = self.get_recipe(pk=pk)34 serialized_recipe = PopulatedRecipeSerializer(recipe)35 return Response(serialized_recipe.data, status=status.HTTP_200_OK)36 def delete(self, _request, pk):37 recipe_to_delete = self.get_recipe(pk=pk)38 recipe_to_delete.delete()39 return Response(status=status.HTTP_204_NO_CONTENT)40 def put(self, request, pk):41 recipe_to_edit = self.get_recipe(pk=pk)42 updated_recipe = RecipeSerializer(recipe_to_edit, data=request.data)43 if updated_recipe.is_valid():44 updated_recipe.save()45 return Response(updated_recipe.data, status=status.HTTP_202_ACCEPTED)46 return Response(updated_recipe.errors, status=status.HTTP_422_UNPROCESSABLE_ENTITIY)47class RecipeLikedView(APIView): 48 permissions_classes = (IsAuthenticated,)49 def get_recipe(self, pk):50 try:51 return Recipe.objects.get(pk=pk)52 except Recipe.DoesNotExist:53 raise NotFound(detail="Cannot find that recipe")54 def put(self, request, pk):55 recipe = self.get_recipe(pk=pk)56 user_to_add = User.objects.get(pk=request.user.id)57 recipe.like.add(user_to_add)58 recipe.save()59 serializer_recipe = PopulatedRecipeSerializer(recipe)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful