Best Python code snippet using localstack_python
views.py
Source:views.py  
...66        try:67            with transaction.atomic():68                obj, created = self._get_or_create(record, foreign_objects)69        except KeyError as e:70            return self._serialize_error(record, "error - missing field", e,71                                         foreign_objects)72        except models.Project.MultipleObjectsReturned as e:73            return self._serialize_error(record, "error - multiple records",74                                         e, foreign_objects)75        except ValueError as e:76            return self._serialize_error(77                record, "error - bad field value - create", e, foreign_objects)78        except IntegrityError as e:79            return self._serialize_error(80                record, "error - integrity error - create", e.__cause__,81                foreign_objects)82        if created:83            return self._serialize(obj, status="created")84        # (else not created)85        if self._is_different(obj, record):86            if self._should_update(obj, record):87                # update every field88                for attr in self.attributes:89                    setattr(obj, attr, record[attr])90                try:91                    with transaction.atomic():92                        obj.save()93                except ValueError as e:94                    return self._serialize_error(95                        record, "error - bad field value - update", e,96                        foreign_objects)97                except IntegrityError as e:98                    return self._serialize_error(99                        record, "error - integrity error - update",100                        e.__cause__, foreign_objects)101                return self._serialize(obj, status="updated")102            else:103                return self._serialize(104                    obj, status="unchanged - update not valid")105        else:106            return self._serialize(obj, status="unchanged - same record")107    def _is_different(self, existing_obj, new_record_data):108        return any([getattr(existing_obj, attr) != new_record_data[attr]109                    for attr in self.attributes])110    def _should_update(self, existing_obj, new_record_data):111        """ Returns True if existing_project should be updated with112        value and estimated from new_record_data.113        """114        return True115    def _serialize_error(self, record, status, exception, foreign_objects):116        data = self._error_fields(record, foreign_objects)117        data["status"] = status118        data["message"] = str(exception)119        return data120    def _serialize(self, obj, status):121        """ Serialize obj and add sync status122        """123        data = self.sync_serializer_class(obj).data124        data["status"] = status125        return data126    def _get_or_create(self, record, foreign_objects):127        fields = self._get_fields(record, foreign_objects)128        fields["defaults"] = {attr: record[attr] for attr in self.attributes}129        obj, created = self.queryset.get_or_create(**fields)...error_handler_config.py
Source:error_handler_config.py  
...19        error_msg = cls(20            code=app_error_code, message=description, details=details21        )22        return error_msg.as_dict()23def _serialize_error(24    http_error_code: int,25    app_error_code: int,26    message: str,27    details: any = None,28) -> tuple:29    error_message = ErrorResponse.build_dict(app_error_code, message, details)30    return jsonify(error_message), http_error_code31def _serialize_app_error(32    http_error_code: int, app_error: AppErrorCode, details: any = None33):34    return _serialize_error(35        http_error_code,36        app_error.value.code,37        app_error.value.description,38        details,39    )40# XXX Faça isto em outro lugar!41def _translate(msg: str) -> str:42    str_browser_not_understand = (43        "The browser (or proxy) sent a request that this "44        "server could not understand."45    )46    what = {47        "Field is required": "Campo é obrigatório.",48        str_browser_not_understand: "Enviada uma requisição não entendida.",49    }50    return what.get(msg, msg)51def app_errorhandling_config(app: Flask):52    # TODO: ajustar erro de unicidade53    # @app.errorhandler(mongoengine.NotUniqueError)54    # def handle_not_unique_error(e):55    #     # XXX Rever56    #     return _serialize_app_error(57    #         400, AppErrorCode.ERROR_DB_NOT_UNIQUE, details=str(e),58    #     )59    # TODO: ajustar erro de validacao60    # @app.errorhandler(mongoengine.ValidationError)61    # def handle_validation_error(e):62    #     if isinstance(e.errors, dict):63    #         details = {64    #             k: _translate(v.message) if v.message else str(v)65    #             for k, v in e.errors.items()66    #         }67    #     else:68    #         details = str(e)69    #     return _serialize_app_error(70    #         400, AppErrorCode.ERROR_DB_VALIDATION_ERROR, details=details71    #     )72    @app.errorhandler(UnprocessableEntity)73    def handle_unprocessable_entity(e):74        return _serialize_app_error(422, AppErrorCode.ERROR_UNPROCESSABLE)75    @app.errorhandler(HTTPException)76    def handle_application_http_error(e):77        http_error_code = e.code or 50078        app_error_code = AppErrorCode.ERROR_GENERIC.value.code79        msg = _translate(e.description)80        details = None81        if isinstance(e, ApplicationException):82            app_error_code = e.app_error_code83            details = e.detail84        return _serialize_error(http_error_code, app_error_code, msg, details)85    @app.errorhandler(Exception)86    def handle_unknown_exception(e):87        # XXX Conforme o caso, além de logar precisarÃamos tratar?88        meta = {"error_key": uuid4()}89        logger.error("Erro inesperado na aplicacao", meta=meta)90        return _serialize_error(91            500,92            AppErrorCode.ERROR_GENERIC.value.code,93            "Erro inesperado",94            details=meta,...excpetion_config.py
Source:excpetion_config.py  
...15    def as_dict(self):16        return asdict(self)171819def _serialize_error(20    http_code: int,21    code: int,22    message: str,23    errors: any = None,24) -> tuple:25    error_message = Error()26    error_message.code = code27    error_message.message = message28    error_message.errors = errors29    return jsonify(error_message), http_code303132def _get_attr_exception(e: BaseException, attr: str, default: any) -> any:33    value = getattr(e, attr, repr(e))34    value = value if value is not None else default35    return value363738def error_handling_config(app: Flask):39    @app.errorhandler(mongoengine.NotUniqueError)40    def handle_not_unique_error(e):41        return _serialize_error(42            400, 400, message=getattr(e, 'message', repr(e)), errors=str(e),43        )4445    @app.errorhandler(UnprocessableEntity)46    def handle_un_processable_entity(e):47        return _serialize_error(48            422, 422, message=getattr(e, 'message', repr(e)), errors=str(e),49        )5051    @app.errorhandler(HTTPException)52    def handle_application_http_error(e):53        code = _get_attr_exception(e, "code", 500)54        error_code = _get_attr_exception(e, "error_code", 500)55        message = _get_attr_exception(e, "message", getattr(e, "description", repr(e)))56        errors = _get_attr_exception(e, "errors", str(e))5758        return _serialize_error(59            error_code, code, message=message, errors=errors,60        )6162    @app.errorhandler(Exception)63    def handle_unknown_exception(e):64        return _serialize_error(65            500, 500, message=getattr(e, "message", repr(e)), errors=str(e),
...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!!
