class AddFertilizer(Resource): """ Endpoint that is called to add a new fertilizer to the DB """ input_args = { 'fertilizer_name': fields.Str(required=True), 'bag_weight_kg': fields.Float(required=True), 'bag_cost_INR': fields.Int(required=True), 'n_per_bag_kg': fields.Float(required=True), 'p_per_bag_kg': fields.Float(required=True), 'k_per_bag_kg': fields.Float(required=True), 'taluka_code': fields.Int(required=True), 'user_id': fields.Str(required=True) } @use_args(input_args) def __init__(self, args): ###################### Inputs from API ###################### self.fertilizer_name = args["fertilizer_name"] self.bag_weight_kg = args["bag_weight_kg"] self.bag_cost_INR = args["bag_cost_INR"] self.n_per_bag_kg = args["n_per_bag_kg"] self.p_per_bag_kg = args["p_per_bag_kg"] self.k_per_bag_kg = args["k_per_bag_kg"] self.taluka_code = args["taluka_code"] self.user_id = args["user_id"] ############################################################# self.cost_per_kg = 0 self.input_list = [] self.activity = "insert" def post(self): # Insert a new fertilizer into the fertilizer_ref_tbl ts = time.time() self.activity_timestamp = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') self.cost_per_kg = self.bag_cost_INR / self.bag_weight_kg self.input_list = [ self.fertilizer_name, self.cost_per_kg, self.bag_weight_kg, self.bag_cost_INR, self.n_per_bag_kg, self.p_per_bag_kg, self.k_per_bag_kg, self.taluka_code, self.user_id, self.activity, self.activity_timestamp ] input_parm = tuple(self.input_list) sql = api_insert_options.insert_fertilizer_ref_tbl message = DatabaseConnection().insert_table_detail(sql, input_parm) return message
class AdminDeliveryConfigHomeView(AdminBaseView): """后台-订单-送货上门设置""" @use_args( { "home_minimum_order_amount": fields.Float( required=True, comment="配送模式起送金额" ), "home_delivery_amount": fields.Float(required=True, comment="配送模式配送费"), "home_minimum_free_amount": fields.Float( required=True, comment="配送模式免配送费最小金额" ), }, location="json" ) def put(self, request, args): import time t1 = time.time() success, msg = update_delivery_config( self.current_shop.id, args, self.current_user.id ) if not success: return self.send_fail(error_text=msg) print(time.time()-t1) return self.send_success()
class Hallway(StructuredNode, Node): """Hallway model""" __validation_rules__ = { "uid": fields.Str(), "name": fields.Str(required=True), 'markerId': fields.Int(required=True), "buildingName": fields.Str(required=True), "floorLevel": fields.Int(required=True), 'shapeType': fields.Str(required=False), 'color': fields.Str(required=False), 'width': fields.Float(required=False), 'length': fields.Float(required=False), 'x': fields.Float(required=False), 'y': fields.Float(required=False), } uid = UniqueIdProperty() name = StringProperty(required=True, index=True) markerId = IntegerProperty(required=True, index=True) buildingName = StringProperty(required=True, index=True) floorLevel = IntegerProperty(required=True, index=True) shapeType = StringProperty(required=False) color = StringProperty(required=False) width = FloatProperty(required=False) length = FloatProperty(required=False) x = FloatProperty(required=False) y = FloatProperty(required=False) floor = RelationshipFrom('models.Floor', 'HAS', cardinality=One) def pre_save(self): Floor.nodes.get(buildingName=self.buildingName, level=self.floorLevel) def post_save(self): Floor.nodes.get(buildingName=self.buildingName, level=self.floorLevel).hallways.connect(self)
class EndPoint(Resource): """ The EndPoint class is a flask endpoint resource used when the url path is /suggestions """ get_args = { "q": fields.Str(required=True), "latitude": fields.Float(required=False, validate=validate.Range(min=-90.0, max=90.0)), "longitude": fields.Float(required=False, validate=validate.Range(min=-90.0, max=90.0)), } def __init__(self, db): self.suggestion = Suggestion(db) @use_kwargs(get_args) def get(self, q, latitude=None, longitude=None): """ Return a suggestion of city(ies) depending of the query with a score depending of the match between the suggestion and what's in the database :param q: suggestion name :param latitude: latitude received from the suggestion ( optional ) :param longitude: longitude received from the suggestion ( optional ) :return: json """ logging.info('GET suggestions?q={}&latitude={}&longitude={}'.format( q, latitude, longitude)) return jsonify(self.suggestion.get(q, latitude, longitude))
class RHUpdateRoom(RHRoomAdminBase): @use_args({ 'verbose_name': fields.Str(allow_none=True), 'site': fields.Str(allow_none=True), 'building': fields.String(validate=lambda x: x is not None), 'floor': fields.String(validate=lambda x: x is not None), 'number': fields.String(validate=lambda x: x is not None), 'longitude': fields.Float(allow_none=True), 'latitude': fields.Float(allow_none=True), 'is_reservable': fields.Bool(allow_none=True), 'reservations_need_confirmation': fields.Bool(allow_none=True), 'notification_emails': fields.List(fields.Email()), 'notification_before_days': fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True), 'notification_before_days_weekly': fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True), 'notification_before_days_monthly': fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True), 'notifications_enabled': fields.Bool(), 'end_notification_daily': fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True), 'end_notification_weekly': fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True), 'end_notification_monthly': fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True), 'end_notifications_enabled': fields.Bool(), 'booking_limit_days': fields.Int(validate=lambda x: x >= 1, allow_none=True), 'owner': Principal(validate=lambda x: x is not None, allow_none=True), 'key_location': fields.Str(), 'telephone': fields.Str(), 'capacity': fields.Int(validate=lambda x: x >= 1), 'division': fields.Str(allow_none=True), 'surface_area': fields.Int(validate=lambda x: x >= 0, allow_none=True), 'max_advance_days': fields.Int(validate=lambda x: x >= 1, allow_none=True), 'comments': fields.Str(), }) def _process(self, args): update_room(self.room, args) RHRoomsPermissions._jsonify_user_permissions.clear_cached(session.user) return jsonify(room_update_schema.dump(self.room, many=False))
class GeomagField(Resource): schema_args = { "lat": fields.Float(required=True, validate=lambda dLat: -90 <= dLat <= 180 ), # accepts normalised [-90, 90] or unormalised [0, 180] "lng": fields.Float( required=True, validate=lambda dLng: -180 <= dLng <= 360 ), # accepts normalised [-180, 180] or unormalised [0, 360] "altitude_km": fields.Float(required=True, validate=lambda km: -1 < km <= 850), "yr": fields.Integer(required=True, validate=lambda y: 2020 <= y < 2025), "mth": fields.Integer(required=True, validate=lambda m: 1 <= m <= 12), "day": fields.Integer(required=True, validate=lambda d: 1 <= d < 31), } @use_kwargs(schema_args, location="query") def get(self, lat, lng, altitude_km, yr, mth, day): result = calculate_field(lat, lng, altitude_km, datetime.date(yr, mth, day)) return result
class PowerPlantSchema(Schema): name = fields.Str(required=True) type = fields.Str(required=True, validate=lambda pptype: pptype in ["gasfired", "turbojet", "windturbine"]) efficiency = fields.Float(required=True, validate=lambda eff: eff <= 1) pmin = fields.Float(required=True, validate=lambda pmin: pmin >= 0) pmax = fields.Float(required=True)
class AdderHandler(BaseRequestHandler): """An addition endpoint.""" add_args = {"x": fields.Float(required=True), "y": fields.Float(required=True)} @use_kwargs(add_args) def post(self, x, y): self.write({"result": x + y})
class AdderResource(object): """An addition endpoint.""" adder_args = {"x": fields.Float(required=True), "y": fields.Float(required=True)} @use_kwargs(adder_args) def on_post(self, req, resp, x, y): req.context["result"] = {"result": x + y}
class TrainArgsSchemaPro(Schema): class Meta: unknown = INCLUDE # supports extra parameters batch_size_per_device = fields.Integer( missing=64, description='Batch size for each GPU.', required=False) dataset = fields.Str( missing='synthetic_data', enum=['synthetic_data', 'imagenet', 'imagenet_mini', 'cifar10'], description='Dataset to perform training on. \ synthetic_data: randomly generated ImageNet-like \ images; imagenet_mini: 3% of the real ImageNet \ dataset', required=False) model = fields.Str(missing='resnet50 (ImageNet)', enum=[ 'googlenet (ImageNet)', 'inception3 (ImageNet)', 'mobilenet (ImageNet)', 'overfeat (ImageNet)', 'resnet50 (ImageNet)', 'resnet152 (ImageNet)', 'vgg16 (ImageNet)', 'vgg19 (ImageNet)', 'resnet56 (Cifar10)', 'resnet110 (Cifar10)', 'alexnet (ImageNet, Cifar10)' ], description='CNN model for training. N.B. Models only \ support specific data sets, given in brackets. \ synthetic_data can only be processed by ImageNet models.', required=False) num_gpus = fields.Integer(missing=1, description='Number of GPUs to train on \ (one node only). If set to zero, CPU is used.', required=False) num_epochs = fields.Float(missing=NUM_EPOCHS, description='Number of epochs to \ train on (float value, < 1.0 allowed).', required=False) optimizer = fields.Str(missing='sgd', enum=['sgd', 'momentum', 'rmsprop', 'adam'], description='Optimizer to use.', required=False) use_fp16 = fields.Boolean(missing=False, enum=[False, True], description='Use 16-bit floats for certain \ tensors instead of 32-bit floats. ', required=False) weight_decay = fields.Float(missing=4.0e-5, description='Weight decay factor for training', required=False) evaluation = fields.Boolean(missing=True, enum=[False, True], description='Perform evaluation after the \ benchmark in order to get accuracy results \ (only meaningful on real data sets!).', required=False) if_cleanup = fields.Boolean(missing=False, enum=[False, True], description='If to delete training and \ evaluation directories.', required=False)
class AddResource(Resource): """An addition endpoint.""" add_args = {"x": fields.Float(required=True), "y": fields.Float(required=True)} @use_kwargs(add_args) def post(self, x, y): """An addition endpoint.""" return {"result": x + y}
class TrainArgsSchema(Schema): class Meta: unknown = INCLUDE # support 'full_paths' parameter model_name = fields.Str( required=True, description="Name of the style image e.g. 'name.jpg' in nextcloud. This will also be the name of the model." ) upload_model = fields.Boolean( required=False, missing = 2, description="Upload model to nextcloud." ) epochs = fields.Int( required=False, missing = 2, description="Number of training epochs." ) learning_rate = fields.Float( required=False, missing = 0.003, description="Learning rate." ) batch_size = fields.Int( required=False, missing = 4, description="Batch size for training." ) content_weight = fields.Float( required=False, missing = 1e5, description="Weight for content-loss." ) style_weight = fields.Float( required=False, missing = 1e10, description="Number of iterations on the network to compute the gradients." ) size_train_img = fields.Int( required=False, missing = 256, description="Size of training images, default is 256 X 256" ) log_interval = fields.Int( required=False, missing = 200, description="Number of images after which the training loss is logged." )
class AddFertilizer(Resource): """ Endpoint that is called to add a new fertilizer to the DB """ input_args = { 'fertilizer_name':fields.Str(required=True), 'cost_per_kg':fields.Float(required=True), 'unit_in_kg':fields.Float(required=True), 'n_per_unit':fields.Int(required=True), 'p_per_unit':fields.Int(required=True), 'k_per_unit':fields.Int(required=True), 's_per_unit':fields.Int(), } @use_args(input_args) def __init__(self,args): ###################### Inputs from API ###################### self.fertilizer_name = args["fertilizer_name"]; self.cost_per_kg = args["cost_per_kg"]; self.unit_in_kg = args["unit_in_kg"] self.n_per_unit = args["n_per_unit"] self.p_per_unit = args["p_per_unit"] self.k_per_unit = args["k_per_unit"] self.s_per_unit = args["s_per_unit"] ############################################################# self.bag_cost = 0 self.input_list = [] def post(self): # Insert a new fertilizer into the fertilizer_ref_tbl self.bag_cost = self.cost_per_kg * self.unit_in_kg; if (self.s_per_unit is None): self.s_per_unit = 0 self.input_list = [self.fertilizer_name, self.cost_per_kg, self.unit_in_kg,self.bag_cost, self.n_per_unit,self.p_per_unit,self.k_per_unit,self.s_per_unit] input_parm = tuple(self.input_list) sql = insert_fertilizer.insert_fertilizer_ref_tbl message = DatabaseConnection().insert_table_detail(sql,input_parm) return message
class PowerPlantLoadSchema(Schema): load = fields.Float(validate=lambda load: load >= 0) fuels = fields.Dict(fields.String( validate=lambda fuel_name: fuel_name in ["gas(euro/MWh)", "kerosine(euro/MWh)", "co2(euro/ton)", "wind(%)"]), fields.Float(), required=True, validate=validate.Length(min=1)) powerplants = fields.List(fields.Nested(PowerPlantSchema), required=True, validate=validate.Length(min=1))
class PriceSchema(ma.ModelSchema): class ProductSchema(ma.ModelSchema): class ProductTagSchema(ma.ModelSchema): name = fields.String() @post_dump def flatten(self, data): return data['name'] productId = fields.Int(attribute="id") productName = fields.String(attribute="name") productTags = fields.Nested(ProductTagSchema, many=True, attribute='tags') class ShopSchema(ma.ModelSchema): class ShopTagSchema(ma.ModelSchema): name = fields.String() @post_dump def flatten(self, data): return data['name'] shopId = fields.Int(attribute='id') shopName = fields.Str(attribute='name') shopTags = fields.Nested(ShopTagSchema, many=True, attribute='tags') shopAddress = fields.Str(attribute='address') price = fields.Float() date = fields.Date() product = fields.Nested(ProductSchema) shop = fields.Nested(ShopSchema) shopDist = fields.Float(attribute='dist') @pre_dump def handle_tuple(self, data): # if with_geo: query result = list of tuple(product, distance) if not isinstance(data, tuple): return data data[0].dist = data[1] return data[0] @post_dump def refactor(self, data): # flatten shop, product entries of data dict t_shop = data['shop'] t_prod = data['product'] del data['shop'] del data['product'] data.update(t_shop) data.update(t_prod) return data
class AdderResource(object): """An addition endpoint.""" adder_args = { 'x': fields.Float(required=True), 'y': fields.Float(required=True), } @use_kwargs(adder_args) def on_post(self, req, resp, x, y): req.context['result'] = {'result': x + y}
class AddResource(Resource): """An addition endpoint.""" add_args = { 'x': fields.Float(required=True), 'y': fields.Float(required=True), } @use_kwargs(add_args) def post(self, x, y): """An addition endpoint.""" return {'result': x + y}
class ShopSchema(ma.ModelSchema): tags = fields.Nested(ShopTagSchema, many=True) lng = fields.Float() lat = fields.Float() class Meta: model = Shop fields = ('id', 'name', 'tags', 'lat', 'lng', 'address', 'withdrawn') @pre_dump def position_to_xy(self, data): point = to_shape(data.position) data.lng, data.lat = point.x, point.y return data
class Distance(Resource): coordinates = { 'x1': fields.Float(missing=0.0), 'y1': fields.Float(missing=0.0), 'x2': fields.Float(missing=0.0), 'y2': fields.Float(missing=0.0) } @use_args(coordinates) def get(self, args): distance = engine.get_distance(args['x1'], args['y1'], args['x2'], args['y2']) return {"distance": distance}
class BrewPiTemp(MethodResource): """ Read/Write temperature on the BrewPi """ def get(self): return transport.get_temperatures() @use_kwargs({'fridge': fields.Float()}) @use_kwargs({'beer': fields.Float()}) def post(self, beer=None, fridge=None): if beer: return transport.set_beer_setpoint(beer) elif fridge: return transport.set_fridge_setpoint(fridge)
def switch(case): return { int: wf.Int(missing=None), float: wf.Float(missing=None), bool: wf.Bool(missing=None), list: wf.DelimitedList(wf.Str(), delimiter=',', missing=[]), }.get(case)
class BestRegions(MethodResource): @use_kwargs( { "min_total": fields.Int(missing=10), "min_rating": fields.Float(missing=4.0) }, locations=["json"], ) def post(self, min_total: int, min_rating: float) -> Tuple[Dict, int]: """Get regions with percentage of wines with good rating """ answer = {} response = get_products_with() wines = (pd.DataFrame(response).replace(["", 0], np.nan).dropna( subset=["aggregateRating-ratingValue", "origins-origin-region"])) regions = pd.DataFrame( wines["origins-origin-region"].value_counts()).sort_index() regions.rename(columns={"origins-origin-region": "total"}, inplace=True) regions_group = wines.groupby( "origins-origin-region")["aggregateRating-ratingValue"] regions["top_wines_percentage"] = regions_group.apply( lambda x: len(x[x >= min_rating]) / len(x) * 100).round() regions = regions.sort_values(["top_wines_percentage", "total"], ascending=False) answer["results"] = regions[regions["total"] > min_total].to_dict( "index") return answer, 200
def filter_value_type_to_request_arg_type(name, value_type, allow_multiple, load_from=None): if value_type == str: arg_type = fields.Str(load_from=load_from or name, location='query') elif value_type == float: arg_type = fields.Float(load_from=load_from or name, location='query') elif value_type == int: arg_type = fields.Int(load_from=load_from or name, location='query') elif value_type == datetime: arg_type = fields.DateTime(load_from=load_from or name, location='query') else: raise Exception( "Unsupported value type '{}' for a request argument".format( value_type)) if allow_multiple: arg_type = fields.DelimitedList(arg_type, load_from=load_from or name, location='query') return arg_type
class Meta: model = models.Album column_overrides = { 'sales': { 'field': fields.Float() }, }
class LegHeightResource(Resource): add_args = {"height": fields.Float(required=True)} @use_kwargs(add_args) def put(self, leg_id, height): GlobalContext.getRobot().getController().setSingleLegHeight(leg_id, height) return "OK"
class ProgressResponseSchema(Schema): status = fields.Str() status_display = fields.Str() completed = fields.Float() current_file_size = fields.Int() total_file_size = fields.Int() episode = fields.Nested(ProgressEpisodeSchema) podcast = fields.Nested(ProgressPodcastSchema)
class PredictArgsSchema(Schema): class Meta: unknown = INCLUDE # support 'full_paths' parameter # full list of fields: https://marshmallow.readthedocs.io/en/stable/api_reference.html # to be able to upload a file for prediction img_content = fields.Field(required=False, missing=None, type="file", data_key="image_content", location="form", description="Image to be styled.") img_style = fields.Field(required=False, missing=None, type="file", data_key="image_style", location="form", description="Image with the style.") style = fields.Str( required=False, # force the user to define the value enum=[ "The Starry Night - Van Gogh", "Mosaic Lady", "Seated Nude - Picasso", "The Great Wave off Kanagawa - Hokusai" ], # list of choices description= "Selection of the image which style we want to transfer. Select one if you don't have any." # help string ) num_steps = fields.Int( required=False, missing=300, description= "Number of iterations on the network to compute the gradients.") style_weight = fields.Int( required=False, missing=1000000, description= "Weigth of the image of the style. It represents the emphasis on style in the image. There is a tradeoff between style weight and content weight." ) content_weight = fields.Float( required=False, missing=1, description= "Weigth of the image of the content. It represents the emphasis on content in the image. There is a tradeoff between style weight and content weight" ) accept = fields.Str( require=False, description= "Returns the image with the new style or a pdf containing the 3 images.", missing='image/png', validate=validate.OneOf(['image/png', 'application/pdf']))
class AdminDeliveryConfigPickView(AdminBaseView): """后台-订单-自提设置""" # 参数校验 def validate_time(self): try: datetime.datetime.strptime(self, "%H:%M") except Exception: return False return True @use_args( { "pick_service_amount": fields.Float(required=True, comment="自提模式服务费"), "pick_minimum_free_amount": fields.Float( required=True, comment="自提模式免服务费最小金额" ), "pick_today_on": fields.Boolean(required=True, comment="今天自提是否开启"), "pick_tomorrow_on": fields.Boolean(required=True, comment="明天自提是否开启"), "pick_periods": fields.Nested( { "from_time": fields.String( required=True, comment="自提起始时间", validate=validate_time ), "to_time": fields.String( required=True, comment="自提终止时间", validate=validate_time ), }, many=True, validate=[validate.Length(1)], unknown=True, comment="自提时段", ), }, location="json" ) def put(self, request, args): success, msg = update_delivery_config( self.current_shop.id, args, self.current_user.id ) if not success: return self.send_fail(error_text=msg) return self.send_success()
class Waypoint(StructuredNode, Node): """Waypoint model""" __validation_rules__ = { "uid": fields.Str(), "name": fields.Str(required=True), 'markerId': fields.Int(required=True), "buildingName": fields.Str(required=True), "floorLevel": fields.Int(required=True), 'shapeType': fields.Str(required=False), 'color': fields.Str(required=False), 'width': fields.Float(required=False), 'length': fields.Float(required=False), 'x': fields.Float(required=False), 'y': fields.Float(required=False), } uid = UniqueIdProperty() name = StringProperty(required=True, index=True) markerId = IntegerProperty(required=True, index=True) buildingName = StringProperty(required=True, index=True) floorLevel = IntegerProperty(required=True, index=True) shapeType = StringProperty(required=False) color = StringProperty(required=False) width = FloatProperty(required=False) length = FloatProperty(required=False) x = FloatProperty(required=False) y = FloatProperty(required=False) floor = RelationshipFrom('models.Floor', 'HAS', cardinality=One) building_unique_waypoint = StringProperty(required=True, unique_index=True) building_unique_marker = StringProperty(required=True, unique_index=True) neighbors = RelationshipTo('Waypoint', 'GOES_TO', cardinality=ZeroOrMore, model=GoesTo) def pre_save(self): Floor.nodes.get(buildingName=self.buildingName, level=self.floorLevel) self.building_unique_waypoint = f'building_{self.buildingName}_waypoint_name_{self.name}' self.building_unique_marker = f'building_{self.buildingName}_marker_id_{self.markerId}' def post_save(self): Floor.nodes.get(buildingName=self.buildingName, level=self.floorLevel).waypoints.connect(self)
class RobotStretchResource(Resource): add_args = {"stretch": fields.Float(required=True)} def get(self): return GlobalContext.getRobot().getController().getLegStretch() @use_kwargs(add_args) def put(self, stretch): GlobalContext.getRobot().getController().setLegStretch(stretch) GlobalContext.getRobot().getController().robotStop() return "Current stretch:" + str(GlobalContext.getRobot().getController().getLegStretch())