Ejemplo n.º 1
0
class AdminCustomersView(AdminBaseView):
    """后台-客户-客户列表"""
    pagination_class = StandardResultsSetPagination

    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_CUSTOMER])
    @use_args(
        {
            "sort_prop":
            fields.String(
                required=False,
                missing="",
                validate=[
                    validate.OneOf(["", "consume_amount", "consume_count"])
                ],
                comment="排序字段",
            ),
            "sort":
            fields.Function(
                deserialize=lambda x: x.rstrip("ending"),
                required=False,
                missing="",
                validate=[validate.OneOf(["", "asc", "desc"])],
                comment="排序方式, +:正序,-:倒序",
            ),
            "keyword":
            fields.String(required=False, missing="", comment="搜索关键字,昵称或者手机号"),
        },
        location="query")
    def get(self, request, args):
        shop = self.current_shop
        customer_list = list_customer_by_shop_id(shop.id, **args)
        customer_list = self._get_paginated_data(customer_list,
                                                 AdminCustomerSerializer)
        return self.send_success(data_list=customer_list)
Ejemplo n.º 2
0
 def get_predict_args(self):
     return {
         "data":
         fields.Field(
             description="Data file to perform inference.",
             required=True,
             location="form",
             type="file",
         ),
         "parameter":
         fields.Int(description="This is a parameter for prediction",
                    required=True),
         "parameter_three":
         fields.Str(
             description=("This is a parameter that forces its value to "
                          "be one of the choices declared in 'enum'"),
             enum=["foo", "bar"],
             validate=validate.OneOf(["foo", "bar"]),
         ),
         "accept":
         fields.Str(
             description=("Media type(s) that is/are acceptable for the "
                          "response."),
             validate=validate.OneOf(["text/plain", "image/png"]),
             location="headers",
         )
     }
Ejemplo n.º 3
0
class UserActionSchema(BaseSchema):
    name = fields.String(required=True)
    # All the fields below are not needed for logout/modification so are not required=True
    password = fields.String(missing=None)
    sync_approval = fields.String(
        missing='unknown',
        validate=validate.OneOf(choices=('unknown', 'yes', 'no')),
    )
    action = fields.String(
        validate=validate.OneOf(choices=('login', 'logout')),
        missing=None,
    )
    premium_api_key = fields.String(missing='')
    premium_api_secret = fields.String(missing='')

    @validates_schema
    def validate_user_action_schema(self, data, **kwargs):
        if data['action'] == 'login':
            if data['password'] is None:
                raise ValidationError('Missing password field for login')
        elif data['action'] is None:
            if data['premium_api_key'] == '' or data['premium_api_secret'] == '':
                raise ValidationError(
                    'Without an action premium api key and secret must be provided',
                )

    class Meta:
        strict = True
        # decoding to a dict is required by the @use_kwargs decorator from webargs
        decoding_class = dict
Ejemplo n.º 4
0
class CommunityRequestsResource(MethodView):
    """Resource to list community membership requests."""

    post_args = {
        'response':
        fields.Raw(location='json',
                   required=True,
                   validate=[validate.OneOf(['accept', 'decline'])]),
        'role':
        fields.Raw(location='json',
                   required=False,
                   validate=[validate.OneOf(['M', 'A', 'C'])])
    }

    @pass_community
    def get(self,
            comid=None,
            community=None,
            outgoing_only=False,
            incoming_only=False,
            page_size=20,
            page=0):
        """List all the community membership requests."""
        admin_ids = \
            [admin.user.id for admin in CommunityMember.get_admins(
                community.id)]
        if int(current_user.get_id()) not in admin_ids:
            abort(404)
        response_object = {}
        if not outgoing_only:
            count, requests = \
                MembershipRequestAPI.get_community_incoming_requests(
                    community.id, page_size=page_size)
            response_object['inc_count'] = count
            response_object['inc_requests'] = []
            for req in requests:
                response_object['inc_requests'].append({
                    'email': req.email,
                    'req_id': req.id
                })
        if not incoming_only:
            count, requests = \
                MembershipRequestAPI.get_community_outgoing_requests(
                    community.id, page_size=page_size)
            response_object['out_count'] = count
            response_object['out_requests'] = []
            for req in requests:
                response_object['out_requests'].append({
                    'email':
                    req.email,
                    'req_id':
                    req.id,
                    'role':
                    str(req.role.title)
                })
        return jsonify(response_object), 200
