def on_post(self, req: falcon.Request, resp: falcon.Response, ip: str = None): results = list() with geoip2.database.Reader( self.asn_path) as reader: # pragma: no cover for ip in req.media.get("ips", None): try: lookup = reader.asn(ip) results.append({ "ip": lookup.ip_address, "asn_number": lookup.autonomous_system_number, "asn_org": lookup.autonomous_system_organization, }) except geoip2.errors.AddressNotFoundError: # pragma: no cover raise falcon.HTTPBadRequest("Bad Request", "No response for query.") resp.media = results
def on_get(self, req, resp, username, val): ''' username: token val from url val: the param value if username in authorized user: process request else: raise exception ''' if username in authorized_user: param = req.url.split('/')[-2] doc = pd.read_sql( 'select "AGENCY_ID", "MONTHS", "PL_START_YEAR", "STATE_ABBR" from detailed_table where "{0}" = {1}' .format(param, val), engine).to_dict('list') # create json representation resp.body = json.dumps(doc, ensure_ascii=False) # not required as default status returned by framework in 200 resp.status = falcon.HTTP_200 else: raise falcon.HTTPBadRequest('Unauthorized user!!!!')
def on_get(self, req, resp, id): tournament = m.Tournament.get(id=id) if not tournament.terminated: raise falcon.HTTPBadRequest( "Tournament isn't terminated yet", "Spirits are visible after tournament") teamId = req.params.get('teamId') if teamId: qr = m.SpiritAvg.select().where( m.SpiritAvg.tournamentId == id, m.SpiritAvg.teamId == teamId).dicts() else: qr = m.SpiritAvg.select().where( m.SpiritAvg.tournamentId == id).dicts() spirits = [] for spirit in qr: del spirit['matchesGiven'], spirit['tournamentId'] spirits.append(spirit) collection = {'count': len(spirits), 'items': spirits} req.context['result'] = collection
def insert(self, table=None, data=None): Table = next((table_class for table_class in self.base.classes if table_class.__name__.lower() == table.lower()), None) columns = [ column_class.name for column_class in Table.__table__.columns ] to_insert = { key: value for key, value in data.iteritems() if key in columns } if Table: item = Table(**to_insert) with self.session() as session: try: session.add(item) session.commit() return self.get_table_contents(Table, per_page=1)[0] except Exception as e: print e msg = find_error_msg(e.message) raise falcon.HTTPBadRequest(title="Error", description=msg) else: raise falcon.HTTPNotFound(title="404", description="Not found")
def process_request(self, req, resp): # req.stream corresponds to the WSGI wsgi.input environ variable, # and allows you to read bytes from the request body. # # See also: PEP 3333 if req.content_length in (None, 0): # Nothing to do return body = req.stream.read() if not body: raise falcon.HTTPBadRequest('Empty request body', 'A valid JSON document is required.') try: req.context['doc'] = json.loads(body.decode('utf-8')) except (ValueError, UnicodeDecodeError): raise falcon.HTTPError(falcon.HTTP_753, 'Malformed JSON', 'Could not decode the request body. The ' 'JSON was incorrect or not encoded as ' 'UTF-8.')
def on_post(self, req, resp): body = req.media if not body: raise falcon.HTTPBadRequest('Empty request body', 'A valid JSON document is required.') username = body['username'] password = body['password'] user = db.query(User).filter(User.username == username).first() print(user.password) print(password) if user is None or not sha256.verify(body['password'], user.password): raise falcon.HTTPUnauthorized( title='Unauthorized', description='Authentication failed!!!') token = jwt.encode(dict(user_id=user.id, exp=datetime.utcnow() + timedelta(seconds=int(JWT_EXP_DELTA_SECONDS))), JWT_SECRET, algorithm=JWT_ALGORITHM) resp.status = falcon.HTTP_200 resp.body = json.dumps( dict(id=user.id, username=user.username, token=token.decode('UTF-8')))
def on_post(self, req, resp): session = req.context['session'] user = session.user warehouse_id = user.warehouse_id params = req.media job_type = params['job_type'] job_prefix = warehouse_id + datetime.utcnow().strftime("%Y%m%d") job_id = SequenceIdGenerator.get_sequence_id(job_prefix) job = SortJobAccessor.create_if_no_running(job_id, job_type, warehouse_id) if job: resp.media = {"job_id": job_id} if job_type == CPSortJob.Type.AllocateCabinetLattice: CPSortJobTasks.run_allocate_cabinet_job.delay(job_id) elif job_type == CPSortJob.Type.CheckInboundParcelReadyToShip: CPSortJobTasks.run_check_ready_to_ship_job.delay(job_id) else: raise falcon.HTTPBadRequest( description="创建失败,有任务未结束,请先取消其他未结束的任务.")
def on_post(self, req, resp): # start_date = arrow.get(req.get_param('start')).datetime if req.get_param else None # end_date = arrow.get(req.get_param('end')).datetime if req.get_param else None token = req.context['token'] user_id = Token.getUserId(token) location_id = req.get_param_as_int('location_id') location = get_location_by_id(location_id) if location.owner_id != user_id: raise falcon.HTTPBadRequest( "Not Authorized", "This user is not authorized to access that location.") new_event = Event( title=req.get_param('title'), start=req.get_param_as_datetime('start', '%Y-%m-%dT%H:%M:%S.%fZ'), end=req.get_param_as_datetime('end', '%Y-%m-%dT%H:%M:%S.%fZ'), location_id=req.get_param('location'), owner_id=user_id) returned_event = add_to_db(new_event) resp.body = json.dumps(returned_event)
def on_post(self, req, resp): data = req.context['data'] # check data if self.check_data(data) != True: raise falcon.HTTPBadRequest('lacking request body') """ set Email. """ mail = self.set_email(data) try: response = self.mail_send_post(mail.get()) except: raise falcon.HTTPError(falcon.HTTP_753, 'failed send email') # response.headers if (300 > response.status_code) and (response.status_code >= 200): # resp.body = json.dumps({ # 'status': 1, # 'message': response.body # }) resp.body = '{"status": 1 ,"message": "' + response.body + '"}' resp.status = falcon.HTTP_200
def DeleteACLSchema(**request_handler_args): req = request_handler_args['req'] authUser(req, request_handler_args['resp'], ['deleteACLSchema']) try: schema = Schema.objects.get( {"_id": ObjectId(request_handler_args['uri_fields']['id'])}) except InvalidId as e: raise falcon.HTTPBadRequest('Bad Request', str(e)) except Schema.DoesNotExist: raise falcon.HTTPNotFound() else: try: schema.delete() req.context['logger'].info({ 'action': 'deleteACLSchema', 'message': "'%s' ACLSchema with id of %s was deleted successfully." % (schema.name, schema._id) }) except Schema.OperationError as e: raise falcon.HTTPInternalServerError('Internal Server Error', e.message)
def updated_resource(resources: hug.types.text, resource_id: hug.types.text, data, response): """This method updates a resource completely""" if resources == 'v1': # This is necessary when resource_id is empty return False try: results = { 'results': [{ resource_id: db.update_res(resources, resource_id, str(data)) }] } log.debug('Results ' + str(results)) if results['results'][0][resource_id]: return json.dumps(results) raise except Exception as e: log.error( 'Could not update Resource: ' + resources + ' with data: ' + str(data), e) raise falcon.HTTPBadRequest('Update Resource Error', 'Failed to update Resource')
def on_post(self, req, resp, *args, **kwargs): super(UpdateUser, self).on_post(req, resp, *args, **kwargs) current_user = req.context["auth_user"] #Assegurar que el id del favor correspon al id del usuari try: if (req.media["username"]) is not None: current_user.username = req.media["username"] if (req.media["email"]) is not None: current_user.email = req.media["email"] if (req.media["phone"]) is not None: current_user.phone = req.media["phone"] if (req.media["password"]) is not None: current_user.password = req.media["password"] self.db_session.add(current_user) self.db_session.commit() resp.status = falcon.HTTP_200 except NoResultFound: raise falcon.HTTPBadRequest( description=messages.user_not_found) # TODO
def process_request(self, req, resp): if req.protocol.lower() == 'https': return xfp = req.get_header('X-FORWARDED-PROTO') if xfp and xfp.lower() == 'https': return forwarded = req.get_header('FORWARDED') if forwarded: # NOTE(kgriffs): The first hop must indicate HTTPS, # otherwise the chain is already insecure. first, __, __ = forwarded.partition(',') match = _FORWARDED_PROTO_RE.search(first) if match and match.group(1).lower() == 'https': return raise falcon.HTTPBadRequest( title='HTTPS Required', description=( 'All requests must be performed via the HTTPS protocol. ' 'Please switch to HTTPS and try again.'))
def on_post(self, req, resp): content = req.media.get('content') for required_attribute in [TEXT, SOURCE, EXTERNAL_ID]: if required_attribute not in content: raise falcon.HTTPBadRequest( description="Missing required attribute: " + required_attribute) try: external_id = content[EXTERNAL_ID] external_source = content[SOURCE].lower() handler.register_content(content[TEXT], external_id, external_source) resp.status = falcon.HTTP_201 except sqlite3.IntegrityError as sqlite_ex: logger.exception(sqlite_ex) raise falcon.HTTPConflict( description= "Unable to save content due to SQlite3 integrity error. Is the content a duplicate?" ) except Exception as ex: logger.exception(ex) raise falcon.HTTPInternalServerError()
def on_post(self, req, resp): """ Accept twilio POST that has message delivery status, and pass it to iris-api """ try: re = self.iclient.post(self.endpoint, req.context['body'], raw=True) except MaxRetryError: logger.exception('Failed posting data to iris-api') raise falcon.HTTPInternalServerError('Internal Server Error', 'API call failed') if re.status is not 204: logger.error( 'Invalid response from API for delivery status update: %s', re.status) raise falcon.HTTPBadRequest('Likely bad params passed', 'Invalid response from API') resp.status = falcon.HTTP_204
def on_post(self, req, resp): #NOTE this doesnt run yolo , only frcnn - call detect_yolo instead of detect_frcnnif we need yolo here serializer = msgpack resp.content_type = "application/x-msgpack" try: data = serializer.loads(req.stream.read()) img_arr = data.get("image") roi = data.get("roi") if roi: r_x1, r_y1, r_x2, r_y2 = roi img_arr = img_arr[r_y1:r_y2, r_x1:r_x2] print "ROI: {},{},{},{}; img_arr.shape: {}".format( r_x1, r_x2, r_y1, r_y2, str(img_arr.shape)) detected = self.detect_rcnn(img_arr) if roi and (r_x1, r_y1) != (0, 0): for obj in detected: x1, y1, x2, y2 = obj["bbox"] obj["bbox"] = x1 + r_x1, y1 + r_y1, x2 + r_x1, y2 + r_y1 resp.data = serializer.dumps({"data": detected}) resp.status = falcon.HTTP_200 except: raise falcon.HTTPBadRequest("Something went wrong in post :(", traceback.format_exc())
def on_post(req, resp): body = req.stream.read() if not body: raise falcon.HTTPBadRequest('Empty request body', 'A valid JSON document is required.') try: req.context['body'] = json.loads(body.decode('utf-8')) except (ValueError, UnicodeDecodeError): raise falcon.HTTPError( falcon.HTTP_753, 'Malformed JSON', 'Could not decode the request body. The ' 'JSON was incorrect or not encoded as ' 'UTF-8.') # Create a JSON representation of the resource resp.body = json.dumps(req.context['body'], ensure_ascii=False) # The following line can be omitted because 200 is the default # status returned by the framework, but it is included here to # illustrate how this may be overridden as needed. resp.status = falcon.HTTP_200
def try_it(*args, **kwargs): try: return fun(*args, **kwargs) except falcon.HTTPNotFound: raise except exceptions.DoesNotExistException: raise falcon.HTTPNotFound except falcon.HTTPBadRequest: raise except exceptions.AlreadyExistsException as ex: raise falcon.HTTPConflict(ex.__class__.__name__, ex.message) except exceptions.InvalidUpdateException as ex: raise falcon.HTTPBadRequest(ex.__class__.__name__, ex.message) except exceptions.RepositoryException as ex: LOG.exception(ex) msg = " ".join(map(str, ex.message.args)) raise falcon.HTTPInternalServerError('Service unavailable', msg) except Exception as ex: LOG.exception(ex) raise falcon.HTTPInternalServerError('Service unavailable', ex)
def on_get(self, req, resp, userId, locationId, deviceId, sensorId): finalTimestamp = int(time.time()) initialTimestamp = finalTimestamp - 3600 * 6 try: data = influxdb_interface.getData( self.influxdb, locationId, sensorId, initialTimestamp, finalTimestamp, maxValues=50, ) data = [float(value["value"]) for value in data] except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, data)
def on_post(self, req: Request, resp: Response): """Create a new user. Required fields: - ``username`` - ``first_name`` - ``last_name`` - ``password`` Raises ------ HTTPBadRequest : If a user named ``username`` already exists. """ username = req.media["username"] if not self.db.user_exists(username): raise falcon.HTTPBadRequest(f"User {username} already exists.") self.db.create_user(**req.media) resp.status = falcon.HTTP_201
def on_post(self, req, resp): model = models.Company( name=req.media.get('name'), address=req.media.get('address'), city=req.media.get('city'), state=req.media.get('state'), zip_code=req.media.get('zip_code'), sub_type='Premium', status='ACTIVE' ) try: model.save(self.db.session) except IntegrityError as err: raise falcon.HTTPBadRequest( 'Company already exists ' 'Error: {}'.format(str(err)) ) resp.status = falcon.HTTP_201 resp.media = { 'id': model.id }
def process_request(self, req, resp): """process_request, translates json Args: req (object): request object resp (object): response object Returns: object: sets data as a req param Raises: falconHTTPBadRequest: some thing happened in processing the request """ if req.method == "GET": pass else: try: req.data = json.loads(req.stream.read().decode("utf-8")) except: raise falcon.HTTPBadRequest( title="Bad request", description= "Invalid body. Unable to parse the given content", )
def process_response(self, req, res, resource=None, req_succeeded=None): """ Handle post-processing of the response (after routing). """ if not req.context.get("session"): return session = req.context["session"] if config.DB_AUTOCOMMIT: try: session.commit() except SQLAlchemyError as e: logger.warning( f"Encountered error during database commit: {e}") session.rollback() raise falcon.HTTPBadRequest() if self._scoped: # remove any database-loaded state from all current objects # so that the next access of any attribute, or any query execution will retrieve new state session.remove() else: session.close()
def on_post(self, req, resp): "/register" req_json = json.loads(req.bounded_stream.read(), encoding='utf-8') for key in req_json.keys(): if key not in ['username', 'password']: raise falcon.HTTPBadRequest( description=f"{key}, key error, not in allow field.") # 401 error will raise in auth_service register_status = self.auth_service.register( username=req_json['username'], password=req_json['password']) if register_status: # register success and login. login_jwt = self.auth_service.login(username=req_json['username'], password=req_json['password']) resp.set_cookie('Authorization', f'Bearer {login_jwt}', max_age=JWT_EXPIRE_TIME) resp.media = {'key': login_jwt} resp.status = falcon.HTTP_200 return True raise falcon.HTTPUnauthorized()
def on_post(self, req, resp, *args, **kwargs): super(UpdateRate, self).on_post(req, resp, *args, **kwargs) current_user = req.context["auth_user"] #Assegurar que el id del favor correspon al id del usuari if "id" in kwargs: question = self.db_session.query(Question).filter( Question.id == kwargs["id"]).one() try: if (req.media["rating"]) is not None: question.rate = req.media["rating"] print("RATE----------" + str(question.rate)) self.db_session.add(question) self.db_session.commit() resp.status = falcon.HTTP_200 except NoResultFound: raise falcon.HTTPBadRequest( description=messages.user_not_found) # TODO
def parse_int(value: str) -> int: """Parse an inbound string value into an integer. This is meant to be used in the context of a Falcon responder, so that an invalid string triggers a ``400 Bad Request`` error response. Parameters ---------- value : str Returns ------- as_int : int Raises ------ HTTPBadRequest : If ``value`` could not be converted to an integer. """ try: return int(value) except TypeError: raise falcon.HTTPBadRequest(f"Cannot interpret {value} as an integer")
def process_request(self, req, resp): if req.content_length in (None, 0): return body = req.stream.read() if not body: raise falcon.HTTPBadRequest('Empty request body', 'A valid JSON document is required.') try: req.context['doc'] = json.loads(body.decode('utf-8')) except ValueError: self.logger.trace("Malformed data received " "via {op} at {uri}:\n".format( op=req.method, uri=req.relative_uri) + body.decode('utf-8')) raise falcon.HTTPError(falcon.HTTP_753, 'Malformed JSON', 'Could not decode the request body.') except UnicodeDecodeError: self.logger.trace("Malformed data received " "via {op} at {uri}:\n".format( op=req.method, uri=req.relative_uri) + str(body)) raise falcon.HTTPError(falcon.HTTP_753, 'Encoding error', 'Could not decode payload as UTF-8')
def on_post(self, req, res): self.logger.debug('aaaa') self.logger.debug(req.media) image = req.media.get('image', None) if image is None: raise falcon.HTTPMissingParam('image') if not isinstance(image, list): raise falcon.HTTPInvalidParam( 'This params is must be "list" type.', 'image') try: request = create_request(1, image) future = self.stub.Predict.future(request, 5.0) predict = future.result().outputs res.media = { key: tf.make_ndarray(predict[key]).tolist() for key in self.predict_keys } except InvalidImageError as e: raise falcon.HTTPBadRequest('Invalid image data.') except Exception as e: self.logger.error(e) traceback.print_exc() raise falcon.HTTPInternalServerError()
def on_post(self, req, resp, userId, locationId, sensorId): # First check if the user grantedRole = dbinterface.selectUserLocationRole( self.db, userId, locationId) if grantedRole < api_utils.Roles.viewer: raise falcon.HTTPUnauthorized( "Unauthorized", "The user is not authorized to retrive this data.") try: fromDate = calendar.timegm(parse(req.media["from"]).timetuple()) toDate = calendar.timegm(parse(req.media["to"]).timetuple()) data = influxdb_interface.getActionsData(self.influxdb, locationId, sensorId, fromDate, toDate) processedData = [] for value in data: action = value["state"] if action is None: action = value["setToogle"] processedData.append(( str(action), calendar.timegm(parse(value["time"]).timetuple()) * 1000, )) except: logger.error( f"Exception. userId: {userId}, locationId: {locationId}", exc_info=True, ) raise falcon.HTTPBadRequest("Bad Request", "The request can not be completed.") resp.media = getResponseModel(True, processedData)
def on_post(self, req, resp, post_body): try: post_body = json.loads(post_body) except ValueError: logger.error('No POST body') raise falcon.HTTPBadRequest( 'Missing parameters', 'Missing build request body or bad request') if not post_body.get('git_repo') or not post_body.get('docker_image'): logger.error('Missing "git_repo" or "docker_image"') raise falcon.HTTPMissingParam( 'Missing git_repo({}) or docker_image({})'.format( post_body.get('git_repo'), post_body.get('docker_image'))) logger.debug('Building image') docker_build = build_image(req.auth, post_body['docker_image'], post_body['git_repo'], post_body.get('docker_tag'), post_body.get('git_branch'), post_body.get('git_directory')) if docker_build: logger.error('Build failed') raise falcon.HTTPInternalServerError('Docker Build failed', docker_build) if 'push' in req.query_string: logger.debug('Push the image to repo') docker_push = push_image(post_body['docker_image'], post_body.get('docker_tag'), post_body.get('registry_user'), post_body.get('registry_password')) if docker_push: logger.error('Push failed') raise falcon.HTTPInternalServerError('Docker Push failed', docker_push) resp.status = falcon.HTTP_200 # This is the default status resp.body = '{{"title": "Build Successful", "description": "Successfully build and pushed {} image and it\'s ' \ 'ready to be deployed"}}'.format(post_body['docker_image'])