Add new code for metric API.

This commit is contained in:
yohan 2024-02-01 13:01:43 +01:00
parent 6527b16787
commit b06f4e65a5

115
api.py
View File

@ -54,7 +54,8 @@ api = Api(app, version='1.0', title='Store metrics in DB',
description='API to record and access metrics.', authorizations=authorizations) description='API to record and access metrics.', authorizations=authorizations)
ns_stock = api.namespace('stock/', description='Stock API') ns_stock = api.namespace('stock/', description='Stock API')
ns_electricity = api.namespace('electricity/', description='Electricity API') ns_float_metric = api.namespace('float_metric/', description='Float metric API')
ns_integer_metric = api.namespace('integer_metric/', description='Integer metric API')
class Stock(db.Model): class Stock(db.Model):
__tablename__ = "Stock" __tablename__ = "Stock"
@ -64,31 +65,73 @@ class Stock(db.Model):
volume = db.Column(db.Integer, nullable=False) volume = db.Column(db.Integer, nullable=False)
metric = db.Column(db.String(10), index=True, nullable=False) metric = db.Column(db.String(10), index=True, nullable=False)
model = api.model('Model', { class Float_metric(db.Model):
'time': fields.DateTime(dt_format='iso8601'), __tablename__ = "Float_metric"
'price': fields.Float(required=True, description='price'), id = db.Column(db.Integer, primary_key=True, autoincrement=True)
'volume': fields.Integer(required=True, description='volume'), time = db.Column(db.DateTime, nullable=False)
'metric': fields.String(required=True, description='Stock name'), value = db.Column(db.Float, nullable=False)
}) metric = db.Column(db.String(10), index=True, nullable=False)
resource_fields = { class Integer_metric(db.Model):
__tablename__ = "Integer_metric"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
time = db.Column(db.DateTime, nullable=False)
value = db.Column(db.Integer, nullable=False)
metric = db.Column(db.String(10), index=True, nullable=False)
Stock_resource_fields = {
'time': fields.DateTime(dt_format='iso8601'), 'time': fields.DateTime(dt_format='iso8601'),
'price': fields.Float(required=True, description='price'), 'price': fields.Float(required=True, description='price'),
'volume': fields.Integer(required=True, description='volume'), 'volume': fields.Integer(required=True, description='volume'),
'metric': fields.String(required=True, description='Stock name'), 'metric': fields.String(required=True, description='Stock name'),
} }
fields_pagination = {
Float_metric_resource_fields = {
'time': fields.DateTime(dt_format='iso8601'),
'value': fields.Float(required=True, description='value'),
'metric': fields.String(required=True, description='Metric name'),
}
Integer_metric_resource_fields = {
'time': fields.DateTime(dt_format='iso8601'),
'value': fields.Integer(required=True, description='value'),
'metric': fields.String(required=True, description='Metric name'),
}
Stock_model = api.model('Stock_Model', Stock_resource_fields)
Float_metric_model = api.model('Float_metric_Model', Float_metric_resource_fields)
Integer_metric_model = api.model('Integer_metric_Model', Integer_metric_resource_fields)
Stock_fields_pagination = {
'current_page': fields.Integer(description='current page number'), 'current_page': fields.Integer(description='current page number'),
'pages': fields.Integer(description='pages count'), 'pages': fields.Integer(description='pages count'),
'total_results': fields.Integer(description='results count'), 'total_results': fields.Integer(description='results count'),
'datas': fields.Nested(api.model('Model_resource', resource_fields)) 'datas': fields.Nested(api.model('Stock_Model_resource', Stock_resource_fields))
} }
model_pagination = api.model('Model_pagination', fields_pagination)
Float_metric_fields_pagination = {
'current_page': fields.Integer(description='current page number'),
'pages': fields.Integer(description='pages count'),
'total_results': fields.Integer(description='results count'),
'datas': fields.Nested(api.model('Float_metric_Model_resource', Float_metric_resource_fields))
}
Integer_metric_fields_pagination = {
'current_page': fields.Integer(description='current page number'),
'pages': fields.Integer(description='pages count'),
'total_results': fields.Integer(description='results count'),
'datas': fields.Nested(api.model('Integer_metric_Model_resource', Integer_metric_resource_fields))
}
Stock_model_pagination = api.model('Stock_Model_pagination', Stock_fields_pagination)
Float_metric_model_pagination = api.model('Float_metric_Model_pagination', Float_metric_fields_pagination)
Integer_metric_model_pagination = api.model('Integer_metric_Model_pagination', Integer_metric_fields_pagination)
@ns_stock.route('/add') @ns_stock.route('/add')
class Global_stocks(Resource): class Global_stocks(Resource):
@auth_required @auth_required
@api.expect(model, validate=True) @api.expect(Stock_model, validate=True)
def post(self): def post(self):
try: try:
data = Stock(**request.json) data = Stock(**request.json)
@ -102,7 +145,7 @@ class Global_stocks(Resource):
@ns_stock.route('/search') @ns_stock.route('/search')
class Search_stocks(Resource): class Search_stocks(Resource):
@auth_required @auth_required
@api.marshal_with(model_pagination, envelope='resource') @api.marshal_with(Stock_model_pagination, envelope='resource')
def get(self): def get(self):
logging.debug(json.loads(request.args.get("filter"))) logging.debug(json.loads(request.args.get("filter")))
page = request.args.get('page', default = 1, type = int) page = request.args.get('page', default = 1, type = int)
@ -128,8 +171,52 @@ class Search_stocks(Resource):
logging.debug(result) logging.debug(result)
return result return result
@ns_float_metric.route('/add')
class Global_float_metric(Resource):
@auth_required
@api.expect(Float_metric_model, validate=True)
def post(self):
try:
data = Float_metric(**request.json)
db.session.add(data)
db.session.commit()
return "OK", 201
except Exception as e:
logging.error(e)
return "K0", 400
@ns_float_metric.route('/search')
class Search_float_metric(Resource):
@auth_required
@api.marshal_with(Float_metric_model_pagination, envelope='resource')
def get(self):
logging.debug(json.loads(request.args.get("filter")))
page = request.args.get('page', default = 1, type = int)
filters = json.loads(request.args.get("filter", default = '*', type = str))
record_query = Float_metric.query.filter()
for metric_filter in filters:
if 'name' in metric_filter.keys():
if metric_filter['name'] == 'metric':
record_query = record_query.filter(Float_metric.metric == metric_filter["val"])
if metric_filter['name'] in ['value', 'time']:
if metric_filter['op'] == 'le':
record_query = record_query.filter(getattr(Float_metric, metric_filter['name']) <= metric_filter["val"])
if metric_filter['op'] == 'ge':
record_query = record_query.filter(getattr(Float_metric, metric_filter['name']) >= metric_filter["val"])
if metric_filter['op'] == 'eq':
record_query = record_query.filter(getattr(Float_metric, metric_filter['name']) == metric_filter["val"])
record_query = record_query.paginate(page=page, per_page=20)
result = dict(datas=record_query.items,
total_results=record_query.total,
current_page=record_query.page,
pages=record_query.pages)
logging.debug(result)
return result
api.add_namespace(ns_stock) api.add_namespace(ns_stock)
api.add_namespace(ns_electricity) api.add_namespace(ns_float_metric)
api.add_namespace(ns_integer_metric)
db.create_all() db.create_all()
migrate = Migrate(app, db, compare_type=True) migrate = Migrate(app, db, compare_type=True)