Ejemplo n.º 5
0
class FilterUsersSchema(FilterSchema):
    sort_by = fields.Str(
        validate=sort_one_of([
            'id', 'name', 'email', 'role', 'status',
            'publisher_id', 'created_at', 'updated_at',
        ]),
        missing='-created_at'
    )
    query = fields.Str(validate=Length(min=3, max=100), missing=None)
    role = fields.Str(validate=validate.OneOf([r[0] for r in ROLES]), missing=None)
    status = fields.Str(validate=validate.OneOf([s[0] for s in STATUSES]), missing=None)
Ejemplo n.º 6
0
class SuperShopVerifyView(UserBaseView):
    """总后台-修改店铺认证状态"""
    @use_args(
        {
            "sign":
            fields.String(required=True, comment="加密认证"),
            "timestamp":
            fields.Integer(required=True, comment="时间戳"),
            "user_id":
            fields.Integer(required=True, comment="用户ID"),
            "shop_id":
            fields.Integer(
                required=True, validate=[validate.Range(1)], comment="店铺ID"),
            "verify_status":
            fields.Integer(
                required=True,
                validate=[
                    validate.OneOf([
                        ShopVerifyActive.YES,
                        ShopVerifyActive.CHECKING,
                        ShopVerifyActive.REJECTED,
                    ])
                ],
                comment="店铺认证状态",
            ),
            "verify_type":
            fields.Integer(
                required=True,
                validate=[
                    validate.OneOf(
                        [ShopVerifyType.ENTERPRISE, ShopVerifyType.INDIVIDUAL])
                ],
                comment="店铺认证类型,个人/企业",
            ),
            "verify_content":
            fields.String(required=True,
                          validate=[validate.Length(0, 200)],
                          comment="认证内容"),
        },
        location="json")
    @SuperBaseView.validate_sign("sign", ("user_id", "timestamp"))
    def put(self, request, args):
        shop = get_shop_by_shop_id(args.pop("shop_id"))
        if not shop:
            return self.send_fail(error_text="店铺不存在")
        serializer = SuperShopVerifySerializer(shop, data=args)
        if not serializer.is_valid():
            return self.send_error(error_message=serializer.errors,
                                   status_code=status.HTTP_400_BAD_REQUEST)
        serializer.save()
        return self.send_success()
Ejemplo n.º 7
0
class AdminDashboardShopDataView(AdminBaseView):
    """后台-店铺数据概览"""

    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_DASHBORD]
    )
    @use_args(
        {
            "statistic_type": fields.Integer(
                required=True,
                validate=validate.OneOf(
                    [StatisticType.DAILY, StatisticType.MONTHLY, StatisticType.YEARLY]
                ),
            ),
            "from_date": fields.String(missing="", comment="筛选起始日期"),
            "to_date": fields.String(missing="", comment="筛选终止日期"),
        },
        location="query"
    )
    def get(self, request, args):
        try:
            from_date, to_date = TimeFunc.get_to_date_by_from_date(
                args["from_date"], args["to_date"], args["statistic_type"]
            )
        except ValueError as e:
            return self.send_fail(error_text=str(e))
        _, data_list = list_shop_dashboard_data(
            self.current_shop.id,
            from_date,
            to_date,
            args["statistic_type"],
        )
        return self.send_success(data_list=data_list)
Ejemplo n.º 8
0
class AdminConfigMsgNotifyView(AdminBaseView):
    """后台-设置-消息通知-获取&修改店铺消息通知设置"""
    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_CONFIG])
    def get(self, request):
        shop_id = self.current_shop.id
        msg_notify = get_msg_notify_by_shop_id(shop_id)
        msg_notify = MsgNotifySerializer(msg_notify).data
        return self.send_success(data=msg_notify)

    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_CONFIG])
    @use_args(
        {
            "field":
            fields.String(
                required=True,
                validate=[validate.OneOf(msg_notify_field_list)],
                comment="更改的字段",
            ),
            "value":
            fields.Boolean(required=True, comment="更改的值"),
        },
        location="json")
    def put(self, request, args):
        shop_id = self.current_shop.id
        msg_notify_info = {args.get("field"): args.get("value")}
        update_msg_notify_by_shop_id(shop_id, msg_notify_info)
        return self.send_success()
