class RequestArgs: schema = { 'freq': fields.Str(required=True), 'name': fields.Str(required=True), 'start_date': fields.Date(required=False), 'end_date': fields.Date(required=False) } validate_with = make_func_list([ 'start_is_not_in_future', 'end_date_after_start_date', 'freq_exist', 'names_validated' ]) query_keys = ['name', 'freq', 'start_date', 'end_date'] def __init__(self, request=flask.request): self.arg_dict = parser.parse(self.schema, req=request, validate=self.validate_with) def _make_dict(self, varnames): return {key: self.arg_dict.get(key) for key in varnames} def get_query_parameters(self): return self._make_dict(self.query_keys) def __getattr__(self, x): return self.arg_dict.get(x)
class RequestArgs: schema = { 'freq': fields.Str(required=True), 'name': fields.Str(required=True), 'start_date': fields.Date(required=False), 'end_date': fields.Date(required=False), 'format': fields.Str(missing='csv') } validate_with = make_func_list([ 'start_is_not_in_future', 'end_date_after_start_date', 'freq_exist', 'name_is_valid', 'format_is_valid' ]) query_keys = ['name', 'freq', 'start_date', 'end_date'] def __init__(self, request=flask.request): self._args = parser.parse(self.schema, req=request, validate=self.validate_with) @property def query_param(self): return {key: self._args.get(key) for key in self.query_keys} def __getattr__(self, x): return self._args.get(x)
class RHUpdateRoomAvailability(RHRoomAdminBase): @use_args({ 'bookable_hours': fields.Nested({ 'start_time': fields.Time(), 'end_time': fields.Time() }, many=True), 'nonbookable_periods': fields.Nested({ 'start_dt': fields.Date(), 'end_dt': fields.Date() }, many=True) }) def _process(self, args): if 'bookable_hours' in args: self._check_invalid_times(args) update_room_availability(self.room, args) return jsonify(nonbookable_periods=nonbookable_periods_schema.dump( self.room.nonbookable_periods, many=True), bookable_hours=bookable_hours_schema.dump( self.room.bookable_hours, many=True)) def _check_invalid_times(self, availability): if any(bh['start_time'] >= bh['end_time'] for bh in availability['bookable_hours']): abort(422, messages={ 'bookable_hours': [_('Start time should not be later than end time')] })
class SimplifiedArgs(RequestArgs): schema = { 'freq': fields.Str(required=False), 'name': fields.Str(required=False), 'start_date': fields.Date(required=False), 'end_date': fields.Date(required=False), } validate_with = make_func_list(['not_all_are_none']) query_keys = ['name', 'freq', 'start_date', 'end_date']
class RHCalendar(RHRoomBookingBase): @use_kwargs({ 'start_date': fields.Date(), 'end_date': fields.Date(), }) def _process(self, start_date, end_date): calendar = get_room_calendar(start_date or date.today(), end_date or date.today()) return jsonify(_serialize_availability(calendar).values())
class RHCreateRoomBlocking(RHRoomBookingBase): @use_args({ 'room_ids': fields.List(fields.Int(), missing=[]), 'start_date': fields.Date(), 'end_date': fields.Date(), 'reason': fields.Str(), 'allowed_principals': fields.List(fields.Dict()) }) def _process(self, args): blocking = create_blocking(created_by=session.user, **args) return jsonify(blockings_schema.dump(blocking, many=False).data)
class RHCreateRoomBlocking(RHRoomBookingBase): @use_args({ 'room_ids': fields.List(fields.Int(), missing=[]), 'start_date': fields.Date(required=True), 'end_date': fields.Date(required=True), 'reason': fields.Str(required=True), 'allowed': PrincipalList(allow_groups=True, required=True), }) def _process(self, args): blocking = create_blocking(created_by=session.user, **args) return jsonify(blockings_schema.dump(blocking, many=False))
class RHCreateRoomBlocking(RHRoomBookingBase): @use_args({ 'room_ids': fields.List(fields.Int(), missing=[]), 'start_date': fields.Date(), 'end_date': fields.Date(), 'reason': fields.Str(), 'allowed_principals': fields.List(fields.Dict()) }) def _process(self, args): blocking = create_blocking(created_by=session.user, **args) approve_or_request_blocking(blocking) return jsonify_data(flash=False)
class TachographGenerationScopeSchema(Schema): company_ids = fields.List(fields.Int(), required=True, validate=lambda l: len(l) > 0) user_ids = fields.List(fields.Int(), required=False) min_date = fields.Date(required=True) max_date = fields.Date(required=True) with_digital_signatures = fields.Boolean(required=False) @validates_schema def check_period_is_small_enough(self, data, **kwargs): if data["max_date"] - data["min_date"] > timedelta(days=60): raise ValidationError( "The requested period should be less than 60 days")
class CoursesList(Resource): @api.doc(params={'q': 'name or part of it', 'date': 'date'}) @use_kwargs({ 'q': args_fields.String(), 'date': args_fields.Date() }, location='query') def get(self, q: str = None, date: datetime.date = None): courses_query = Course.query if q: courses_query = courses_query.filter(Course.name.contains(q)) if date: courses_query = courses_query.filter(Course.starting_date <= date, Course.ending_date >= date) courses = courses_query.all() return CourseShema(many=True, only=['id', 'name']).dump(courses) @api.expect(course_fields) def post(self): course_data = CourseShema().load(request.get_json()) course = Course(**course_data) try: db.session.add(course) db.session.commit() except exc.IntegrityError as e: abort(400, description=f"Course with name {course.name} already exist") return CourseShema().dump(course)
class RHRoomBlockings(RHRoomBookingBase): @use_kwargs({ 'start_dt': fields.Date(), 'end_dt': fields.Date(), 'blockings_in_my_rooms': fields.Bool(), 'my_blockings': fields.Bool() }) def _process(self, start_dt, end_dt, blockings_in_my_rooms, my_blockings): filters = { 'start_dt': start_dt, 'end_dt': end_dt, 'created_by': session.user if my_blockings else None, 'in_rooms_owned_by': session.user if blockings_in_my_rooms else None } blockings = get_room_blockings(**filters) return jsonify(blockings_schema.dump(blockings).data)
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)
class MoneyValue(Resource): args = { 'start_date': fields.Date(required=True), 'start_value': fields.Int(required=True), 'end_date': fields.Date(required=True), } @use_kwargs(args) def get(self, start_date, start_value, end_date): if start_date > end_date: abort(422, "start_date is after end_date") start_date_str = start_date.strftime('%d/%m/%Y') end_date_str = end_date.strftime('%d/%m/%Y') start_real_value = -1 end_value = -1 with open('data/inflation_data.csv', 'r') as csvfile: read = csv.reader(csvfile, delimiter=',') headers = next(read)[1:] final_csv_row = None for row in read: if row[0] == start_date_str: start_real_value = start_value / float(row[1]) elif row[0] == end_date_str: end_value = float(row[1]) final_csv_row = row # Try one last time using yesterday's value if end_value < 0: end_date = end_date - datetime.timedelta(days=1) end_date_str = end_date.strftime('%d/%m/%Y') if final_csv_row[0] == end_date_str: end_value = float(final_csv_row[1]) if start_real_value < 0: abort(422, "No data available for that start_date") if end_value < 0: abort(422, "No data available for that end_date") return jsonify({ 'devalued': int(start_real_value * end_value), 'real': start_real_value })
class StatsResource(Resource): @requires_auth @use_args({ 'dateFrom': fields.Date(required=True, location='query'), 'dateTo': fields.Date(required=True, location='query'), 'product': fields.Int(required=True, location='query'), 'format': fields.Str(missing='json', location='query', validate=validate.Equal('json')) }) def get(self, args, **kwargs): query = db.session.query(Price.date, func.min(Price.price), func.avg(Price.price), func.max(Price.price)).\ filter(Price.product_id == args['product'], Price.date.between(args['dateFrom'], args['dateTo'])).\ group_by(Price.date).order_by(Price.date.asc()) stats = [Stat(*x) for x in query.all()] return StatSchema(many=True).dump(stats).data
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 RHCreateRoomBlocking(RHRoomBookingBase): @use_kwargs({ 'room_ids': fields.List(fields.Int(), missing=[]), 'start_date': fields.Date(), 'end_date': fields.Date(), 'reason': fields.Str(), 'allowed_principals': fields.List(fields.Dict(), missing=[]) }) def _process(self, room_ids, start_date, end_date, reason, allowed_principals): rooms = Room.query.filter(Room.id.in_(room_ids)).all() allowed = [] for obj in allowed_principals: if obj.get('is_group'): allowed.append(GroupProxy(obj['id'], provider=obj['provider'])) else: allowed.append(User.query.filter(User.id == obj['id']).one()) blocking = create_blocking(rooms, start_date, end_date, reason, allowed) approve_or_request_blocking(blocking) return jsonify_data(flash=False)
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)
class RequestFrameArgs(RequestArgs): schema = { 'freq': fields.Str(required=True), 'names': fields.Str(required=False), 'start_date': fields.Date(required=False), 'end_date': fields.Date(required=False), } validate_with = make_func_list([ 'start_is_not_in_future', 'end_date_after_start_date', 'freq_exist', 'names_are_valid' ]) query_keys = ['names', 'freq', 'start_date', 'end_date'] def __init__(self, request=flask.request): self._args = parser.parse(self.schema, req=request, validate=self.validate_with) names = self._args.get('names') if names: self._args['names'] = names.split(',')
class RequestFrameArgs(RequestArgs): schema = { 'freq': fields.Str(required=True), 'name': fields.Str(required=False), 'start_date': fields.Date(required=False), 'end_date': fields.Date(required=False) } validate_with = make_func_list([ 'start_is_not_in_future', 'end_date_after_start_date', 'freq_exist', 'names_validated' ]) query_keys = ['names', 'freq', 'start_date', 'end_date'] def __init__(self, request=flask.request): super().__init__(request) # convert names name_str = self.arg_dict.get('name') names = convert_name_string_to_list(name_str) if not names: names = Allowed.names(self.freq) self.arg_dict['names'] = names
class SignatureSheets(Resource): insert_sheet = { 'updated': fields.Date(required=False), 'id_type': fields.Int(required=True), 'id_employee': fields.Str(required=True), 'first_name': fields.Str(required=True), 'last_name': fields.Str(required=True), 'email': fields.Str(required=True), } def get(self): """Return all the signature sheets in the db""" page = 1 per_page = 10 sheet = SignatureSheetModel.get_last_date() records = SignatureSheetModel.query.order_by( SignatureSheetModel.id_signature.desc()).limit(per_page).offset( (page - 1) * per_page) if records: return {'SignatureSheets': list(map(lambda x: x.json(), records))} return {'message': 'Nothing found'} @use_args(insert_sheet) def post(self, args): updated = args.get('updated', None) id_type = args.get('id_type', None) id_employee = args.get('id_employee', None) first_name = args.get('first_name', None) last_name = args.get('last_name', None) email = args.get('email', None) date = datetime.datetime.now() #data = SignatureSheets.parser.parse_args() if updated: sheet = SignatureSheetModel(updated, id_type, id_employee, first_name, last_name, email, 1, 1, "504-xxxx-xxxx") else: sheet = SignatureSheetModel(date, id_type, id_employee, first_name, last_name, email, 1, 1, "504-xxxx-xxxx") try: sheet.insert() return {'message': 'Signature Sheet correctly inserted'} except: return {'message': "something wrong probably item already exist"}
class DateAddHandler(BaseRequestHandler): """A date adder endpoint.""" dateadd_args = { 'value': fields.Date(required=False), 'addend': fields.Int(required=True, validate=validate.Range(min=1)), 'unit': fields.Str(missing='days', validate=validate.OneOf(['minutes', 'days'])) } @use_kwargs(dateadd_args) def post(self, value, addend, unit): """A date adder endpoint.""" value = value or dt.datetime.utcnow() if unit == 'minutes': delta = dt.timedelta(minutes=addend) else: delta = dt.timedelta(days=addend) result = value + delta self.write({'result': result.isoformat()})
class DateAddResource(Resource): dateadd_args = { "value": fields.Date(required=False), "addend": fields.Int(required=True, validate=validate.Range(min=1)), "unit": fields.Str( missing="days", validate=validate.OneOf(["minutes", "days"]) ), } @use_kwargs(dateadd_args) def post(self, value, addend, unit): """A date adder endpoint.""" value = value or dt.datetime.utcnow() if unit == "minutes": delta = dt.timedelta(minutes=addend) else: delta = dt.timedelta(days=addend) result = value + delta return {"result": result.isoformat()}
class DateAddResource(object): """A datetime adder endpoint.""" dateadd_args = { 'value': fields.Date(required=False), 'addend': fields.Int(required=True, validate=validate.Range(min=1)), 'unit': fields.Str(missing='days', validate=validate.OneOf(['minutes', 'days'])) } @falcon.before(add_args(dateadd_args)) def on_post(self, req, resp): """A datetime adder endpoint.""" args = req.context['args'] value = args['value'] or dt.datetime.utcnow() if args['unit'] == 'minutes': delta = dt.timedelta(minutes=args['addend']) else: delta = dt.timedelta(days=args['addend']) result = value + delta req.context['result'] = {'result': result.isoformat()}
class DateAddResource(object): """A datetime adder endpoint.""" dateadd_args = { "value": fields.Date(required=False), "addend": fields.Int(required=True, validate=validate.Range(min=1)), "unit": fields.Str( missing="days", validate=validate.OneOf(["minutes", "days"]) ), } @falcon.before(add_args(dateadd_args)) def on_post(self, req, resp): """A datetime adder endpoint.""" args = req.context["args"] value = args["value"] or dt.datetime.utcnow() if args["unit"] == "minutes": delta = dt.timedelta(minutes=args["addend"]) else: delta = dt.timedelta(days=args["addend"]) result = value + delta req.context["result"] = {"result": result.isoformat()}
class CurrentBalanceByDateEndpoint(Resource): get_args = {"Date": fields.Date()} insert_args = { "Date": fields.Date(), "CurrBal1": fields.Integer(), "CurrBal10": fields.Integer(), "CurrBal100": fields.Integer(), "CurrBal1000": fields.Integer(), "CurrBal10000": fields.Integer(), "CurrBal50000": fields.Integer(), "CurrBalGT50000": fields.Integer() } @use_kwargs(insert_args) def post(self, Date, CurrBal1=None, CurrBal10=None, CurrBal100=None, CurrBal1000=None, CurrBal10000=None, CurrBal50000=None, CurrBalGT50000=None): current_balance = CurrentBalance(date=Date, currbal1=CurrBal1, currbal10=CurrBal10, currbal100=CurrBal100, currbal1000=CurrBal1000, currbal10000=CurrBal10000, currbal50000=CurrBal50000, currbalgt50000=CurrBalGT50000) db_session.add(current_balance) try: db_session.commit() response = { "ResponseCode": ResponseCodes.Success.value, "ResponseDesc": ResponseCodes.Success.name, "CurrentBalance": serialize_current_balance(current_balance) } except SQLAlchemyError as e: print(str(e)) db_session.rollback() response = { "ResponseCode": ResponseCodes.InternalError.value, "ResponseDesc": ResponseCodes.InternalError.name, "ErrorMessage": ResponseDescriptions.ErrorFromDataBase.value } return response @use_kwargs(get_args) def get(self, Date=None): error = self.validateCurrentBalanceInput(Date) if error is not None: return { "ResponseCode": ResponseCodes.InvalidRequestParameter.value, "ResponseDesc": ResponseCodes.InvalidRequestParameter.name, "ErrorMessage": error.value } current_balance = db_session.query(CurrentBalance).filter( and_(CurrentBalance.date == Date)).one_or_none() if current_balance is None: response = { "ResponseCode": ResponseCodes.NoDataFound.value, "ResponseDesc": ResponseCodes.NoDataFound.name, "ErrorMessage": ResponseDescriptions.NoDataFound.value } else: response = { "ResponseCode": ResponseCodes.Success.value, "ResponseDesc": ResponseCodes.Success.name, "CurrentBalance": serialize_current_balance(current_balance) } return response def validateCurrentBalanceInput(self, date): error = None if date is None: error = ResponseDescriptions.DateInputMissing else: try: date.strftime('%Y-%m-%d') except ValueError: error = ResponseDescriptions.DateInputMissing return error
class RHStatsAPI(RH): """Provide statistics on daily visitors""" def _check_access(self): from indico_cern_access.plugin import CERNAccessPlugin auth = request.authorization username = CERNAccessPlugin.settings.get('api_username') password = CERNAccessPlugin.settings.get('api_password') if not auth or not auth.password or auth.username != username or auth.password != password: response = current_app.response_class( 'Authorization required', 401, { 'WWW-Authenticate': 'Basic realm="Indico - CERN Access Stats"' }) raise Unauthorized(response=response) def _get_stats(self, start_date, end_date): access_start = db.cast( db.func.coalesce( db.cast(Request.data['start_dt_override'].astext, UTCDateTime()), Event.start_dt).astimezone('Europe/Zurich'), db.Date) access_end = db.cast( db.func.coalesce( db.cast(Request.data['end_dt_override'].astext, UTCDateTime()), Event.end_dt).astimezone('Europe/Zurich'), db.Date) query = (db.session.query( access_start, access_end, db.func.count('*')).filter( CERNAccessRequest.request_state == CERNAccessRequestState. active).join(CERNAccessRequest.registration).join( Registration.event).join( Request, db.and_( Request.event_id == Event.id, Request.type == 'cern-access', Request.state == RequestState.accepted)).filter( _db_dates_overlap(access_start, access_end, start_date, end_date)).group_by( access_start, access_end)) counts = Counter() for start, end, count in query: for offset in range((end - start).days + 1): day = start + timedelta(days=offset) counts[day] += count return dict(counts) @use_args( { 'from': fields.Date(required=True), 'to': fields.Date(required=True), }, location='query') def _process(self, args): start_date = args['from'] end_date = args['to'] if start_date > end_date: abort(422, messages={'from': ['start date cannot be after end date']}) stats = self._get_stats(start_date, end_date) days = [ start_date + timedelta(days=offset) for offset in range((end_date - start_date).days + 1) ] data = {day.isoformat(): stats.get(day, 0) for day in days} return jsonify(data)
class Waskeys(Resource): get_args = { "id": fields.String(required=False, missing=None), "fromDateTime": fields.DateTime(required=False, missing=None), "active": fields.Boolean(required=False, missing=None), "name": fields.String(required=False, missing=None) } @use_kwargs(get_args) @require_headers def get(self, id, fromDateTime, active, name): if fromDateTime: result = [ washkey for washkey in washkeys if datetime.fromisoformat(washkey["CreatedTime"]) > fromDateTime ] elif active: result = [ washkey for washkey in washkeys if washkey["Active"] == active ] elif name: result = [ washkey for washkey in washkeys if name.lower() in washkey["Name"].lower() ] else: result = [ washkey for washkey in washkeys if not id or washkey["Id"] == id ] return result, 200 post_args = { "washKey": fields.Nested( { "id": fields.String(required=True), "credit": fields.Integer(required=True), "productrestriction": fields.Integer(required=False, missing=0), "name": fields.String(required=False, missing=""), "active": fields.Boolean(required=False, missing=True), "expiry": fields.Date(required=False, missing=None) }, location="json", required=True), "paymentType": fields.String(required=False, missing="", location="json") } @use_kwargs(post_args) @require_headers def post(self, washKey, paymentType): for washkey in washkeys: if washkey["Id"] == washKey["id"]: return "{ error : {errorCode : 40901, errorMessage : " "washkey already exists" "}", 409 washkey = { "Id": washKey["id"], "Name": washKey["name"], "Credit": washKey["credit"], "ProductRestriction": washKey["productrestriction"], "Active": washKey["active"], "Expiry": washKey["expiry"].isoformat(), "CreatedTime": datetime.utcnow().isoformat() } washkeys.append(washkey) return "{}", 200
display_name='enforcement matters') @app.route('/legal/statutes/') def statutes_landing(): return render_template('legal-statutes-landing.html', parent='legal', result_type='statutes', display_name='statutes') @app.route('/legal/search/advisory-opinions/') @use_kwargs({ 'query': fields.Str(load_from='search'), 'offset': fields.Int(missing=0), 'ao_no': fields.List(fields.Str, missing=None), 'ao_name': fields.List(fields.Str, missing=None), 'ao_min_date': fields.Date(missing=None), 'ao_max_date': fields.Date(missing=None), 'ao_is_pending': fields.Bool(missing=None), 'ao_requestor': fields.Str(missing=None), 'ao_requestor_type': fields.Int(missing=0), 'ao_category': fields.List(fields.Str, missing=None) }) def advisory_opinions(query, offset, ao_no=None, ao_name=None, ao_min_date=None, ao_max_date=None, ao_is_pending=None, ao_requestor=None, ao_requestor_type=None, ao_category=None): return legal_doc_search(query, 'advisory_opinions', offset=offset, ao_no=ao_no, ao_name=ao_name, ao_min_date=ao_min_date, ao_max_date=ao_max_date, ao_is_pending=ao_is_pending, ao_requestor=ao_requestor, ao_requestor_type=ao_requestor_type,
} committee_list = { 'q': fields.List(fields.Str, description=docs.COMMITTEE_NAME), 'committee_id': fields.List(IStr, description=docs.COMMITTEE_ID), 'candidate_id': fields.List(IStr, description=docs.CANDIDATE_ID), 'state': fields.List(IStr, description=docs.STATE_GENERIC), 'party': fields.List(IStr, description=docs.PARTY), 'min_first_file_date': fields.Date( description= 'Selects all committees whose first filing was received by the FEC after this date' ), 'max_first_file_date': fields.Date( description= 'Selects all committees whose first filing was received by the FEC before this date' ), 'treasurer_name': fields.List(fields.Str, description=docs.TREASURER_NAME), } committee_history = { 'election_full': election_full, } filings = {
user_profile = user.profile if user.profile else UserProfile( user=user).save() user_profile_json = { 'email': user.email, 'birthday': user_profile.birthday } return jsonify( snake_to_camel_case_dict({'user_profile': user_profile_json})) @profiles_api.route('/edit', methods=['PUT']) @use_converted_kwargs({ 'birthday': fields.Date(required=False), 'email': fields.Str(required=False), 'current_password': fields.Str(required=True), 'new_password': fields.Str(required=False), }) @require_authentication def edit_profile(user, email, current_password, new_password, birthday): """ Edit profile things. """ if not PasswordManager.context.verify(current_password, user.password_hash): raise exceptions.Unauthorized('Existing password was not correct.') user_profile = user.profile if user.profile else UserProfile(user=user)