Best Python code snippet using slash
views.py
Source:views.py
...32 # Validate and return a Bad Request error if necessary33 try:34 schema(request.args.to_dict())35 except MultipleInvalid as err:36 resp = _handle_exception(err, '400')37 else:38 # Call business layer method and return an Internal Server Error if anything goes wrong39 try:40 # Default n to 041 if request.args.get('n'):42 n = request.args['n']43 else:44 n = '0'45 # Check which argument we have and set up appropriate BLO46 if request.args.get('month'):47 bl = BLO_PlantLists()48 plants = bl.get_seasonal_plants(request.args['month'], n)49 resp = _get_response(plants)50 elif request.args.get('id'):51 bl = BLO_PlantLists()52 plants = bl.get_bed_plants(request.args['id'], n)53 resp = _get_response(plants)54 elif request.args.get('name'):55 bl = BLO_Plants()56 plants = bl.get_plants(request.args['name'], n)57 resp = _get_response(plants)58 else:59 # No arguments provided, return bad request error60 resp = _handle_exception('Provide either name, month or id', '400')61 except Exception as err:62 resp = _handle_exception(err, '500')63 return resp64@app.route('/beds')65def get_beds():66 """@app.route('/beds') takes67 plant (plant name number, optional, coercible to int)68 lat (latitude, coercible to float)69 long (longitude, coercible to float)70 n (max number of records required, coercible to int, n=0 returns all71 Finds n flower beds containing a given plant (optional), sorted in order of proximity to a position defined by72 lat, long73 Returns a list of populated Node objects.74 If the plant is not found, an empty list is returned. If n=0, all matches are returned."""75 # Define validation schema76 schema = Schema({77 'plant': Coerce(int),78 Required('lat'): Coerce(float),79 Required('long'): Coerce(float),80 'n': Coerce(int)81 })82 # Validate and return a Bad Request error if necessary83 try:84 schema(request.args.to_dict())85 except MultipleInvalid as err:86 resp = _handle_exception(err, '400')87 else:88 # Call business layer method and return an Internal Server Error if anything goes wrong89 try:90 # Default n to 091 if request.args.get('n'):92 n = request.args['n']93 else:94 n = '0'95 bl = BLO_GIS(GeoNode(0, '', request.args['long'], request.args['lat']))96 beds = bl.get_flower_beds(request.args.get('plant'), n)97 resp = _get_response(beds)98 except Exception as err:99 resp = _handle_exception(err, '500')100 return resp101@app.route('/places')102def get_places():103 """@app.route('/places') takes104 lat (latitude, coercible to float)105 long (longitude, coercible to float)106 n (max number of records required, coercible to int, n=0 returns all107 Finds n places, sorted in order of proximity to a position defined by lat, long108 Returns a list of populated Place objects.109 If none are found, an empty list is returned. If n=0, all matches are returned."""110 # Define validation schema111 schema = Schema({112 Required('lat'): Coerce(float),113 Required('long'): Coerce(float),114 'n': Coerce(int)115 })116 # Validate and return a Bad Request error if necessary117 try:118 schema(request.args.to_dict())119 except MultipleInvalid as err:120 resp = _handle_exception(err, '400')121 else:122 # Call business layer method and return an Internal Server Error if anything goes wrong123 try:124 # Default n to 0125 if request.args.get('n'):126 n = request.args['n']127 else:128 n = '0'129 bl = BLO_GIS(GeoNode(0, '', request.args['long'], request.args['lat']))130 places = bl.get_places(n)131 resp = _get_response(places)132 except Exception as err:133 resp = _handle_exception(err, '500')134 return resp135@app.route('/routes/bed/<int:id>')136def route_bed(id):137 """@app.route('/route/bed') takes138 lat (latitude, coercible to float)139 long (longitude, coercible to float)140 id (id of a flower bed, coercible to int)141 Calculates the shortest route between the given flower bed and a position defined by lat, long142 Returns a Route object.143 If route cannot be calculated, an empty object is returned"""144 # Define validation schema145 schema = Schema({146 Required('lat'): Coerce(float),147 Required('long'): Coerce(float)148 })149 # Validate and return a Bad Request error if necessary150 try:151 schema(request.args.to_dict())152 except MultipleInvalid as err:153 resp = _handle_exception(err, '400')154 else:155 # Call business layer method and return an Internal Server Error if anything goes wrong156 try:157 bl = BLO_Route(GeoNode(0, '', request.args['long'], request.args['lat']))158 route = bl.get_bed_route(id)159 resp = _get_response(route)160 except BedNotFound as err:161 # id doesn't exist, return 404162 resp = _handle_exception(err, '404')163 except Exception as err:164 resp = _handle_exception(err, '500')165 return resp166@app.route('/routes/place/<int:id>')167def route_place(id):168 """@app.route('/route/place') takes169 lat (latitude, coercible to float)170 long (longitude, coercible to float)171 id (id of a place, coercible to int)172 Calculates the shortest route between the given place and a position defined by lat, long173 Returns a Route object.174 If route cannot be calculated, an empty object is returned"""175 # Define validation schema176 schema = Schema({177 Required('lat'): Coerce(float),178 Required('long'): Coerce(float)179 })180 # Validate and return a Bad Request error if necessary181 try:182 schema(request.args.to_dict())183 except MultipleInvalid as err:184 resp = _handle_exception(err, '400')185 else:186 # Call business layer method and return an Internal Server Error if anything goes wrong187 try:188 bl = BLO_Route(GeoNode(0, '', request.args['long'], request.args['lat']))189 route = bl.get_place_route(id)190 resp = _get_response(route)191 except PlaceNotFound as err:192 # id doesn't exist, return 404193 resp = _handle_exception(err, '404')194 except Exception as err:195 resp = _handle_exception(err, '500')196 return resp197def _get_response(resp_obj):198 # Success! Encode response and set up a Response object199 # Status code will be 200200 resp = make_response(jsonpickle.encode(resp_obj))201 resp.mimetype = 'application/json'202 return resp203def _handle_exception(err, code):204 # Failure! Encode error message and set up status205 print("Exception: ", err)206 resp = make_response(jsonpickle.encode(str(err)))207 resp.mimetype = 'application/json'208 resp.status = code209 return resp210if __name__ == '__main__':...
ir_http.py
Source:ir_http.py
...78 except Exception:79 _logger.exception("Exception during request Authentication.")80 raise openerp.exceptions.AccessDenied()81 return auth_method82 def _handle_exception(self, exception):83 # If handle_exception returns something different than None, it will be used as a response84 return request._handle_exception(exception)85 def _dispatch(self):86 # locate the controller method87 try:88 rule, arguments = self._find_handler(return_rule=True)89 func = rule.endpoint90 except werkzeug.exceptions.NotFound, e:91 return self._handle_exception(e)92 # check authentication level93 try:94 auth_method = self._authenticate(func.routing["auth"])95 except Exception:96 # force a Forbidden exception with the original traceback97 return self._handle_exception(98 convert_exception_to(99 werkzeug.exceptions.Forbidden))100 processing = self._postprocess_args(arguments, rule)101 if processing:102 return processing103 # set and execute handler104 try:105 request.set_handler(func, arguments, auth_method)106 result = request.dispatch()107 if isinstance(result, Exception):108 raise result109 except Exception, e:110 return self._handle_exception(e)111 return result112 def _postprocess_args(self, arguments, rule):113 """ post process arg to set uid on browse records """114 for arg in arguments.itervalues():115 if isinstance(arg, orm.browse_record) and arg._uid is UID_PLACEHOLDER:116 arg._uid = request.uid117 try:118 arg[arg._rec_name]119 except KeyError:120 return self._handle_exception(werkzeug.exceptions.NotFound())121 def routing_map(self):122 if not hasattr(self, '_routing_map'):123 _logger.info("Generating routing map")124 cr = request.cr125 m = request.registry.get('ir.module.module')126 ids = m.search(cr, openerp.SUPERUSER_ID, [('state', '=', 'installed'), ('name', '!=', 'web')], context=request.context)127 installed = set(x['name'] for x in m.read(cr, 1, ids, ['name'], context=request.context))128 if openerp.tools.config['test_enable']:129 installed.add(openerp.modules.module.current_test)130 mods = [''] + openerp.conf.server_wide_modules + sorted(installed)131 self._routing_map = http.routing_map(mods, False, converters=self._get_converters())132 return self._routing_map133def convert_exception_to(to_type, with_message=False):134 """ Should only be called from an exception handler. Fetches the current...
error_handling_context.py
Source:error_handling_context.py
...43 :param exc_tb: exception traceback44 :return: falsable statement if exception wasn't handled,45 truable otherwise46 """47 exc_handled = await _handle_exception(48 exc_val, exc_tb=exc_tb,49 ws_con=self._ws_con50 )51 await self._ws_con.close()52 return exc_handled53@functools.singledispatch54async def _handle_exception(exc_val, exc_tb, ws_con) -> bool:55 """56 Handles exception raised inside the context of a context manager57 :param exc_val: instance of the raised exception58 :param exc_tb: exception traceback59 :return: True if the exception was handled, False otherwise60 """61 return False # don't handle exceptions by default62@_handle_exception.register(asyncio.CancelledError)63@_handle_exception.register(asyncio.TimeoutError)64async def _(exc_val, exc_tb, ws_con):65 await send_error_message_by_code(ws=ws_con, error_code=5000)66 return True67@_handle_exception.register(MessageFormatViolationError)68async def _(exc_val, exc_tb, ws_con):...
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!!