def edit_managed_instagram_account(id): managed_instagram_account = ManagedInstagramAccount.query.get_or_404(id) try: for key, value in request.json.items(): setattr(managed_instagram_account, key, value) except Exception as err: raise ValidationError(str(err)) db.session.add(managed_instagram_account) db.session.commit() return jsonify(managed_instagram_account_schema.dump(managed_instagram_account))
def import_data(self, data): try: if 'info_id' in data: self.info_id = data['info_id'] self.status = data['status'] self.color = data['color'] self.img = data['img'] self.desc = data['desc'] except ValueError as e: raise ValidationError("Invalid References: missing " + e.args[0])
def edit_post(id): post = Post.query.get_or_404(id) try: for key, value in request.json.items(): setattr(post, key, value) except Exception as err: raise ValidationError(str(err)) db.session.add(post) db.session.commit() return jsonify(post_schema.dump(post))
def import_data(self, data): try: self.c_name = data['c_name'] self.e_name = data['e_name'] self.type = data['type'] self.desc = data['desc'] self.ref_min = float(data['ref_min']) self.ref_max = float(data['ref_max']) except KeyError as e: raise ValidationError("Invalid Information: missing " + e.args[0])
def from_json(json_score): user_id = json_score.get('user_id') game = json_score.get('game') state = json_score.get('state') score = json_score.get('score') max_score = json_score.get('max_score') duration = json_score.get('duration') is_exam = json_score.get('is_exam') if game is None or game == '': raise ValidationError('score does not have a game') if state is None or state == '': raise ValidationError('score does not have a state') return Score(user_id=user_id, game=game, score=score, max_score=max_score, duration=duration, state=state, is_exam=is_exam)
def validate_repeat(self): '''Valudate: repeat''' repeat_emailEvent = self.query.filter_by( event_id=self.event_id, email_group_id=self.email_group_id, email_subject = self.email_subject, email_content=self.email_content, timestamp=self.timestamp ).first() if repeat_emailEvent and repeat_emailEvent.id != self.id: raise ValidationError(VALIDERROR_TEMPLATE["repeat"] % ('email_event',))
def new_comment(id): if request.json: post = Post.from_json(request.json, True) post.author = g.current_user post.parent_post_id = id post.disabled = not g.current_user.confirmed db.session.add(post) db.session.commit() return jsonify(post.to_json()), 201 else: raise ValidationError("body is Empty")
def from_json(json_compile_info): ''' update compile info using json :param json_compile_info: json :return: compile_info item ''' info = json_compile_info.get('info') if info is None or info == '': raise ValidationError('Compile_info require full data') return CompileInfo(info=info)
def import_data(self, data, user_id): try: self.user_id = user_id self.date = datetime_parser.parse(data['date']).date() self.distance = data['distance'] self.time = datetime_parser.parse(data['time']).time() self.latitude = data['latitude'] self.longitude = data['longitude'] except KeyError as e: raise ValidationError('Invalid Entry: missing ' + e.args[0]) return self
def from_json(json_project: Dict[str, Any]) -> 'Project': name = json_project.get('name') reference_number = json_project.get('reference_number') margin = json_project.get('margin') admin_fee = json_project.get('admin_fee') if name is None or name == '': raise ValidationError('project does not have a name') return Project(name=name, margin=margin, admin_fee=admin_fee, reference_number=reference_number)
def from_json(cls, json_user): """ Convert a json request to a User """ email = json_user.get('email') username = json_user.get('username') password = json_user.get('password') if email and username and password: return cls(email=email, username=username, password=password) else: raise ValidationError('insufficient data to create User')
def is_valid_number(num, max_val: int) -> bool: """Function validate a number. Args: num (int): number to be validated. max_val (int): number cannot exceed this value. Raises: TypeError: raised when input is not of type "int". ValidationError: raised when the integer number is < 0 or > max_val. """ if not isinstance(num, int): raise TypeError("Only Integer Values are allowed") if num < 0: raise ValidationError("Negative numbers are not allowed") if num > max_val: raise ValidationError("Input exceed maximum allowed limit") return True
def register(): """ 注册,省去了PC端注册时邮件验证的步骤 """ email = request.args.get('email') password = request.args.get('password') username = request.args.get('username') if email is None: raise ValidationError('邮箱不能为空') if password is None: raise ValidationError('密码不能为空') if username is None: raise ValidationError('昵称不能为空') user = User(email=email, username=username, password=password, confirmed=True) db.session.add(user) db.session.commit() return response()
def add_comment(blog_id): """ 提交评论 """ content = request.args.get('content') if content is None or content == '': raise ValidationError('评论内容不能为空') blog = Blog.query.get_or_404(blog_id) comment = Comment(content=content, blog=blog, user=g.current_user) db.session.add(comment) db.session.commit() return response()
def delete_option(id): option = SkuOption.query.get_or_404(id) feature_id = option.sku_feature.id if option.is_used(): raise ValidationError("sku option has been used", 400) db.session.delete(option) db.session.commit() cache.delete_memoized(get_features) cache.delete_memoized(get_feature, feature_id) response = jsonify({'status': "success"}) response.status_code = 200 return response
def from_json(post_json, order_status): details = post_json.get('details') # if (details is None or details == ''): # raise ValidationError('doesnot have a customer name') # payment_method = post_json.get('payment_method') # if (payment_method is None or payment_method == ''): # raise ValidationError('doesnot have a payment_method') # payment_status = post_json.get('payment_status') # if (payment_status is None or payment_status == ''): # raise ValidationError('doesnot have a payment_status') total_amount = 0 # if (total_amount is None or total_amount == ''): # raise ValidationError('doesnot have a total_amount') delivery_address = post_json.get('delivery_address') if (delivery_address is None or delivery_address == ''): raise ValidationError('doesnot have a delivery address') delivery_address_pin = post_json.get('delivery_address_pin') if (delivery_address_pin is None or delivery_address_pin == ''): raise ValidationError('doesnot have a delivery address pin') if (delivery_address_pin.strip() != ''): charge = DeliveryCharge.get_delivery_charge( int(delivery_address_pin.strip(), base=10)) if charge is None: charge = DeliveryCharge.get_default_charge() delivery_charge = charge.amount customer_name = post_json.get('customer_details').get('customer_name') if (customer_name is None or customer_name == ''): raise ValidationError('doesnot have a customer name') customer_contact_phone = post_json.get('customer_details').get( 'contact_phone') if (customer_contact_phone is None or customer_contact_phone == ''): raise ValidationError('doesnot have a customer phone') customer_address = post_json.get('customer_details').get( 'contact_address') if (customer_address is None or customer_address == ''): raise ValidationError('doesnot have a customer address') customer_address_pin = post_json.get('customer_details').get( 'address_pin') if (customer_address_pin is None or customer_address_pin == ''): raise ValidationError('doesnot have a customer address pin') return PlacedOrder(\ total_amount = total_amount, payment_method = PaymentMethod.default_id().id, payment_status = PaymentStatus.get_pending().id,\ details = details, delivery_address = delivery_address,\ delivery_address_pin = delivery_address_pin, delivery_charge = delivery_charge,\ customer_name= customer_name, customer_contact_phone= customer_contact_phone ,\ customer_address = customer_address,customer_address_pin = customer_address_pin,\ order = order_status)
def from_json(json_baseurl): url_name = json_baseurl.get('url_name') qa_url = json_baseurl.get('qa_url') pro_url = json_baseurl.get('pro_url') system_id = json_baseurl.get('system_id') project_id = json_baseurl.get('project_id') if url_name is None or url_name == '': raise ValidationError('url_name is null') return Baseurl(url_name=url_name, qa_url=qa_url, pro_url=pro_url, system_id=system_id, project_id=project_id)
def from_json(json_post): body = json_post.get('body') title = json_post.get('title') summary = json_post.get('summary') category_data = json_post.get('category') if body == '' or title == '' or summary == '' or category_data == '': return ValidationError('message missing') category = Category.query.filter_by(tag=category_data).first() if category is None: category = Category(tag=category_data) db.session.add(category) db.session.commit() return Post(body=body, title=title, summary=summary, category=category)
def lookup_jid(jid): """ 默认登录用户能查所有的jobs, 这里设置只能返回本服务器的jobs. 这里用了一个requests的内部变量做的修改. :param jid: :return: """ ret = Salt.salt_client.lookup_jid(jid=jid) if ret.status_code == 401: raise ValidationError('SaltStack NetAPI Permission required') # 返回的内容类似: # {u'return': [{u'SERVER6': True}]} return ret
def modify_post(id): if request.json and request.json.get('body'): post = Post.query.get_or_404(id) if g.current_user.can( Permission.MODERATE_COMMENTS) or post.author == g.current_user: post.body = request.json.get('body') db.session.add(post) db.session.commit() else: return forbidden("您不具备操作权限") return jsonify(post.to_json()) else: raise ValidationError('body 是空的')
def delete_feature(id): feature = SkuFeature.query.get_or_404(id) if feature.is_used(): raise ValidationError("sku feature has been used", 400) for option in feature.sku_options: db.session.delete(option) db.session.delete(feature) db.session.commit() cache.delete_memoized(get_features) cache.delete_memoized(get_feature, id) response = jsonify({'status': "success"}) response.status_code = 200 return response
def from_json(json): provider_branch_id = json.get('provider_branch_id') teacher_id = json.get('teacher_id') latitude = json.get('latitude') longitude = json.get('longitude') if provider_branch_id is None: raise ValidationError('provider_branch_id cannot be empty') if teacher_id is None: raise ValidationError('teacher_id cannot be empty') if latitude is None: raise ValidationError('latitude cannot be empty') if longitude is None: raise ValidationError('longitude cannot be empty') return TrainingSession(provider_branch_id=provider_branch_id, teacher_id=teacher_id, latitude=latitude, longitude=longitude)
def from_json(json_news): # json 입력 루틴 context = json_news.get('context') if context is None or context == '': raise ValidationError('news does not have a context') parsed_context = removeEscapeChar(context).lower() group = None if json_news.get('group') is not None and json_news.get('group') != '': group = json_news.get('group') news = News(context=context, parsed_context=parsed_context, group=group) return news
def json_schema_validator_by_filename( json_data, json_schema_filename, json_schema_file_path='app/utils/json_schema'): """ 默认从'app/utils/json_schema'目录里读取文件内容做验证. """ try: json_schema_file_full_path = get_full_path(json_schema_file_path, json_schema_filename) with open(json_schema_file_full_path) as f: json_schema = f.read() except IOError, e: raise ValidationError('Invalid json schema file path', e)
def from_json(json_comment): # json 입력 루틴 author_id = json_comment.get('author_id') googleUserImage = json_comment.get('googleUserImage') context = json_comment.get('context') if (author_id is None or author_id == '') and \ (context is None or context == ''): raise ValidationError('comment does not have a context') parsed_context = removeEscapeChar(context).lower() return Comment(author_id=author_id, googleUserImage=googleUserImage, context=context, parsed_context=parsed_context)
def import_data(self, data): try: self.client_id = data['client_id'] self.original_id = data['original_id'] self.puyuan_id = data['puyuan_id'] self.is_reported = data['is_reported'] self.product_type = data['product_type'] self.sampling_date = data['sampling_date'] self.receive_date = data['receive_date'] self.test_date = data['test_date'] self.tester = data['tester'] self.auditor = data['auditor'] self.content = data['content'] except KeyError as e: raise ValidationError("Invalid Information: missing " + e.args[0])
def from_json(json_submission): ''' update submissions using json :param json_submission: :return: submission item ''' status = json_submission.get('status') exec_time = json_submission.get('exec_time') exec_memory = json_submission.get('exec_memory') if status is None or status == '' or exec_time is None or exec_time == '' or exec_memory is None or exec_memory == '': raise ValidationError('Status require full data') return SubmissionStatus(status=status, exec_time=exec_time, exec_memory=exec_memory)
def remove_user_from_group(): """ 把用户从组里移除 需要post中提供group_id,用户的email :return: """ try: group_id = request.get_json()['group_id'] email = request.get_json()['email'] except KeyError as e: raise ValidationError('Invalid Group or User: missing' + e.args[0]) group = Group.query.get_or_404(group_id) user = User.query.filter_by(email=email).first_or_404() return jsonify([user.export_data() for user in group.remove_user(user)])
def from_json(json_data): required = ['from_', 'to'] valid_data = {} for field in required: data = json_data.get(field) if data is None or data == '': raise ValidationError( 'exchange rate does not have a {}'.format(field)) valid_data[field] = data return ExchangeRateList( from_=valid_data['from_'], to=valid_data['to'], )
def from_json(json_match_week): values = [] number = json_match_week.get('number') user_id = json_match_week.get('user_id') matches = json_match_week.get('matches') values.append(number) values.append(user_id) values.append(matches) for value in values: if value is None or value == '': raise ValidationError('One or more values were wrong') return MatchWeek(number=number, user_id=user_id, matches=matches)