Ejemplo n.º 9
0
class AdminPayModeConfigView(AdminBaseView):
    """后台-商铺的支付方式设置"""
    @AdminBaseView.permission_required(
        [AdminBaseView.staff_permissions.ADMIN_CONFIG])
    @use_args(
        {
            "key":
            fields.String(
                required=True,
                validate=[validate.OneOf(["weixin_jsapi", "on_delivery"])],
                comment="设置的字段名",
            ),
            "value":
            fields.Boolean(required=True, comment="设置的字段值"),
        },
        location="json")
    def put(self, request, args):
        shop = self.current_shop
        config_info = {args.get("key"): args.get("value")}
        is_wx = "weixin_jsapi" in config_info.keys()
        # 未认证或者未开通线上支付时,还是可以点击关闭货到付款按钮
        if is_wx and shop.cerify_active != ShopVerifyActive.YES:
            return self.send_fail(error_text="已认证的商铺才可申请开通在线支付,您的店铺暂未认证,请前往认证")
        if is_wx and shop.pay_active != ShopPayActive.YES:
            return self.send_fail(error_text="店铺未开通线上支付")
        some_config = update_some_config_by_shop_id(shop.id, config_info)
        # 最少需要保留一种支付方式
        if not some_config.weixin_jsapi and not some_config.on_delivery:
            return self.send_fail(error_text="至少保留一种商城支付方式,否则客户无法支付")
        return self.send_success()
Ejemplo n.º 10
0
class CalendarDatesExport(CalendarDatesView):

    renderers = {
        'csv': (calendar.EventSchema, calendar.render_csv, 'text/csv'),
        'ics':
        (calendar.ICalEventSchema, calendar.render_ical, 'text/calendar'),
    }

    @use_kwargs(args.calendar_dates)
    @use_kwargs({
        'renderer':
        fields.Str(missing='ics', validate=validate.OneOf(['ics', 'csv'])),
    })
    def get(self, **kwargs):
        query = self.build_query(**kwargs)
        today = datetime.date.today()
        query = query.filter(
            self.model.start_date >= today - relativedelta(years=1),
            self.model.start_date < today + relativedelta(years=1),
        )
        schema_type, renderer, mimetype = self.renderers[kwargs['renderer']]
        schema = schema_type(many=True)
        return Response(
            renderer(schema.dump(query).data, schema),
            mimetype=mimetype,
        )
Ejemplo n.º 11
0
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."
    )
            
    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']))
    
    model_name = fields.Str(
        required=False,
        missing = "mosaic",
        description="Name of the saved model. This module already comes with some styles, just write the name: 'mosaic', 'candy', 'rain_princess' or 'udnie'. You can see the styles in the dataset/style_images folder. Running 'get_metadata' return the list of models in the module."
    )
Ejemplo n.º 12
0
class Stats(Schema):

    param = fields.Str(
        required=True,
        validate=validate.OneOf(["disk", "cpu", "ram"]),
        description="Please select the type of monitor",
    )
Ejemplo n.º 13
0
class AnswerGrate(Resource):

    grate_args = {
        'grate': fields.Int(validate=validate.OneOf([0, 1, 2]), required=True)
    }

    def get(self, ask_id):
        abort_if_ask_doesnt_exist(ask_id)
        ask = Ask.query.get(ask_id)
        if g.student_user.id != ask.student_id:
            abort(403, code=0, message='没有权限')
        grate_value = ask.answer_grate
        return {'code': 1, 'grate_value': grate_value}, 200

    @use_args(grate_args)
    def put(self, args, ask_id):
        abort_if_ask_doesnt_exist(ask_id)
        ask = Ask.query.get(ask_id)
        if g.student_user.id != ask.student_id:
            abort(403, code=0, message='没有权限')
        if not ask.be_answered:
            abort(400, code=0, message='没有被回答')
        ask.answer_grate = args['grate']
        db.session.add(ask)
        db.session.commit()
        return {'code': 1}, 201
Ejemplo n.º 14
0
def get_predict_args():

    parser = OrderedDict()

    # Add data and url fields
    parser['files'] = fields.Field(
        required=False,
        missing=None,
        type="file",
        data_key="data",
        location="form",
        description="Select the image you want to classify.")

    # Use field.String instead of field.Url because I also want to allow uploading of base 64 encoded data strings
    parser['urls'] = fields.String(
        required=False,
        missing=None,
        description="Select an URL of the image you want to classify.")
    # missing action="append" --> append more than one url

    # Add format type of the response
    parser['accept'] = fields.Str(
        description="Media type(s) that is/are acceptable for the response.",
        missing='application/zip',
        validate=validate.OneOf(
            ['application/zip', 'image/png', 'application/json']))

    return parser
Ejemplo n.º 15
0
class FilterDeviceHealthSchema(FilterSchema):
    sort_by = fields.Str(validate=validate.OneOf(
        ['device_id', 'software_version', 'created_at']),
                         missing='created_at')
    device_id = fields.Integer(missing=None)
    start_date_time = fields.DateTime(missing=None)
    end_date_time = fields.DateTime(missing=None)
