class PatchServicesSchema(Schema): """ Request body PATCH /services """ title = fields.Str(allow_none=True) description = fields.Str(allow_none=True) process_graph = fields.Dict(allow_none=True) enabled = fields.Bool(allow_none=True) parameters = fields.Dict(allow_none=True) plan = fields.Str(allow_none=True) budget = fields.Number(allow_none=True) @validates("process_graph") def validate_process_graph(self, graph): validate_graph_with_known_processes(graph)
class ClusterSchema(Schema): id = fields.Str() name = fields.String() duration = fields.Number() network_type = fields.String() mapped_ports = fields.Dict() service_url = fields.Dict() # containers = fields.Dict() size = fields.Integer() release_ts = fields.DateTime() health = fields.String() create_ts = fields.DateTime() apply_ts = fields.DateTime() worker_api = fields.String() status = fields.String() state = fields.String() host = fields.Method("get_host_name") host_id = fields.Method("get_host_id") user_id = fields.String() api_url = fields.String() consensus_plugin = fields.String() containers = fields.Method("get_containers") service_ports = fields.Method("get_service_ports") config = fields.Dict() def get_host_name(self, cluster): return cluster.host.name def get_host_id(self, cluster): return str(cluster.host.id) def format_create_ts(self, cluster): return cluster.create_ts.strftime("%a, %d %b %Y %H:%M:%S") def format_apply_ts(self, cluster): return cluster.apply_ts.strftime("%a, %d %b %Y %H:%M:%S") def get_containers(self, cluster): return [ container.name for container in Container.objects(cluster=cluster) ] def get_service_ports(self, cluster): return [ service_port.port for service_port in ServicePort.objects( cluster=cluster).order_by('port') ]
class LightAppMenu(Resource): @use_kwargs({ "name": fields.String(required=True), "application_id": fields.String(required=True), "type": fields.Number(required=True), "icon": fields.String(required=False), "link": fields.String(required=False), "page_key": fields.String(required=False), "parent_id": fields.String(required=False), "page_id": fields.String(required=False), }) def post(self, **kwargs): print("menu post") app_id = kwargs.get('application_id') app = db.session.query(Application).filter(Application.id == app_id).first() if not app: return json_response(message="找不到应用", status=404) """添加应用菜单 --- tags: - 轻应用 parameters: - name: id in: body type: number required: true """ menu = ApplicationMenus( name=kwargs.get('name'), application_id=app_id, icon=kwargs.get('icon'), link=kwargs.get('link'), type=ApplicationMenus.string_to_page_type(kwargs.get('type')), platform=kwargs.get('platform', 'pc, mobile'), sort=kwargs.get('sort', 0), parent_id=kwargs.get('parent_id'), page_key=kwargs.get('page_key'), page_id=kwargs.get('page_id') ) db.session.add(menu) db.session.commit() return json_response(message="添加成功", data={ "id": menu.id })
class ComputeOptionSchema(Schema): class Meta: unknown = EXCLUDE expression = fields.String( description='Mathematical expression to execute.', example='(v1 - v2) / (v1 + v2)', required=True) stretch_range = fields.List( fields.Number(allow_none=True), validate=validate.Length(equal=2), example='[0,1]', description='Stretch range to use as JSON array.', required=True) colormap = fields.String( description='Colormap to apply to image (see /colormap).', validate=validate.OneOf(('explicit', *AVAILABLE_CMAPS)), missing=None) tile_size = fields.List( fields.Integer(), validate=validate.Length(equal=2), example='[256,256]', description='Pixel dimensions of the returned PNG image as JSON list.') v1 = _operator_field(1) v2 = _operator_field(2) v3 = _operator_field(3) v4 = _operator_field(4) v5 = _operator_field(5) @pre_load def decode_json(self, data: Mapping[str, Any], **kwargs: Any) -> Dict[str, Any]: data = dict(data.items()) for var in ('stretch_range', 'tile_size'): val = data.get(var) if val: try: data[var] = json.loads(val) except json.decoder.JSONDecodeError as exc: msg = f'Could not decode value {val} for {var} as JSON' raise ValidationError(msg) from exc return data
class TransactionSchema(Schema): id = fields.Number() title = fields.Str() bitfinex_channel = fields.Number() bitfinex_id = fields.Number() bitfinex_currency = fields.Str() bitfinex_timestamp = fields.Number() bitfinex_price = fields.Number() bitfinex_amount = fields.Number() created_at = fields.DateTime() updated_at = fields.DateTime()
class ImporterTaskLogV1(Schema): """Importer task log schema.""" id = fields.Integer() status = fields.String(dump_only=True) start_time = fields.DateTime(dump_only=True) end_time = fields.DateTime(dump_only=True) original_filename = fields.String(dump_only=True) provider = fields.String(dump_only=True) mode = fields.String(dump_only=True) source_type = fields.String(dump_only=True) entries_count = fields.Number(dump_only=True) class Meta: """Meta attributes for the schema.""" unknown = EXCLUDE
class VideoSchema(StrictKeysSchema): """Video schema.""" _access = fields.Nested(AccessSchema) _buckets = fields.Nested(BucketSchema) _cds = fields.Nested(_CDSSSchema, required=True) _deposit = fields.Nested(VideoDepositSchema, required=True) _oai = fields.Nested(OaiSchema) _project_id = fields.Str() accelerator_experiment = fields.Nested(AcceleratorExperimentSchema) agency_code = fields.Str() category = fields.Str() contributors = fields.Nested(ContributorSchema, many=True, required=True) copyright = fields.Nested(CopyrightSchema) date = DateString(required=True) description = fields.Str(required=True) doi = DOI() duration = fields.Str() external_system_identifiers = fields.Nested(ExternalSystemIdentifiersField, many=True) featured = fields.Boolean() internal_note = fields.Str() keywords = fields.Nested(KeywordsSchema, many=True) language = fields.Str() license = fields.Nested(LicenseSchema, many=True) note = fields.Str() publication_date = fields.Str() recid = fields.Number() related_links = fields.Nested(RelatedLinksSchema, many=True) report_number = fields.List(fields.Str, many=True) schema = fields.Str(attribute="$schema", dump_to='$schema') title = fields.Nested(TitleSchema, required=True) translations = fields.Nested(TranslationsSchema, many=True) type = fields.Str() vr = fields.Boolean() # Preservation fields location = fields.Str() original_source = fields.Str() physical_medium = fields.Nested(PhysicalMediumSchema, many=True) @post_load(pass_many=False) def post_load(self, data): """Post load.""" data['$schema'] = current_jsonschemas.path_to_url(Video._schema) return data
class LogSchema(Schema): """LogSchema.""" class Meta: """Meta attributes for class.""" unkown = EXCLUDE _id = fields.Str() username = fields.Str() is_admin = fields.Bool() status_code = fields.Number() path = fields.Str() method = fields.Str() args = fields.Dict() json = fields.Field(allow_none=True) created = DateTimeField() error = fields.Str()
class ScenarioSchema(ModelSchema): # class Meta(ModelSchema.Meta): # model = Scenario # sqla_session = db.session ID = fields.Number(dump_only=True) NAME = fields.String(required=True) DESCRIPTION = fields.String(required=True) LAST_UPDATED_DATE = fields.String(dump_only=True) LAST_UPDATED_BY = fields.String(dump_only=True) PROJECT = fields.String(dump_only=True) TYPE = fields.String(dump_only=True) STATUS = fields.String(dump_only=True) APPROVED = fields.String(dump_only=True) APPROVED_DATE = fields.String(dump_only=True) CONDITIONS = fields.String(dump_only=True) LAST_UPDATED_BY_NAME = fields.String(dump_only=True)
class UserSchema(Schema): id = fields.Number(dump_only=True) username = fields.String(dump_only=True) email = fields.Email(required=True) password = fields.Str(required=True, load_only=True) full_name = fields.Str(required=True) date_of_birth = fields.Date() created_at = fields.DateTime(dump_only=True) modified_at = fields.DateTime(dump_only=True) phone_number = fields.String() password_salt = fields.String(required=True) admin_level = fields.String(dump_only=True)
class ChartDataPivotOptionsSchema(ChartDataPostProcessingOperationOptionsSchema ): """ Pivot operation config. """ index = (fields.List( fields.String( allow_none=False, description="Columns to group by on the table index (=rows)", ), minLength=1, required=True, ), ) columns = fields.List( fields.String( allow_none=False, description="Columns to group by on the table columns", ), minLength=1, required=True, ) metric_fill_value = fields.Number( required=False, description= "Value to replace missing values with in aggregate calculations.", ) column_fill_value = fields.String( required=False, description="Value to replace missing pivot columns names with.") drop_missing_columns = fields.Boolean( description="Do not include columns whose entries are all missing " "(default: `true`).", required=False, ) marginal_distributions = fields.Boolean( description="Add totals for row/column. (default: `false`)", required=False, ) marginal_distribution_name = fields.String( description= "Name of marginal distribution row/column. (default: `All`)", required=False, ) aggregates = ChartDataAggregateConfigField()
class EntityDataResource(Resource): @user_required @use_kwargs({ 'type': fields.Number(), 'search_params': fields.List(fields.Dict()), 'page_params': fields.List(fields.Dict()), 'order_params': fields.List(fields.Dict()) }) def post(self, id, **kwargs): """修改业数据回显选项列表 --- tags: - page页面数据 parameters: - name: search_params in: data type: List required: false description: 列表搜索条件 - name: page_params in: data type: List required: false description: 分页条件 - name: order_params in: data type: List required: false description: 排序条件 responses: 200: description: 成功 examples: response: {"data": {"entity_data": [], "entity_fields": []}} """ entity = Entity.query.filter(Entity.id == id).first() if not entity: return json_response(message="未找到对应的entity", status=404) # try: entity_schema = EntitySchema(data_type=kwargs.get("data_type", 9)) data = entity_schema.dump(entity).data # except Exception as e: # _ = e # return json_response(message=str(e), status=403) return json_response(data=data)
class StateSchema(Schema): message_id = fields.Str() status = fields.Str(allow_none=True) actor_name = fields.Str(allow_none=True) args = fields.List(fields.Raw(), allow_none=True) kwargs = fields.Dict(keys=fields.Str(), values=fields.Raw(), allow_none=True) options = fields.Dict(keys=fields.Str(), values=fields.Raw(), allow_none=True) progress = fields.Number(allow_none=True) priority = fields.Int(allow_none=True) enqueued_datetime = fields.Str(allow_none=True) started_datetime = fields.Str(allow_none=True) end_datetime = fields.Str(allow_none=True) queue_name = fields.Str(allow_none=True) composition_id = fields.Str(allow_none=True)
class BillDetailSchema(Schema): call_start_date = fields.Date() call_start_time = fields.Time() duration = fields.String() destination = fields.String() price = fields.Number() @pre_dump def adjust_data(self, original): interval = (original.end_timestamp - original.start_timestamp) duration = get_duration(interval) return { 'call_start_date': original.start_timestamp.date(), 'call_start_time': original.start_timestamp.time(), 'duration': '{}h{}min{}s'.format(*duration), 'destination': original.destination, 'price': original.price }
class ChangeCitizenSchema(Schema): town = fields.Str(validate=validateStringFileds) street = fields.Str(validate=validateStringFileds) building = fields.Str(validate=validateStringFileds) apartment = fields.Number(strict=True, validate=isPositiveNumber) name=fields.Str(validate=validateName) gender=fields.Str(validate=OneOf(['male','female'])) birth_date=fields.DateTime(strict=True, format='%d.%m.%Y',validate=isPastDate) relatives=fields.List(fields.Integer()) class Meta: strict = True unknown = RAISE @validates_schema def validate_notnull(self, data, **kwargs): if data == {}: raise ValidationError('Data should contains more then 0 fields')
class SubmissionSchema(Schema): id = fields.Integer() salary = fields.Number(required=True) email = fields.Email(required=True) years_experience = fields.Integer(required=True) number_of_employers = fields.Integer() years_with_current_employer = fields.Integer() verified = fields.Boolean() perks = fields.Nested('PerkSchema', many=True) submission_to_perks = fields.Nested('SubmissionToPerkSchema', exclude=('submission_id', 'perk_id'), many=True) employment_type = fields.Nested('EmploymentTypeSchema') location = fields.Nested('LocationSchema') roles = fields.Nested('RoleSchema', exclude=('id', 'listed'), many=True) education = fields.Nested('EducationSchema', exclude=('id', )) techs = fields.Nested('TechSchema', exclude=('id', 'listed'), many=True) verification_request = fields.Nested('VerificationRequestSchema', exclude=('id', )) created_at = fields.DateTime() @post_load def make_model(self, data, **kwargs): if 'instance' in data: model = data['instance'] else: model = Submission() dump_dict_values(model, data) return model @validates_schema(skip_on_field_errors=True) def validate_object(self, data, **kwargs): if not ('years_with_current_employer' in data and 'years_experience') in data: return if not data['years_with_current_employer'] <= data['years_experience']: raise ValidationError({ 'years_with_current_employer': 'Years with current employer must be <= total years of experience', 'years_experience': 'years_with_current_employer' })
class DeadLetterSchema(Schema): id = fields.Number() created_at = fields.DateTime() topic = fields.Str() partition = fields.Number() offset = fields.Number() timestamp = fields.Number() key = fields.Str() value = fields.Str() decoded_value = fields.Str() headers = fields.Str() checksum = fields.Str() serialized_key_size = fields.Number() serialized_value_size = fields.Number() serialized_header_size = fields.Number() log = fields.Str() schema = fields.Str()
class JobRunSchema(Schema): id = fields.Integer() name = fields.Str() scheduled_at = fields.DateTime() rejected_at = fields.DateTime() failed_at = fields.DateTime() cancelled_at = fields.DateTime() run_at = fields.DateTime() finished_at = fields.DateTime() parallelization = fields.Number() status = fields.Str() job_template = fields.Nested(JobTemplateSchema()) job_template_name = fields.Method("set_template_name", dump_only=True) all_connected_logs = fields.Nested(LogSchema(), many=True) HIDDEN_FROM_LIST=["all_connected_logs"] def set_template_name(self, jr): return jr.job_template.name
class ExperimentSchema(Schema): id = fields.Str() name = fields.Str() description = fields.Str() created = fields.DateTime() state = fields.Str(allow_none=True) duration = fields.Number(allow_none=True) log_id = fields.Str(load_from="logId") canvas = fields.Dict(load_only=True) task_instances = fields.List(fields.Str(), dump_only=True) instance_type = fields.Str(load_from="instanceType", allow_none=True) service_url = fields.Str(load_from="serviceUrl", allow_none=True) tensorboard_url = fields.Str(load_from="tensorboardUrl", allow_none=True) output_id = fields.Str(load_from="instanceOutputId", allow_none=True) timeout_seconds = fields.Integer(allow_none=True) @post_load def make_experiment(self, data): return Experiment(**data)
class VideoSchema(SQLAlchemySchema): """ video schema """ class Meta: """ meta class """ model = Video sqla_session = db.session load_instance = True id = fields.Number(dump_only=True) title = fields.String(required=True) video_files = sqlma_fields.Nested(VideoFileSchema, many=True, exclude=("id", "created")) image_files = sqlma_fields.Nested(ImageFileSchema, many=True, exclude=("id", "created")) created_at = fields.DateTime(dump_only=True) description = fields.String(required=True)
class ValuationIndicatorsSchema(Schema): assetId = fields.Number(attribute='asset_id') assetSymbol = fields.String(attribute='asset_symbol') searchDate = fields.DateTime(attribute='search_date') dividendYield = fields.Float(attribute='dividend_yield') priceEarnings = fields.Float(attribute='price_earnings') pegRatio = fields.Float(attribute='peg_ratio') priceBookValue = fields.Float(attribute='price_book_value') evEbitda = fields.Float(attribute='ev_ebitda') evEbit = fields.Float(attribute='ev_ebit') priceEbitda = fields.Float(attribute='price_ebitda') priceEbit = fields.Float(attribute='price_ebit') bookValueShare = fields.Float(attribute='book_value_share') priceAsset = fields.Float(attribute='price_asset') earningsShare = fields.Float(attribute='earnings_share') pricesSalesRatio = fields.Float(attribute='prices_sales_ratio') pricesWorkingCapital = fields.Float(attribute='prices_working_capital') priceNetCurrentAssets = fields.Float(attribute='price_net_current_assets')
class ModelOutputConfigurationSchema(Schema): output_name = fields.String(required=True) is_softmax = fields.Boolean(required=False) value_multiplier = fields.Float(required=False) value_index_mapping = fields.Dict(keys=fields.String(), values=fields.Integer(), required=False) classes = fields.Dict(keys=fields.String(), values=fields.Number(), required=False) confidence_threshold = fields.Float(required=False, validate=validate.Range(min=0, max=1)) top_k_results = fields.Integer(required=False, validate=validate.Range( min=0, min_inclusive=False)) @post_load def make_model_output_configuration(self, data, **kwargs): return ModelOutputConfiguration(**data)
class EventSchema(ModelSchema): class Meta(ModelSchema.Meta): model = Event sql_session = db.session id = fields.Number(dump_only=True) name = fields.String() day = fields.Number() start = fields.Time() lesson_id = fields.Number() classroom_id = fields.Number() teacher_id = fields.Number() group_id = fields.Number() length = fields.Time()
class Data_tweetSchema(Schema): conversation_id = fields.Number() created_at = fields.Number() date = fields.Date() time = fields.Time() timezone = fields.Str() user_id = fields.Number() username = fields.Str() name = fields.Str() place = fields.Str() tweet = fields.Str() replies_count = fields.Number() retweets_count = fields.Number() likes_count = fields.Number() link = fields.Str() retweet = fields.Str() quote_url = fields.Str() video = fields.Number()
class SaborTamanhoSchema(Schema): """ Classe filho tamanho Possui métodos para tradução de id/hash_id na serialização/deserialização A api não deve nunca retornar o id que consta no banco de dados """ hash_id = fields.String(attribute="tamanho_id") valor = fields.Number() @post_load def make_sabor_tamanho(self, data): """ No pós deserialização objeto SaborTamanho é composto onde atributo 'tamanho' recebe objeto Tamanho referente ao hash_id e valor de 'tamanho_id' é alterado de hash_id para id :param data: dados do objeto a ser deserializado :return: instância de SaborTamanho """ t = Tamanho.by_hash_id(self.context['user'].empresa_id, data['tamanho_id']) data['tamanho'] = t data['tamanho_id'] = t.id return SaborTamanho(**data) @post_dump(pass_many=True) def encode_id(self, data, many): """ No pós serialização id é codificado para hash_id :param data: dados do objeto a ser serializadp :param many: true/false indica se objeto é uma lista :return: dados com id codificado """ for d in data: encoded_id = generate_hash( 'tamanhos', [self.context['user'].empresa_id, int(d['hash_id'])]) d['hash_id'] = encoded_id return data
class ProjectSchema(StrictKeysSchema): """Project schema.""" _access = fields.Nested(AccessSchema) _buckets = fields.Nested(BucketSchema) _deposit = fields.Nested(ProjectDepositSchema) _oai = fields.Nested(OaiSchema) contributors = fields.Nested(ContributorSchema, many=True) creator = fields.Nested(CreatorSchema) date = fields.Str() description = fields.Nested(DescriptionSchema) description_translations = fields.Nested(DescriptionTranslationSchema, many=True) keywords = fields.Nested(KeywordsSchema, many=True) license = fields.Str() recid = fields.Number() schema = fields.Str(attribute='$schema') title = fields.Nested(TitleSchema) title_translations = fields.Nested(TitleTranslationSchema, many=True) videos = fields.Nested(ProjectVideoSchema, many=True)
class UserSchema(Schema): id = fields.Number() name = fields.String() email = fields.Str() creationDate = fields.DateTime('%Y-%m-%d') role = fields.Nested(RoleSchema) # is_enabled = fields.Boolean() # Define UserAuth DataModel. Make sure to add flask_user UserMixin!! # class UserAuth(Base, UserMixin): # id = Column(Integer, primary_key=True) # user_id = Column(Integer(), ForeignKey('user.id', ondelete='CASCADE')) # # # User authentication information # username = Column(String(50), nullable=False, unique=True) # password = Column(String(255), nullable=False, default='') # # # Relationships # user = relationship('User', uselist=False, foreign_keys=user_id)
class PatientSchema(Schema): id = fields.Number() enterprise_id = fields.Str() member_records = fields.List( fields.Nested(PatientMemberRecordSchema, dump_only=True)) created_date = fields.DateTime() created_by = fields.Str() last_modified_date = fields.DateTime() last_modified_by = fields.Str() def populate_schema(self, id, enterprise_id, member_records, created_by, created_date, last_modified_by, last_modified_date): self.id = id self.enterprise_id = enterprise_id self.member_records = member_records self.created_by = created_by self.created_date = created_date self.last_modified_by = last_modified_by self.last_modified_date = last_modified_date return self
class OrderCreateSchema(ModelSchema): order_number = fields.Str(required=True) trad_no = fields.Str(required=False, default='') invoice_titile = fields.Str(required=False, default='') invoice_company = fields.Str(required=False, default='') invoice_content = fields.Str(required=False, default='') consignee_address = fields.Str(required=False, default='') order_price = fields.Number(required=True, default=0.0) pay_status = fields.Str(required=False, default='未支付') is_send = fields.Boolean(required=False, default=False) user_id = fields.Int(required=True) goods = fields.List(fields.Dict(), required=True) class Meta(OrderSchema.Meta): model = Order strict = True fields = ('id', 'created_at', 'updated_at', 'order_number', 'trad_no', 'invoice_titile', 'invoice_company', 'invoice_content', 'is_send', 'user_id', 'goods', 'consignee_address', 'order_price', 'pay_status')
class BusinessSchema(Schema): id = fields.Number(dump_only=True) business_name = fields.Str(required=True) owner_full_name = fields.Str(required=True) email = fields.Email(required=True) password = fields.Str(required=True, load_only=True) created_at = fields.DateTime(dump_only=True) modified_at = fields.DateTime(dump_only=True) phone_number = fields.String() password_salt = fields.String(required=True) password_reset_code = fields.String(dump_only=True) password_reset_timeout = fields.DateTime(dump_only=True) description = fields.Str()