def _hour_adver_report_get(): current_app.logger.info(request.url) current_app.logger.info("current_app _hour_adver_report get") rules = { "startdate": [Required, Length(8, 8)], "enddate": [Required, Length(8, 8)] } valid, errors = validate(rules, request.args) # current_app.logger.info(str(valid) + str(errors)) result = results() # 参数校验 if not valid: result.set_statuscode(1) result.set_data(str(errors)) return jsonify(json.loads(str(result))) conn = MysqlUtil("adver") sql = """select day<=%s """ % (request.args.get('startdate', None), request.args.get('enddate', None)) if request.args.get('b', None): sql = sql + " and b in (%s)" % (request.args.get('b', None)) sql = sql + """ group by day,hour,b,impid,a ) as t left join adx_ssp_adposition b on b.id=t.impid left join( select * from adver_ssp_strategy union all select * from adver_ssp_strategy_sp)e on e.id=t.a """ current_app.logger.info(sql) print sql flag, res = conn.excute(sql) if flag: data = [] for row in res: dict_tmp = collections.defaultdict() dict_tmp['day'] = row[0] dict_tmp['hour'] = row[1] dict_tmp['b'] = row[2] dict_tmp['impid'] = row[3] dict_tmp['impidname'] = row[4] dict_tmp['strategyid'] = row[5] dict_tmp['strategyname'] = row[6] dict_tmp['request'] = row[7] dict_tmp['start'] = row[8] dict_tmp['imp'] = row[9] dict_tmp['click'] = row[10] dict_tmp['clickrate'] = row[11] for k, v in dict_tmp.items(): dict_tmp[k] = conver_type(v) data.append(dict_tmp) print "取出的条数=" + str(len(data)) current_app.logger.info("取出的条数=" + str(len(data))) result.set_statuscode(0) result.set_data(data) else: result.set_statuscode(1) result.set_resultMsg(res + ":sql exec fail!!!") return jsonify(json.loads(str(result)))
def validate_input(self, data): rules = { 'name': [Required, Not(Blank()), Length(3)], 'email': [Required, Not(Blank())], 'password': [Required, Not(Blank()), Length(6)], } return validate(rules, data)
def _day_seller_en_get(): current_app.logger.info(request.url) current_app.logger.info("current_app _day_seller_en_get get") rules = { "startdate": [Required, Length(8, 8)], "enddate": [Required, Length(8, 8)] } valid, errors = validate(rules, request.args) # current_app.logger.info(str(valid) + str(errors)) result = results() # 参数校验 if not valid: result.set_statuscode(1) result.set_data(str(errors)) return jsonify(json.loads(str(result))) conn = MysqlUtil("adver") sql = """s """ % (request.args.get('startdate', None), request.args.get('enddate', None)) if request.args.get('en', None): sql = sql + " and en in ( '%s') " % (request.args.get('en', None)) sql = sql + """ group by day,en,terminal """ current_app.logger.info(sql) print sql flag, res = conn.excute(sql) if flag: data = [] for row in res: list_col = [ 'day', 'en', 'terminal', 'oreq', 'sreq', 'sres', 'sans', 'request', 'start', 'imp', 'click', 'repository', 'repository_max', 'repository_30max' ] dict_tmp = convert_object(list_col, row) #判断列数是否一致 if dict_tmp == 1: data.append({"error": '序列化列数不一致'}) result.set_data(data) result.set_statuscode(1) return jsonify(json.loads(str(result))) for k, v in dict_tmp.items(): dict_tmp[k] = conver_type(v) data.append(dict_tmp) print "取出的条数=" + str(len(data)) current_app.logger.info("取出的条数=" + str(len(data))) result.set_statuscode(0) result.set_data(data) else: result.set_statuscode(1) result.set_resultMsg(res + ":sql exec fail!!!") return jsonify(json.loads(str(result)))
def _hour_adx_buyer_position_get(): current_app.logger.info(request.url) current_app.logger.info("current_app hour_adx_buyer_position get") rules = { "startdate": [Required, Length(8, 8)], "enddate": [Required, Length(8, 8)] } valid, errors = validate(rules, request.args) # result = results() current_app.logger.info(str(valid) + str(errors)) #参数校验 if not valid: result.set_statuscode(1) result.set_data(str(errors)) return jsonify(json.loads(str(result))) conn = MysqlUtil("adver") sql = """SEL day>=%s and day<=%s """ % (request.args.get('startdate', None), request.args.get('enddate', None)) if request.args.get('b', None): sql = sql + " and buyerid in (%s)" % (request.args.get('b', None)) sql = sql + """ group by hab.buyerid,hab.day,hab.hour,hab.impid,asa.name""" current_app.logger.info(sql) print sql flag, res = conn.excute(sql) if flag: data = [] for row in res: dict_tmp = collections.defaultdict() dict_tmp['buyerid'] = row[0] dict_tmp['day'] = row[1] dict_tmp['hour'] = row[2] dict_tmp['impid'] = row[3] dict_tmp['impidname'] = row[4] dict_tmp['imp'] = row[5] dict_tmp['click'] = row[6] dict_tmp['effectincome'] = row[7] dict_tmp['position_request'] = row[8] dict_tmp['position_bid'] = row[9] dict_tmp['win'] = row[10] dict_tmp['timeoutrate'] = row[11] for k, v in dict_tmp.items(): dict_tmp[k] = conver_type(v) data.append(dict_tmp) print "取出的条数=" + str(len(data)) current_app.logger.info("取出的条数=" + str(len(data))) result.set_statuscode(0) result.set_data(data) else: result.set_statuscode(1) result.set_resultMsg(res + ":sql exec fail!!!") return jsonify(json.loads(str(result)))
def get_rules(valid_users_list, valid_teams_list): # Audit log attributes needs to meet the following rules. rules = { constant.USER_ATTRIBUTE: [Required, In(valid_users_list), Length(5, maximum=100)], constant.TEAM_ATTRIBUTE: [Required, In(valid_teams_list), Length(5, maximum=100)], constant.COMPONENT_ATTRIBUTE:[Required, Length(5, maximum=100), Pattern(name_regex)], constant.SUB_COMPONENT_ATTRIBUTE:[Required, Length(5, maximum=100), Pattern(name_regex)] } return rules
def validate_input(self, data): users = User.all() rules = { 'name': [Required, Not(Blank()), Length(3)], 'email': [Required, Not(Blank()), Not(In(users.pluck('email')))], 'password': [Required, Not(Blank()), Length(6)], } return validate(rules, data)
def login(self): users = User.all() self.messages({ 'username': '******', 'password': '******', }) return self.validate({ 'username': [ Required, Length(1, 35), In(users.pluck('email').map(lambda item: item.lower())) ], 'password': [Required, Length(1)] })
def validate_backend(data): rules = { "host": [Required, ValidHostWithPort()], "service_name": [Required, Length(3, 50)], "target_group_name": [Required], } return validate(rules, data)
def validate_target_group(data): rules = { "service_name": [Required, Length(3, 50)], "target_group_name": [Required], "weight": [Required, Range(0, 256)], } return validate(rules, data)
def register(self): users = User.all() self.messages({ 'email': 'That email already exists', 'username': '******' }) return self.validate({ 'username': [Required, Length(3, 20)], 'email': [Required, Length(1), Not(In(users.pluck('email')))], 'password': [Required] })
def validate_new_form(self): self.request.request_variables['tags'] = self.request.input( 'tags').split(',') return self.validate({ 'title': [Required, Not(Blank())], 'body': [Required, Not(Blank())], 'tags': [Required, Length(1, maximum=5)], })
def validator_doc(doc_data): results = {} result_errors = {} validation = { 'doc_tab': [Required, In(tab)], 'model_id': [Required, Length(0, maximum=50), lambda x: isinstance(x, str)], 'doc_content': [Required, lambda x: isinstance(x, list)] } res = validate(validation, doc_data) result_errors.update(res.errors) if isinstance(doc_data['doc_content'], list): for content in doc_data['doc_content']: validation = { 'language': [Required, In(language)], 'doc_name': [ Required, Length(0, maximum=50), lambda x: isinstance(x, str) ], 'content_title': [ Required, Length(0, maximum=200), lambda x: isinstance(x, str) ], 'developer': [Length(0, maximum=50), lambda x: isinstance(x, str)], 'brief_intro': [lambda x: isinstance(x, dict)], 'method': [lambda x: isinstance(x, dict)], 'model_evaluation': [lambda x: isinstance(x, dict)], 'data_set_size': [lambda x: isinstance(x, dict)], 'ethnicity': [lambda x: isinstance(x, dict)], 'limitation': [lambda x: isinstance(x, dict)], 'return_params': [lambda x: isinstance(x, dict)], 'state_explain': [lambda x: isinstance(x, dict)], 'example_result': [lambda x: isinstance(x, dict)], 'ref': [lambda x: isinstance(x, list)] } content_res = validate(validation, content) result_errors.update(content_res.errors) valid = True if result_errors: valid = False results['errors'] = result_errors results['valid'] = valid return results
def validate_service(data): rules = { "name": [Required, Length(3, 50)], "fqdn": [Required], "healthcheck_path": [], "healthcheck_interval": [Range(1000, 60000)], "healthcheck_rise": [Range(0, 20)], "healthcheck_fall": [Range(0, 20)], "connection_draining": [Range(5, 300)] } return validate(rules, data)
class DemoHandler(RESTHandler): AUTH_CHECK = True # 是否需要校验身份 arguments_valid_rules = { "phone": [Required, InstanceOf(unicode), Length(11, maximum=11)], "password": [ Required, ], } def get(self, *args, **kwargs): arguments = self.request.DATA # 请求参数 access_log.info("phone: %s, password: %s" % (arguments["phone"], arguments["password"])) error_log.error("f231312312332321") phone = arguments["phone"] result = {"message": "KO", "arguments": arguments} self._response(result) # 无异步,也可使用 self.write @gen.coroutine def post(self, *args, **kwargs): access_log.info("POST request") arguments = self.request.DATA # 请求参数, 兼容前端传json数据 url = "http://api.leyingke.com/lyk_new/v1/util/province/" http_client = AsyncHTTPClient() response = yield http_client.fetch(url) self._response(response.body, status=HTTP_STATUS_CREATED) @gen.coroutine def put(self, *args, **kwargs): access_log.info("PUT request") url = "http://api.leyingke.com/lyk_new/v1/util/province/" http_client = AsyncHTTPClient() response = yield http_client.fetch(url) self._response(response.body, status=HTTP_STATUS_ACCEPTED) def delete(self, *args, **kwargs): arguments = self.request.DATA # 请求参数 access_log.info("delete request") result = {"message": "delete", "arguments": arguments} self._response(result, status=HTTP_STATUS_ACCEPTED) # 无异步,也可使用 self.write
def test_valid(): rules = { "foo": [Required, Length(8,8)], # foo must be exactly equal to 123 "bar": [Required, Truthy()], # bar must be equivalent to True "baz": [In(["spam", "eggs", "bacon"])], # baz must be one of these options "qux": [Not(Range(1, 100))] # qux must not be a number between 1 and 100 inclusive } # then this following dict would pass: passes = { "foo": '20191027', "bar": True, # or a non-empty string, or a non-zero int, etc... "baz": "sp2am", "qux": 101 } valid,errors = validate(rules,passes) # 姿势 2 print valid print errors print type(valid) print type(errors)
def _check_params(data): """ Check if all the required parameters have been sent :param data: just a part of the post request, ipv4 or ipv6 :return: nothing, raise an exception in case of missing value """ rules = { "as": [Required, Length(1, maximum=15)], "name": [Required, Length(1, maximum=15)], "ip": [Required, Length(1, maximum=15)], "ixtype": [Required, Length(1, maximum=15)], "asexport": [Required, Length(1, maximum=15)], "import": [Required, Length(1, maximum=15)] } result = validate(rules, data) if not result[0]: raise BirdException(['{0} {1}'.format(key, value) for key, value in result[1].iteritems()])
def hello_form(self): self.messages({'name': 'Your name is not long enough!'}) return self.validate({'name': [Required, Length(3)]})
def test_validator_length(self): email_validator = Validator() email_validator.validate({'id': [Length(0, maximum=2)]}) assert email_validator.check({'id': [1, 2, 3, 4, 5]}) is False
def test(self): return self.validate({ 'id': [Length(0, maximum=2)] })
InstanceOf, SubclassOf, [Length(0, maximum=5)], url, GreaterThan, LessThan https://validatorpy.readthedocs.io/en/latest/index.html ''' rules = { "test": { "POST": { "ab": [Required, InstanceOf(str)], "id": [Required, InstanceOf(int)] } }, "reg": { "POST": { "name": [Required, Pattern(r"\w+")], "password": [Required, InstanceOf(str), Length(6, maximum=30)], } }, "login": { "GET": { "name": [Required, Pattern(r"\w+")], "password": [Required, InstanceOf(str), Length(6, maximum=30)], } }, "vote/add": { "POST": { "name": [Required, Pattern(r"\w+")], "pic_url": [Required, Url()], "bno": [Required, InstanceOf(int)]