Ejemplo n.º 16
0
    def _set_params_required(self, subset):
        ''' Set the param validation required parameter '''

        # make list or not
        self._required = [self._required] if not isinstance(self._required, (list, tuple)) else self._required

        # update the required attribute
        for req_param in self._required:
            if req_param in subset.keys():
                subset[req_param].required = True
                subset[req_param].allow_none = False

            if req_param == 'bintemp':
                bintemps = self._get_bin_temps()
                subset[req_param].validate = validate.OneOf(bintemps)
                subset[req_param].validators.append(validate.OneOf(bintemps))

        return subset
Ejemplo n.º 17
0
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']))
Ejemplo n.º 18
0
class SuperUserView(SuperBaseView):
    """总后台-用户-获取用户详情&修改用户基本信息"""
    @use_args(
        {
            "sign": fields.String(required=True, comment="加密认证"),
            "timestamp": fields.Integer(required=True, comment="时间戳"),
            "user_id": fields.Integer(required=True, comment="用户ID"),
        },
        location="query")
    @SuperBaseView.validate_sign("sign", ("user_id", "timestamp"))
    def get(self, request, args):
        user = self._get_current_user(request)
        if not user:
            return self.send_error(status_code=status.HTTP_401_UNAUTHORIZED,
                                   error_message={"error_text": "用户未登录"})
        serializer = SuperUserSerializer(user)
        return self.send_success(data=serializer.data)

    @use_args({
        "sign":
        fields.String(required=True, comment="加密认证"),
        "timestamp":
        fields.Integer(required=True, comment="时间戳"),
        "user_id":
        fields.Integer(required=True, comment="用户ID"),
        "nickname":
        fields.String(required=False,
                      validate=[validate.Length(1, 15)],
                      comment="用户昵称"),
        "realname":
        fields.String(required=False,
                      validate=[validate.Length(1, 15)],
                      comment="用户真实姓名"),
        "sex":
        fields.Integer(
            required=False,
            validate=[validate.OneOf([Sex.UNKNOWN, Sex.FEMALE, Sex.MALE])],
        ),
        "birthday":
        fields.Date(required=False, comment="出生日期"),
        "head_image_url":
        fields.String(required=False,
                      validate=[validate.Length(0, 1024)],
                      comment="用户头像")
    })
    @SuperBaseView.validate_sign("sign", ("user_id", "timestamp"))
    def put(self, request, args):
        user = self._get_current_user(request)
        if not user:
            return self.send_error(status_code=status.HTTP_401_UNAUTHORIZED,
                                   error_message={"error_text": "用户未登录"})
        if not args:
            return self.send_fail(error_text="参数有误")
        user = update_user_basic_data(user, args)
        serializer = UserSerializer(user)
        return self.send_success(data=serializer.data)
Ejemplo n.º 19
0
class MintTokenSchema(BaseSchema):
    to = AddressField(required=True)
    value = fields.Integer(required=True,
                           validate=validate.Range(min=1, max=UINT256_MAX))
    contract_method = fields.String(validate=validate.OneOf(
        choices=("increaseSupply", "mint", "mintFor")))

    class Meta:
        strict = True
        decoding_class = dict
Ejemplo n.º 20
0
def add_settings_routes(app):
    """ Create routes related to settings """
    @app.route('/v1/rule_settings/', methods=['GET'])
    @requires_agency_code_perms('submitter')
    @use_kwargs({
        'agency_code':
        webargs_fields.String(required=True),
        'file':
        webargs_fields.String(validate=webargs_validate.OneOf(
            FILE_TYPES,
            error='Must be {}, or {}'.format(', '.join(FILE_TYPES[:-1]),
                                             FILE_TYPES[-1])),
                              required=True)
    })
    def get_rule_settings(**kwargs):
        """ Returns the rule settings based on the filters provided """
        agency_code = kwargs.get('agency_code')
        file = kwargs.get('file')
        return list_rule_settings(agency_code, file)

    @app.route('/v1/save_rule_settings/', methods=['POST'])
    @requires_agency_code_perms('submitter')
    @use_kwargs({
        'agency_code':
        webargs_fields.String(required=True),
        'file':
        webargs_fields.String(validate=webargs_validate.OneOf(
            FILE_TYPES,
            error='Must be {}, or {}'.format(', '.join(FILE_TYPES[:-1]),
                                             FILE_TYPES[-1])),
                              required=True),
        'errors':
        webargs_fields.List(webargs_fields.Dict),
        'warnings':
        webargs_fields.List(webargs_fields.Dict)
    })
    def post_save_rule_settings(**kwargs):
        """ Set the rule settings based on the rules provided """
        agency_code = kwargs.get('agency_code')
        file = kwargs.get('file')
        errors = kwargs.get('errors', [])
        warnings = kwargs.get('warnings', [])
        return save_rule_settings(agency_code, file, errors, warnings)
