def on_post(self, req, resp, cpid): data = json.loads(req.bounded_stream.read()) if cpid not in self.bdd.campaigns.keys(): raise falcon.HTTPNotFound( description=f"Campaign {cpid} doesn't exist") try: self.check_params(data) except Exception as e: raise falcon.HTTPUnprocessableEntity(description=str(e)) try: pacing = GlobalPacing( total_budget=int(data['budget']), start_date=datetime.strptime(data['start'], '%Y-%m-%d'), end_date=datetime.strptime(data['end'], '%Y-%m-%d')) self.bdd.instances[data['liid']] = pacing self.bdd.campaigns[cpid].append(data['liid']) output = json.dumps({ "status": "ok", }) except ValueError: raise falcon.HTTPUnprocessableEntity( description= 'Budget could be negative OR start date superior to end ' 'date') resp.status = falcon.HTTP_200 resp.body = output
def on_post(self, request, response, rider_id=None): if not rider_id: raise falcon.HTTPPreconditionFailed("Rider id not provided") rider = helpers.get_rider(rider_id) if not rider: raise falcon.HTTPPreconditionFailed("Rider with id: {} not found".format(rider_id)) if rider.riding: raise falcon.HTTPUnprocessableEntity("Rider is already riding") body = json.load(request.stream) pickup_location = body.get("pickup_location") drop_location = body.get("drop_location") if not pickup_location or not drop_location: raise falcon.HTTPPreconditionFailed("Pickup or Drop location not specified") try: ride = Ride(Location(**pickup_location), Location(**drop_location), rider) except Exception as e: raise falcon.HTTPUnprocessableEntity(e) taxi_category = body.get("category") taxi = helpers.get_nearest_available_taxi(Location(**pickup_location), taxi_category) if not taxi: ride.set_taxi_unavailable() raise falcon.HTTPUnprocessableEntity("Taxi is unavailable") ride.start(taxi) RIDES.append(ride) response.body = json.dumps({"message": "Ride registered.", "data": ride.to_dict()}) response.status = falcon.HTTP_201
def create_activity_log(): box_code_index = 1 for i in range(1, 12): for j in range(1, 31): if i == 2 and j >= 28: continue for k in range(10, 19): activity_collector = ActivityLog() activity_inspector = ActivityLog() activity_collector.box_code = generate_box_index( box_code_index) box_code_index = activity_collector.box_code activity_collector.worker_id = randint(2, 4) activity_collector.payload = WORKERS['ean13'][ activity_collector.worker_id - 1] activity_collector.type = 'COLLECT' activity_collector.status = 'SUCCESS' if i < 10 and j < 10: date = '2019-0{0}-0{1}'.format(i, j) elif i < 10 and j > 9: date = '2019-0{0}-{1}'.format(i, j) elif i > 9 and j < 10: date = '2019-{0}-0{1}'.format(i, j) time = '{0}:55:'.format(k) + str(randint(10, 59)) activity_collector.local_time = date + ' ' + time activity_collector.server_time = date + ' ' + '{0}:55:00'.format( k) try: activity_collector.save() activity_collector.db_session.commit() except Exception: falcon.HTTPUnprocessableEntity() activity_inspector.box_code = box_code_index activity_inspector.worker_id = 1 activity_inspector.payload = randint(30, 80) activity_inspector.type = 'REVIEW' activity_inspector.status = 'SUCCESS' activity_inspector.local_time = date + ' ' + \ '{0}:00:'.format(k+1) + str(randint(10, 59)) activity_inspector.server_time = date + ' ' + '{0}:00:00'.format( k + 1) try: activity_inspector.save() activity_inspector.db_session.commit() except Exception: falcon.HTTPUnprocessableEntity()
def on_post(self, req, resp): # Validate nanopub only using cached assertions/annotations # complete - fill in any missing assertion/annotation validations # force - redo all validations # cached - only return cached/pre-generated validations validation_level = req.get_param('validation_level', default="complete") # BEL Resources loading try: data = req.stream.read(req.content_length or 0) data = data.decode(encoding="utf-8") data = data.replace("\u00a0", " ") # get rid of non-breaking spaces data = json.loads(data) except ValueError as e: raise falcon.HTTPUnprocessableEntity( title="Cannot process payload", description= f"Cannot process nanopub (maybe an encoding error? please use UTF-8 for JSON payload) error: {e}", ) nanopub = {} if "nanopub" in data: nanopub["nanopub"] = data.get("nanopub") else: nanopub = None error_level = data.get("error_level", "WARNING") if nanopub: try: nanopub = bel.nanopub.validate.validate( nanopub, error_level=error_level, validation_level=validation_level) resp.media = nanopub resp.status = falcon.HTTP_200 except Exception as e: log.error(traceback.print_exc()) raise falcon.HTTPUnprocessableEntity( title="Cannot process nanopub", description=f"Cannot process nanopub: {e}") else: raise falcon.HTTPBadRequest( title="Cannot process nanopub", description= f"No nanopub in payload to process. Please check your submission.", )
def on_post(self, req, resp, **kwargs): """ Handles POST requests. Creates a certificate resource for a user. """ try: payload = json.loads(req.stream.read().decode('utf-8')) private_key = base64.b64decode(payload['private_key']) cert = Certificate(user_id=kwargs.get('user_id'), private_key=private_key, active=payload['active'], body=payload['body']) self.session.add(cert) self.session.commit() except KeyError: raise falcon.HTTPBadRequest( description= 'Missing one or more of the following fields: private_key, active, or body' ) except IntegrityError: raise falcon.HTTPNotFound(description='User does not exist') except (DataError, StatementError, json.decoder.JSONDecodeError): raise falcon.HTTPUnprocessableEntity( description= 'Bad request format - make sure all fields are the proper data type.' ) except TypeError: raise falcon.HTTPBadRequest( description='Bad request format - not valid JSON.') resp.status = falcon.HTTP_201 resp.body = json.dumps({'id': cert.id, 'user_id': cert.user_id})
def test_http_unprocessable_with_title_and_desc_and_challenges(self): try: raise falcon.HTTPUnprocessableEntity(title='Test', description='Testdescription') except falcon.HTTPUnprocessableEntity as e: self.assertEqual('Test', e.title, 'Title should be "Test"') self.assertEqual('Testdescription', e.description, 'Description should be "Testdescription"')
def _create(self, req, resp): schema = self.schema_cls() deserialized = json.load(req.bounded_stream) parsed = schema.load(deserialized, session=self.session) if parsed.errors: raise falcon.HTTPUnprocessableEntity(description=parsed.errors) try: self.session.add(parsed.data) self.session.flush() except SQLAlchemyError as err: raise falcon.HTTPUnprocessableEntity(description='Database error') from err resp.body = json.dumps(parsed.data.id, cls=ImprovedJSONEncoder) resp.status = falcon.HTTP_201
def on_get(self, req, resp, **kwargs): """ Handles GET requests. Lists certificate resources for a user. """ user_exists = self.session.query( exists().where(User.id == kwargs.get('user_id'))).scalar() if not user_exists: raise falcon.HTTPNotFound(description='User does not exist') cert_query = self.session.query(Certificate)\ .filter(Certificate.user_id == kwargs.get('user_id')) filter_active = req.get_param('active', default='false') if filter_active not in ['true', 'false']: raise falcon.HTTPUnprocessableEntity( description= 'Bad request format - active query parameter must be "true" or "false".' ) elif filter_active == 'true': cert_query = cert_query.filter(Certificate.active == True) certs = cert_query.all() resp.status = falcon.HTTP_200 resp.body = json.dumps( list( map(lambda c: { 'id': c.id, 'body': c.body, 'active': c.active }, certs)))
def extract_user_from_req(req, hdr_name, claim_fld): with start_action(action_type="extract_user_from_req"): token = extract_access_token_from_req(req, hdr_name) try: claims = parse_access_token(token=token) except (RuntimeError, KeyError) as exc: raise falcon.HTTPForbidden( "Failed to verify JWT claims: {}".format(exc)) username = claims[claim_fld] if not username: raise falcon.HTTPUnprocessableEntity( "Could not determine username from claim field {}!".format( claim_fld)) username = username.lower() if "@" in username: # Process as if email and use localpart equivalent username = username.split("@")[0] e_ns = get_execution_namespace() if not e_ns: e_ns = "user" # pick a reasonable default for user namespaces u_ns = "{}-{}".format(e_ns, quote(username)) user = User( name=username, namespace=u_ns, uid=int(claims["uidNumber"]), access_token=token, claims=claims, ) return user
def on_get(self, req, resp): ''' Return (R, G, B) colour for star of type <type><decimal><size GET /misc/starcolor/<code> Returns { "code": <code>, "RGB": {"red": <red>, "blue": <blue>, "green": <green>} } ''' self.query_parameters = {'code': None} LOGGER.debug('query_string = %s', req.query_string) self.query_parameters = parse_query_string(req.query_string, self.query_parameters) self.clear_data() code = self.query_parameters['code'] self._validate_code(code) try: assert self.code is not None assert self.code != '' except AssertionError: raise falcon.HTTPUnprocessableEntity( title='Bad parameter value {}'.format(code), description='Invalid code {}'.format(code)) self.get_details() doc = {'code': self.code, 'rgb': self.rgb} resp.body = json.dumps(doc) resp.status = falcon.HTTP_200
def test_http_unprocessable_entity_no_title_and_desc_and_challenges(self): try: raise falcon.HTTPUnprocessableEntity() except falcon.HTTPUnprocessableEntity as e: self.assertEqual(status.HTTP_422, e.title, 'The title should be ' + status.HTTP_422 + ', but it is: ' + e.title) self.assertEqual(None, e.description, 'The description should be None')
def on_post(self, req: falcon.Request, resp: falcon.Response, number: str): if number == req.media.get("fragmentNumber"): annotations = self._annotation_service.update( AnnotationsSchema().load(req.media), req.context.user) resp.media = AnnotationsSchema().dump(annotations) else: raise falcon.HTTPUnprocessableEntity( description="Fragment numbers do not match.")
def wrapper(*args, **kwargs): if len(dec_args) == 1: schema = dec_args[0] else: schema = type('schema', (Schema, ), {**dec_kwargs}) try: load = schema().load(args[1].media) except Exception: raise falcon.HTTPUnprocessableEntity() if load.errors != {}: raise falcon.HTTPUnprocessableEntity() args[1].parsed = load.data return func(*args, **kwargs)
def on_post(self, req: falcon.Request, resp: falcon.Response): params = get_and_validate_schema(AppointmentPostSchema, req) try: resp.media = appointment_service.make_and_get_an_appoinment( params, req.context.session ) except AppointmentException as exc: raise falcon.HTTPUnprocessableEntity({'appointment_error': exc.args[0]}) from exc
def _clean(self, request, *args, **kwargs): cleaned = super()._clean(request, *args, **kwargs) usr = getattr(request, 'user', None) is_valid = usr.check_password(cleaned['old_password']) if not is_valid: raise falcon.HTTPUnprocessableEntity( description=_('Wrong password'), ) try: dj_validate_password(cleaned['new_password1']) except DjangoValidationError as e: raise falcon.HTTPUnprocessableEntity( description=e.error_list[0].message, ) if cleaned['new_password1'] != cleaned['new_password2']: raise falcon.HTTPUnprocessableEntity( description=_('Passwords not match'), ) return cleaned
def _update(self, req, resp, resource_id, partial=False): resource = self._get_for_update(resource_id) if not resource: raise falcon.HTTPNotFound() schema = self.schema_cls(instance={}) deserialized = json.load(req.bounded_stream) parsed = schema.load(deserialized, session=self.session, instance=resource, partial=partial) if parsed.errors: raise falcon.HTTPUnprocessableEntity(description=parsed.errors) try: self.session.flush() except SQLAlchemyError as err: raise falcon.HTTPUnprocessableEntity(description='Database error') from err resp.status = falcon.HTTP_204
def _get_data(self, cleaned, *args, **kwargs): user = self.request.user data = cleaned['data']['attributes'] is_valid = user.check_password(data['old_password']) if not is_valid: raise falcon.HTTPUnprocessableEntity( description=_('Wrong password'), ) try: dj_validate_password(data['new_password1']) except DjangoValidationError as e: raise falcon.HTTPUnprocessableEntity( description=e.error_list[0].message, ) if data['new_password1'] != data['new_password2']: raise falcon.HTTPUnprocessableEntity( description=_('Passwords not match'), ) user.set_password(data['new_password1']) user.save() user.is_password_changed = True return user
def on_post(self, req, resp): data = json.loads(req.bounded_stream.read()) try: self.check_params(data) except Exception as e: raise falcon.HTTPUnprocessableEntity(description=str(e)) self.bdd.campaigns[data['cpid']] = [] resp.body = json.dumps({ "status": "ok", })
async def on_websocket(self, req, ws, generic_error): self.called = True if generic_error == 'true': raise Exception('Oh snap!') # NOTE(kgriffs): This may not make a lot of sense to do, but the # framework will try to do something reasonable with it by # rejecting the WebSocket handshake and setting the close code # to 3000 + falcon.util.http_status_to_code(error.status) raise falcon.HTTPUnprocessableEntity()
def on_patch(self, req, resp): # type: (falcon.Request, falcon.Response) -> None new_bets = {bet['id']: bet['result'] for bet in req.context['json']} user = req.context['user'] bets = self.session().query(DBBet).filter_by(better_id = user.id).all() bets = {bet.id: bet for bet in bets} # check all bets to be patched belong to current user bad_ids = new_bets.keys() - bets.keys() if bad_ids: raise falcon.HTTPForbidden(description = \ 'The following bets ids do not exist (or do not belong to you): %s' % ','.join(map(str, bad_ids))) # filter bets to be changed patched_bets = {id: bet for id, bet in bets.items() if id in new_bets.keys()} # ensure all bets are for future matches! now = self.now() past_match_ids = [id for id, bet in patched_bets.items() if bet.match.matchtime <= now] if past_match_ids: raise falcon.HTTPForbidden(description = \ 'The following bets ids are related to past matches, ' + \ 'you are not allowed to place bets on them: %s' % ','.join(map(str, past_match_ids))) # ensure match is already known (teams not "virtual") unknown_match_ids = [id for id, bet in patched_bets.items() if bet.match.team1.group == 'virtual' or bet.match.team2.group == 'virtual'] if unknown_match_ids: raise falcon.HTTPUnprocessableEntity( description = 'The following bets ids relate to match which teams are still not known, ' + \ 'you are not allowed to place bets on them: %s' % ','.join(map(str, unknown_match_ids))) # update patched bets session = self.session() for id, bet in patched_bets.items(): bet.bettime = now bet.result = new_bets[id] # calculate utility columns winner and goals_diff result = RESULT_PATTERN.match(bet.result) goals1 = int(result.group(1)) goals2 = int(result.group(2)) if goals1 > goals2: bet.winner = 1 bet.goals_diff = goals1 - goals2 elif goals1 < goals2: bet.winner = 2 bet.goals_diff = goals2 - goals1 else: bet.winner = 0 bet.goals_diff = 0 session.add(bet) session.commit() session.refresh(bet) req.context['result'] = patched_bets.values()
def on_post(self, req, resp, liid): data = json.loads(req.bounded_stream.read()) ts = datetime.timestamp(datetime.utcnow()) # ts = data['ts'] try: self.check_and_parse_parameters(data) except Exception as e: raise falcon.HTTPUnprocessableEntity(description=str(e)) try: good_instance = self.bdd.instances[liid] except KeyError: raise falcon.HTTPNotFound( description=f"line item {liid} doesn't exist") try: buying, *_ = good_instance.choose_pacing(ts, data['tz'], data['cpm'], data['imps'], data['brid']) except Exception as e: raise falcon.HTTPUnprocessableEntity(description=str(e)) resp.body = json.dumps({'status': 'ok', 'buying': buying}) resp.status = falcon.HTTP_200
def on_patch(self, req, resp, **kwargs): """ Handles PATCH requests. Updates active state for a certificate resource. """ try: payload = json.loads(req.stream.read().decode('utf-8')) active_state = payload['active'] cert_query = self.session.query(Certificate)\ .options(FromCache('default'))\ .filter(Certificate.id == kwargs.get('certificate_id'))\ .filter(Certificate.user_id == kwargs.get('user_id'))\ # Invalidate the cache cert = cert_query.one() cert_query.invalidate() if active_state == cert.active: raise falcon.HTTPBadRequest( description= 'Certificate is already in the requested active state') cert.active = active_state self.session.commit() except KeyError: raise falcon.HTTPBadRequest( description= 'Missing one or more of the following fields: active') except NoResultFound: raise falcon.HTTPNotFound( description= 'No certificate found for the specified user and certificate') except (DataError, StatementError, json.decoder.JSONDecodeError): raise falcon.HTTPUnprocessableEntity( description= 'Bad request format - make sure all fields are the proper data type.' ) except TypeError: raise falcon.HTTPBadRequest( description='Bad request format - not valid JSON.') # Notify external service of change try: if payload.get('notify', False): CertificateService.notify(cert.id, cert.active) except HTTPError as e: raise falcon.HTTPServiceUnavailable( description="Internal service error: {error}".format(error=e)) resp.status = falcon.HTTP_202 resp.body = json.dumps({'id': cert.id, 'active': cert.active})
def on_post(self, req, resp, liid): data = json.loads(req.bounded_stream.read()) try: good_instance = self.bdd.instances[liid] except KeyError: raise falcon.HTTPNotFound( description=f"line item {liid} doesn't exist") try: good_instance.change_setup(data['new_budget']) except Exception as e: raise falcon.HTTPUnprocessableEntity(description=f"Exception {e}") resp.body = json.dumps({'status': 'ok'}) resp.status = falcon.HTTP_200
def on_post(self, req, resp): # BEL Resources loading try: data = json.load(req.bounded_stream) except ValueError as e: raise falcon.HTTPUnprocessableEntity( title="Cannot process payload", description= f"Cannot process nanopub (maybe an encoding error? please use UTF-8 for JSON payload) error: {str(e)}", ) if data.get("nanopub", None) is not None: response_type = data.get("response_type", "nanopub") error_level = data.get("error_level", "WARNING") nanopub = {"nanopub": data.get("nanopub")} try: results = bel.nanopub.validate.validate(nanopub, error_level) log.info(f"Validation results: {results}") if response_type == "nanopub": nanopub["nanopub"]["metadata"]["gd_validation"] = results resp.media = nanopub else: resp.media = {"validation_results": results} resp.status = falcon.HTTP_200 except Exception as e: log.error(traceback.print_exc()) raise falcon.HTTPUnprocessableEntity( title="Cannot process nanopub", description=f"Cannot process nanopub: {str(e)}") else: raise falcon.HTTPBadRequest( title="Cannot process nanopub", description= f"No nanopub in payload to process. Please check your submission.", )
def parse_query_string(self, query_string): '''Parse query string''' if query_string != '': options_list = query_string.split('&') for option in options_list: param, value = option.split('=') if param in self.query_parameters: if isinstance(self.query_parameters[param], list): self.query_parameters[param].append(value) else: self.query_parameters[param] = value else: raise falcon.HTTPUnprocessableEntity( title='Unprocessable request', description='Unknown parameter {}'.format(param))
def on_patch(self, request, response, rider_id=None): if not rider_id: raise falcon.HTTPPreconditionFailed("Rider id not provided") rider = helpers.get_rider(rider_id) if not rider: raise falcon.HTTPPreconditionFailed("Rider with id: {} not found".format(rider_id)) if not rider.riding: raise falcon.HTTPUnprocessableEntity("Rider is currently not riding") body = json.load(request.stream) end_ride = body.get("end_ride", False) if not end_ride: raise falcon.HTTPBadRequest rider_current_ride = helpers.get_rider_current_ride(rider_id) if not rider_current_ride: raise falcon.HTTPUnprocessableEntity("Current ride of Rider: {} not found".format(rider)) rider_current_ride.stop() response.body = json.dumps({"message": "Ride has ended", "data": rider_current_ride.to_dict()}) response.status = falcon.HTTP_200
def wrapper(req, resp, resource, params): if req.method in ('POST', 'PUT'): req_params = extract_params(req) # elif req.method == 'GET': # req_params = req.params elif req.method in ('GET', 'PATCH'): req_params = extract_params(req) try: # import pdb # pdb.set_trace() validate_params(schema, req_params) except ValidationError as err: raise falcon.HTTPUnprocessableEntity(title=err.schema['message'], description=err.message) else: req.context['validated_params'] = req_params
def on_post(self, req, resp, liid): data = json.loads(req.bounded_stream.read()) try: self.check_params(data) except Exception as e: raise falcon.HTTPUnprocessableEntity(description=str(e)) try: good_instance = self.bdd.instances[liid] except KeyError: raise falcon.HTTPNotFound( description=f"line item {liid} doesn't exist") try: good_instance.dispatch_notifications(data['brid'], data['status']) except KeyError: raise falcon.HTTPNotFound( description=f"br with id {data['brid']} doesn't exist") resp.body = json.dumps({'status': 'ok'}) resp.status = falcon.HTTP_200
def validation(_self, _req, _resp, *args, **kwargs): try: if query: setattr(_req.context, 'query', query(**_req.params)) media = _req.media or {} if data: setattr(_req.context, 'data', data(**media)) except ValidationError as err: raise falcon.HTTPUnprocessableEntity( 'Schema failed validation', description=str(err), ) except Exception: raise response = func(_self, _req, _resp, *args, **kwargs) if resp: _resp.media = response.dict() return response
def create_workers(): for i in range(0, 4): # import pdb; pdb.set_trace() worker = Worker() worker.ean13 = WORKERS['ean13'][i] worker.password = Worker.generate_worker_password() worker.name = WORKERS['name'][i] worker.surname = WORKERS['surname'][i] worker.middle_name = WORKERS['middle_name'][i] worker.type = WORKERS['type'][i] try: worker.save() worker.db_session.commit() except Exception: falcon.HTTPUnprocessableEntity() if i == 0: inspector_data.append(str(worker.password))