Best Python code snippet using autotest_python
app.py
Source:app.py  
...26    def __init__(self) -> None:27        super().__init__()28        if not static.frun:29            static.frun = True30            self.handle_recipes('handle_recipe_action_get_randoms',10)31            print(" :: __INIT__ :: ")32    @classmethod33    def pre_init(self):34        self.obj_scrapeweeklys = []35        self.obj_scrapedatabase = wr_scrapeDatabase()36        self.recipeNames = self.obj_scrapedatabase.get_allNames()37        self.user = user()38        self.vendor = vendor()39        self.QR = QR()40        self.create_cards = create_cards()41        self.ordershistory = ordershistory()42        self.basket_manager = basket_manager()43        self.favorites_manager = favorites_manager()44        self.git_manager = git_manager()45        print(" :: SERVER STARTED :: ")46    @route('/')47    def index(self):48        retval = self.handle_recipes('return_recipes')49        print(" :: index :: successfully passed")50        tags = self.obj_scrapedatabase.get_all_tags()51        return(render_template('index.html',52                               tags=tags,53                               r_name=retval['recipe_title'],54                               r_subtitle=retval['recipe_subtitle'],55                               filename=retval['recipe_img'],56                               r_type=retval['recipe_type'],57                               r_subtype=retval['recipe_tag'],58                               r_id=retval['recipe_id'],59                               r_fav_status= [self.favorites_manager.get_fav_status(e) for e in retval['recipe_id']],60                               amount=len(retval['recipe_title'])61                               ))62    @route('/login')63    def login(self):64        return(render_template('login.html', vendor = enumerate(self.vendor.early.items())))65    @route('/settings')66    def settings(self):67        return(render_template('settings.html'))68    @route('/orders', methods=['GET'])69    def orders(self):70        return(render_template('orders.html',data = self.ordershistory.get()))71    def handle_recipes(self,fcn,val=""):72        if fcn=='handle_recipe_action_get_randoms':73            static.recipes = self.obj_scrapedatabase.get_random(val)74        elif fcn=='handle_recipe_action_get_by_tag':75            static.recipes = self.obj_scrapedatabase.get_by_tag(val)76        elif fcn=='handle_recipe_action_get_by_id':77            static.recipes = self.obj_scrapedatabase.get_byID(val)78        elif fcn=='handle_recipe_action_search_ingredient':79            static.recipes = self.obj_scrapedatabase.search_by_ingredient(val)80        elif fcn=='return_recipes':81            pass82        return(static.recipes)83    def handle_basket(self,fcn,val=""):84        if fcn=='handle_basket_action_relative_ids':#e.g. 1,2,3,4...85            try:86                ''' Try getting new basket elements '''87                val = operator.itemgetter(*list(map(int, val)))(self.handle_recipes('return_recipes')['recipe_id'])88                ''' Adding them to the existing basket items '''89                static.basket_ids = static.basket_ids + (val if isinstance(val,tuple) else (val,))90                static.basket_ids = tuple(np.unique(static.basket_ids))91                static.basket_items = self.basket_manager.build_basket(static.basket_ids)92            except:93                pass94        elif fcn=='handle_basket_action_absolute_ids':#e.g. 1833,3919,2143...95            try:96                ''' Adding them to the existing basket items '''97                static.basket_ids = static.basket_ids + tuple([int(e) for e in val])98                static.basket_ids = tuple(np.unique(static.basket_ids))99                static.basket_items = self.basket_manager.build_basket(static.basket_ids)100            except:101                pass102        elif fcn=='remove_item':103            temp_list = list(static.basket_ids)104            temp_list.remove(val)105            static.basket_ids = tuple(temp_list)106            self.handle_basket('handle_basket_action_absolute_ids',static.basket_ids)107        elif fcn=='clear_basket':108            static.basket_items = []109            static.basket_ids = ()110        elif fcn=='return_basket':111            pass112        return(static.basket_items)113    @route('/', methods=['POST'])114    def post_route(self):115        retval = request.get_json()116        route = retval.get('Route')117        if route == 'basket':118            self.handle_basket('handle_basket_action_relative_ids',request.get_json().get('Recipes'))119            return(make_response(jsonify(self.handle_basket('return_basket')), 201))120        elif route == 'clearBasket':121            self.handle_basket('clear_basket')122            return(make_response(jsonify(self.handle_basket('return_basket')), 201))123        elif route == 'deleteItem':124            self.handle_basket('remove_item',retval.get('deleteItem'))125            return(make_response(jsonify(self.handle_basket('return_basket')), 201))126        elif route == 'saveCredentials':127            self.user.setCredentials(retval.get('vendor'),retval.get('username'),retval.get('password'),retval.get('ipaddress'))128            status = self.vendor.login(retval.get('vendor'))129            info = self.vendor.getUserInfo(retval.get('vendor'))130            return(make_response(jsonify({'vendor':retval.get('vendor'),'status':status,'info':info}), 200))131        elif route == 'checkout':132            return(make_response(jsonify(self.vendor.handleCheckout(ingredients=self.handle_basket('return_basket').get('unique_basket_elements'),vendor=retval.get('vendor'))), 200))133        elif route == 'mod':134            return(make_response(jsonify(self.vendor.modify_basket(idx=retval.get('idx'),fnc=retval.get('f'))), 200))135        elif route == 'push_vendor_basket':136            self.ordershistory.set(self.handle_basket('return_basket').get('basket_recipe_elements').get('recipe_id'))137            return(make_response(jsonify({'status':'ok','missing':self.vendor.push_basket(retval.get('vendor'))['missing']}), 200))138        elif route == 'getCurrentUserStatus':139            return(make_response(jsonify(self.vendor.early), 200))140        elif route == 'create_cards':141            self.ordershistory.set(self.handle_basket('return_basket').get('basket_recipe_elements').get('recipe_id'))142            static.cards_ids = tuple(self.handle_basket('return_basket').get('basket_recipe_elements').get('recipe_id'))143            return(redirect(url_for('WebView:cards')))144        elif route == 'ordershistory_basket':145            self.handle_basket('handle_basket_action_absolute_ids',self.ordershistory.get_recipe_ids(retval['basket_uid']))146            return(redirect(url_for('WebView:index')))147        elif route == 'ordershistory_delete':148            self.ordershistory.delete_item(retval['basket_uid'])149            return(redirect(url_for('WebView:index')))150        elif route == 'ordershistory_cards':151            static.cards_ids = self.ordershistory.get_recipe_ids(retval['basket_uid'])152            return(redirect(url_for('WebView:cards')))153        elif route == 'logout':154            self.vendor.logout()155            return(make_response(jsonify({'none':'none'}), 200))156        elif route == 'favorite_set':157            self.favorites_manager.set(retval['recipe_id'])158            return(make_response(jsonify({'none':'none'}), 200))159        elif route == 'favorite_unset':160            self.favorites_manager.unset(retval['recipe_id'])161            return(make_response(jsonify({'none':'none'}), 200))162        elif route == 'search_autocomplete_action':163            return(make_response(jsonify(self.obj_scrapedatabase.search_autocomplete_action(retval.get('query'))), 200))164        elif route == 'show_recipes_by_tag':165            self.handle_recipes('handle_recipe_action_get_by_tag',retval.get('tag'))166            return(redirect(url_for('WebView:index')))167        elif route=='show_recipes_by_ingredient_search':168            self.handle_recipes('handle_recipe_action_search_ingredient',retval.get('ingredient_list'))169            return(redirect(url_for('WebView:index')))170        elif route=='count_recipes_by_ingredient_search':171            return(make_response(jsonify(self.obj_scrapedatabase.count_search_by_ingredient(retval.get('ingredient_list'))), 200))172        elif route=='handle_update_app_action':173            return(make_response(jsonify(self.git_manager.update_available()), 200))174        elif route=='start_application_update':175            self.git_manager.update_repository()176            return(make_response(jsonify({'':''}), 200))177            178    @route('/choose', methods=['POST'])179    def post_route_choose(self):180        route = dict(request.form)['btn']181        if route == 'random':182            self.handle_recipes('handle_recipe_action_get_randoms',int(dict(request.form)['range']))      183        if route == 'recent':184            if not self.obj_scrapeweeklys:185                self.obj_scrapeweeklys = self.vendor.handleWeeklys()            186            self.handle_recipes('handle_recipe_action_get_by_id',self.obj_scrapeweeklys.get())187        if route == 'btn_favorites_show':188            self.handle_recipes('handle_recipe_action_get_by_id',self.favorites_manager.get_fav_recipe_ids())189        return(redirect(url_for('WebView:index')))190    @route('/cards')191    def cards(self):192        return(render_template('cards.html',data=self.create_cards.get(static.cards_ids),basket_items=self.basket_manager.build_basket(static.cards_ids)))193    @route('/favorites')194    def favorites(self):195        return(render_template('favorites.html'))196@app.route('/wake')197def wake_state():198    return(Response("data: close\n\n", mimetype= 'text/event-stream'))199@app.route('/progress')200def progress():201    global thread202    ''' args : start or retrieve '''...services.py
Source:services.py  
1import requests2from decouple import config as secret3from requests import HTTPError, Response4class SpoonacularApiServiceError(Exception):5    """6    Handle error in SpoonacularApiService.7    """8class SpoonacularBusinessRuleError(Exception):9    """10    Handle error in SpoonacularApiService.11    """12class SpoonacularApiService(object):13    """14    Class for making requests to Spoonacular Api.15    """16    def __init__(self):17        self._base_url = "https://api.spoonacular.com/recipes"18        self._session = requests.session()19    def get_by_ingredients(self, ingredients: str) -> list:20        """21        Method to get recipes by ingredients name.22        Maximum of 3 ingredients allowed.23        Args:24            - ingredients (str): it's sent as query param from our api.25        """26        endpoint = "findByIngredients"27        params = {}28        ingredients_quantity = 029        if ingredients:30            ingredients_quantity = (31                len(ingredients.split(",")) if "," in ingredients else 132            )33        try:34            if ingredients_quantity <= 3 and ingredients_quantity != 0:35                params["apiKey"] = self._get_api_key()36                params["ingredients"] = ingredients37                result = self._get(endpoint, params=params)38                return self._handle_data(result)39            else:40                message = {41                    f"Should get 1 to 3 ingredients but got "42                    f"{ingredients_quantity}"43                }44                raise SpoonacularBusinessRuleError(message)45        except SpoonacularBusinessRuleError as error:46            message = {47                f"Error getting endpoint {endpoint} with params "48                f"{ingredients}: {error}"49            }50            raise SpoonacularBusinessRuleError(message)51        except HTTPError as error:52            message = {53                f"Error while trying to get data from Spoonacular API: {error}"54            }55            raise SpoonacularApiServiceError(message)56    def _get(self, endpoint, params=None) -> Response:57        headers = {"content-type": "application/json"}58        response = self._session.get(59            f"{self._base_url}/{endpoint}", params=params, headers=headers60        )61        response.raise_for_status()62        return response63    @staticmethod64    def _handle_data(response) -> list:65        """66        It's used to manipulate the Spoonacular API response to67        return the following attributes:68        - title;69        - image;70        - ingredients.71        Args:72            - response (Response): It's received from _get method.73        """74        handle_recipes = []75        for recipe in response.json():76            dict_recipe = {77                "title": recipe["title"],78                "image": recipe["image"],79                "ingredients": [80                    ingredient["name"]81                    for ingredient in recipe["usedIngredients"]82                ],83            }84            dict_recipe["ingredients"] += [85                ingredient["name"]86                for ingredient in recipe["missedIngredients"]87            ]88            handle_recipes.append(dict_recipe)89        return handle_recipes90    @staticmethod91    def _get_api_key() -> str:92        """93        Get the API_KEY from .env file94        """...ui.py
Source:ui.py  
...42    def handle_edit_recipes(self, recipe_id, name, instruction, ingredients):43        self._hide_current_view()44        self._show_edit_view(recipe_id, name, instruction, ingredients)45        self._pack()46    def handle_recipes(self):47        self._hide_current_view()48        self._show_recipes_view()49        self._pack()50    def handle_register(self):51        self._hide_current_view()52        self._show_register_view()53        self._pack()54    def handle_login(self):55        self._hide_current_view()56        self._show_login_view()...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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