Ejemplo n.º 21
0
class WilayaArg(Schema):
    wilaya = fields.Str(validate=validate.OneOf(wilayas_values))

    @pre_load
    def handle_multi_word_wilaya(self, in_data, **kwargs):
        out_data = {**in_data}
        warnings.warn(
            'Hacking ..., check why multi word wilayas have two spaces')
        out_data['wilaya'] = out_data['wilaya'].replace(' ', '  ')
        return out_data
Ejemplo n.º 22
0
class UpdateUserSchema(ma.Schema, PublisherChecks):
    name = fields.Str(validate=validate.Length(min=1, max=100), missing=None)
    email = fields.Str(validate=validate.Email(), missing=None)
    role = fields.Str(validate=validate.OneOf([r[0] for r in ROLES]), missing=None)
    publisher_id = fields.Integer(missing=None)

    @validates_schema
    def check_all(self, data, **_):  # noqa
        if not any([v for v in data.values()]):
            raise ValidationError('All fields are empty')
Ejemplo n.º 23
0
class StatisticsValueDistributionSchema(BaseSchema):
    distribution_by = fields.String(
        required=True,
        validate=validate.OneOf(choices=('location', 'asset')),
    )

    class Meta:
        strict = True
        # decoding to a dict is required by the @use_kwargs decorator from webargs
        decoding_class = dict
Ejemplo n.º 24
0
class RHUserExperiment(RHProtected):
    def _process_GET(self):
        from indico_burotel.plugin import BurotelPlugin
        return jsonify(value=BurotelPlugin.user_settings.get(session.user, 'default_experiment'))

    @use_kwargs({
        'value': fields.String(validate=validate.OneOf({'ATLAS', 'CMS', 'ALICE', 'LHCb', 'HSE'}), allow_none=True)
    })
    def _process_POST(self, value):
        from indico_burotel.plugin import BurotelPlugin
        BurotelPlugin.user_settings.set(session.user, 'default_experiment', value)
Ejemplo n.º 25
0
class DataImportSchema(BaseSchema):
    source = fields.String(
        required=True,
        validate=validate.OneOf(choices=('cointracking.info',)),
    )
    filepath = FileField(required=True)

    class Meta:
        strict = True
        # decoding to a dict is required by the @use_kwargs decorator from webargs
        decoding_class = dict
Ejemplo n.º 26
0
class DeploySchema(ma.Schema):
    title = ma.Str(required=True)
    image = ma.Str(required=True)
    restart_policy = ma.Str(required=True,
                            validate=validate.OneOf(
                                ['always', 'on-failure', 'unless-stopped']))
    ports = ma.List(ma.Nested(PortSchema))
    volumes = ma.List(ma.Nested(VolumesSchema))
    env = ma.List(ma.Nested(EnvSchema))
    sysctls = ma.List(ma.Nested(SysctlsSchema))
    cap_add = ma.List(ma.Str())
Ejemplo n.º 27
0
class Foo(Resource):
    args = {
        'bar':
        fields.Str(
            required=True,
            validate=validate.OneOf(['baz', 'qux']),
        ),
    }

    @use_kwargs(args)
    def get(self, bar):
        return {'bar': bar}
Ejemplo n.º 28
0
class PortSchema(ma.Schema):
    cport = ma.Int(
        validate=validate.Range(min=0, max=65535)
    )
    hport = ma.Int(
        required=True,
        validate=validate.Range(min=0, max=65535)
    )
    proto = ma.Str(
        required=True,
        validate=validate.OneOf(['tcp','udp'])
    )
Ejemplo n.º 29
0
class db_data(Resource):
    dateadd_args = {
        "startDate": fields.Date(required=False),
        "timespan": fields.Str(missing="DAY", validate=validate.OneOf(["DAY", "MONTH", "YEAR"])),
    }
    @use_args(dateadd_args, location="query")
    def get(self, args):
        if "startDate" not in args:
            startDate = datetime.date.today()
        else:
            startDate = args["startDate"]
        return e3dc.get_db_data(startDate = startDate, timespan = args["timespan"], keepAlive = True)
Ejemplo n.º 30
0
class FilterSchema(Schema):
    """Structure for a filter."""

    function = fields.Str(
        required=False,
        missing="and",
        validate=validate.OneOf(["and", "or", "xor", "one"]),
    )
    invert = fields.Boolean(required=False, missing=False)
    rules = fields.List(fields.Nested(RuleSchema),
                        required=True,
                        validate=validate.Length(min=1))