class SubjectSchema(ma.Schema): name = fields.String()
def update_password_args(): """Defines and validates params for updating a password""" return { "reset_token": fields.String(required=True), "password": fields.String(required=True) }
from webargs import fields from flask_apispec import doc, use_kwargs, marshal_with from flask_jwt_extended import jwt_required # Import app code from app.main import app from app.api.api_v1.api_docs import docs, security_params from app.core import config from app.core.celery_app import celery_app # Import Schemas from app.schemas.msg import MsgSchema # Import models @docs.register @doc( description='Test Celery worker', security=security_params, tags=['utils'], ) @app.route(f'{config.API_V1_STR}/test-celery/', methods=['POST']) @use_kwargs({ 'word': fields.String(required=True), }) @marshal_with(MsgSchema()) @jwt_required def route_test_celery(word): celery_app.send_task('app.worker.test_celery', args=[word]) return ({'msg': 'Word received'}, 201)
def evaluation_args(): """Defines and validates suggested tags params""" return { "data": fields.List(fields.String(), missing=[]), }
class GetTransactionDataByDateAndTokenNameEndpoint(Resource): """ Class implementing get transaction data by date and token name API """ args = { "day": fields.Integer(), "month": fields.Integer(), "year": fields.Integer(), "date_offset": fields.Integer(), "token_name": fields.String() } @use_kwargs(args) def get(self, year, month, day, date_offset, token_name): """ Method for GET request :param year: :param month: :param day: :param date_offset: :param token_name: """ # Validate User Input try: request = { "day": day, "month": month, "year": year, "date_offset": date_offset, "token_name": token_name } validations_result = validate_input(year, month, day, date_offset) response = {} if validations_result is not None and len(validations_result) > 0: response = { "ResponseCode": ResponseCodes.InvalidRequestParameter.value, "ResponseDesc": ResponseCodes.InvalidRequestParameter.name, "ValidationErrors": validations_result } else: # all valid from_time = datetime(int(year), int(month), int(day)) to_time = from_time + timedelta(days=int(date_offset)) from_unixtime = time.mktime(from_time.timetuple( )) # get the unix time to form the query to_unixtime = time.mktime(to_time.timetuple()) token_data = db_session.query(EthereumToken).filter( EthereumToken.token_name == token_name).first() # perform the query transaction_data = db_session.query(Transaction).filter( and_(Transaction.ntime >= from_unixtime, Transaction.ntime <= to_unixtime)).order_by( Transaction.ntime.asc()) if transaction_data is not None and len( list(transaction_data)) != 0: transaction_list = [] for transaction in transaction_data: transaction_list.append( serialize_transaction(transaction)) response = { "ResponseCode": ResponseCodes.Success.value, "ResponseDesc": ResponseCodes.Success.name, "FromDate": from_time.strftime('%Y-%m-%d %H:%M:%S'), "ToDate": to_time.strftime('%Y-%m-%d %H:%M:%S'), "TokenId": token_data.token_id, "TokenName": token_data.token_name, "NumberOfTransactions": len(transaction_list), "Transactions": transaction_list } else: response = { "ResponseCode": ResponseCodes.NoDataFound.value, "ResponseDesc": ResponseCodes.NoDataFound.name, "ErrorMessage": ResponseDescriptions.NoDataFound.value } except Exception as ex: response = { "ResponseCode": ResponseCodes.InternalError.value, "ResponseDesc": ResponseCodes.InternalError.name, "ErrorMessage": str(ex) } finally: return response
def add_generation_routes(app, is_local, server_path): """ Create routes related to file generation Attributes: app: A Flask application is_local: A boolean flag indicating whether the application is being run locally or not server_path: A string containing the path to the server files (only applicable when run locally) """ @app.route("/v1/generate_file/", methods=["POST"]) @convert_to_submission_id @requires_submission_perms('writer') @use_kwargs({ 'file_type': webargs_fields.String(required=True, validate=webargs_validate.OneOf( ('D1', 'D2', 'E', 'F'), error="Must be either D1, D2, E or F")), 'start': webargs_fields.String(validate=webargs_validate.Regexp( DATE_REGEX, error="Must be in the format MM/DD/YYYY")), 'end': webargs_fields.String(validate=webargs_validate.Regexp( DATE_REGEX, error="Must be in the format MM/DD/YYYY")), 'agency_type': webargs_fields.String( missing='awarding', validate=webargs_validate.OneOf( ('awarding', 'funding'), error="Must be either awarding or funding if provided")), 'file_format': webargs_fields.String( missing='csv', validate=webargs_validate.OneOf( ('csv', 'txt'), error="Must be either csv or txt if provided")) }) def generate_file(submission_id, file_type, **kwargs): """ Kick of a file generation, or retrieve the cached version of the file. Attributes: submission: submission ID for which we're generating the file file_type: type of file to generate the job for start: the start date for the file to generate end: the end date for the file to generate agency_type: The type of agency (awarding or funding) to generate the file for file_format: determines if the file generated is a txt or a csv """ start = kwargs.get('start') end = kwargs.get('end') agency_type = kwargs.get('agency_type') file_format = kwargs.get('file_format') return generation_handler.generate_file(submission_id, file_type, start, end, agency_type, file_format) @app.route("/v1/check_generation_status/", methods=["GET"]) @convert_to_submission_id @requires_submission_perms('reader') @use_kwargs({ 'file_type': webargs_fields.String(required=True, validate=webargs_validate.OneOf( ('D1', 'D2', 'E', 'F'), error="Must be either D1, D2, E or F")) }) def check_generation_status(submission, file_type): """ Return status of file generation job Attributes: submission: submission for which we're generating the file file_type: type of file to check the status of """ return generation_handler.check_generation(submission, file_type) @app.route("/v1/generate_detached_file/", methods=["POST"]) @requires_login @use_kwargs({ 'file_type': webargs_fields.String(required=True, validate=webargs_validate.OneOf( ('A', 'D1', 'D2'))), 'cgac_code': webargs_fields.String(), 'frec_code': webargs_fields.String(), 'start': webargs_fields.String(), 'end': webargs_fields.String(), 'year': webargs_fields.Int(), 'period': webargs_fields.Int(validate=webargs_validate.OneOf( list(range(2, 13)), error="Period must be an integer 2-12.")), 'agency_type': webargs_fields.String( missing='awarding', validate=webargs_validate.OneOf( ('awarding', 'funding'), error="Must be either awarding or funding if provided")), 'file_format': webargs_fields.String( missing='csv', validate=webargs_validate.OneOf( ('csv', 'txt'), error="Must be either csv or txt if provided")), 'element_numbers': webargs_fields.Bool(missing=False), }) def generate_detached_file(file_type, **kwargs): """ Generate a file from external API, independent from a submission Attributes: file_type: type of file to be generated cgac_code: the code of a CGAC agency if generating for a CGAC agency frec_code: the code of a FREC agency if generating for a FREC agency start: start date in a string, formatted MM/DD/YYYY end: end date in a string, formatted MM/DD/YYYY year: integer indicating the year to generate for (YYYY) period: integer indicating the period to generate for (2-12) agency_type: The type of agency (awarding or funding) to generate the file for file_format: determines if the file generated is a txt or a csv """ cgac_code = kwargs.get('cgac_code') frec_code = kwargs.get('frec_code') start = kwargs.get('start') end = kwargs.get('end') year = kwargs.get('year') period = kwargs.get('period') agency_type = kwargs.get('agency_type') file_format = kwargs.get('file_format') element_numbers = kwargs.get('element_numbers') return generation_handler.generate_detached_file( file_type, cgac_code, frec_code, start, end, year, period, agency_type, file_format, element_numbers) @app.route("/v1/check_detached_generation_status/", methods=["GET"]) @requires_login @use_kwargs({'job_id': webargs_fields.Int(required=True)}) def check_detached_generation_status(job_id): """ Return status of file generation job """ return generation_handler.check_detached_generation(job_id)
@login_required def edit(id): taxon = Taxon.query \ .options(orm.joinedload('vernacular_names')) \ .get_or_404(id) geographies = Geography.query.all() return resource.render_html(taxon=taxon, geographies=geographies, form=TaxonForm(obj=taxon)) @resource.destroy @login_required def destroy(id): taxon = Taxon.query.get_or_404(id) db.session.delete(taxon) db.session.commit() return '', 204 @resource.route("/<int:id>/count") @login_required @use_args({'relation': fields.DelimitedList(fields.String(), required=True)}) def taxon_count(args, id): data = {} taxon = Taxon.query.get_or_404(id) for relation in args['relation']: _, base = relation.rsplit('/', 1) data[base] = utils.count_relation(taxon, relation) return utils.json_response(data)
def _update_viewarg(self, name, choices): ''' Updates the global View arguments validator ''' viewargs[name] = fields.String(required=True, location='view_args', validate=validate.OneOf(choices))
class ShopTagSchema(ma.ModelSchema): name = fields.String() @post_dump def flatten(self, data): return data['name']
from project.api.common.decorators import login_required, admin_required from project.api.common.utils import make_response bp_supplier_user_info = Blueprint('supplier_user_info', __name__) supplier_user_info_schema = SupplierUserInfoSchema() supplier_user_infos_schema = SupplierUserInfoSchema(many=True) supplier_user_info_args = { 'id': fields.Integer(required=True, location='view_args') } save_args = { 'supplier_id': fields.Integer(required=True), 'jojo_number': fields.String(required=False), 'payment_type_id': fields.Integer(required=False), 'reimbursement_type_id': fields.Integer(required=False), } @bp_supplier_user_info.route('/', methods=['PUT']) @admin_required @use_args(save_args) def add_or_update_supplier_user_info(args): """Private""" supplier_user_info = SupplierUserInfo.query.filter_by( user_id=g.user_id, supplier_id=args['supplier_id']).first() if not supplier_user_info: supplier_user_info = SupplierUserInfo(**{ **args,
from marvin.core.exceptions import MarvinError from marvin.utils.datamodel.dap import datamodel as dm from marvin.utils.general import validate_jwt def plate_in_range(val): if int(val) < 6500: raise ValidationError('Plateid must be > 6500') # List of global View arguments across all API routes viewargs = { 'name': fields.String( required=True, location='view_args', validate=[validate.Length(min=4), validate.Regexp('^[0-9-]*$')]), 'galid': fields.String( required=True, location='view_args', validate=[validate.Length(min=4), validate.Regexp('^[0-9-]*$')]), 'bintype': fields.String(required=True, location='view_args'), 'template': fields.String(required=True, location='view_args'), 'property_name': fields.String(required=True, location='view_args'), 'channel':
from project import db from project.api.models import ContactPerson, Customer from project.api.schemas import ContactPersonSchema from project.api.common.decorators import login_required from project.api.common.utils import make_response bp_contact_person = Blueprint('contact_person', __name__) contact_person_schema = ContactPersonSchema() contact_persons_schema = ContactPersonSchema(many=True) args = {'id': fields.Integer(required=True, contact_person='view_args')} save_args = { 'firstname': fields.String(50, required=True), 'lastname': fields.String(50, required=True), 'title': fields.String(50), 'customer_id': fields.Integer(required=True) } @bp_contact_person.route('/<id>', methods=['GET']) @login_required @use_args(args) def get_contact_person_detail(args, id): contact_person = ContactPerson.query.get(id) if not contact_person: return make_response(status_code=404, status='failure', message='No contact person found with that id')
class AuthorSchema(ma.Schema): name = fields.String(dump_only=True) birth_year = fields.String(dump_only=True) death_year = fields.String(dump_only=True)
class LanguageSchema(ma.Schema): code = fields.String(dump_only=True)
class SuperShopPayVerifyView(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"), "payment_status": fields.Integer( required=True, validate=[ validate.OneOf([ ShopPayActive.YES, ShopPayActive.CHECKING, ShopPayActive.REJECTED, ]) ], comment="认证状态", ), "lc_merchant_no": fields.String(required=False, validate=[validate.Length(0, 15)], comment="商户号"), "lc_terminal_id": fields.String(required=False, validate=[validate.Length(0, 50)], comment="终端号"), "lc_access_token": fields.String( required=False, validate=[validate.Length(0, 32)], comment="扫呗access_token", ), }, location="json") @SuperBaseView.validate_sign("sign", ("user_id", "timestamp")) def post(self, request, args): shop = get_shop_by_shop_id(args.get("shop_id")) if not shop: return self.send_fail(error_text="店铺不存在") payment_status = args.get("payment_status") if shop.pay_active == payment_status: text = ( "正在审核中" if payment_status == ShopPayActive.CHECKING else "已通过审核" if payment_status == ShopPayActive.YES else "已拒绝审核") return self.send_fail(error_text="该店铺%s, 请不要重复操作" % text) shop.pay_active = payment_status # 创建paychannel if shop.pay_active == ShopPayActive.YES: pay_channel_info = { "smerchant_no": args.get("lc_merchant_no"), "terminal_id1": args.get("lc_terminal_id"), "access_token": args.get("lc_access_token"), "channel_type": ShopPayChannelType.LCSW, } serializer = ShopPayChannelSerializer(data=pay_channel_info, context={"shop": shop}) if serializer.is_valid(): return self.send_error(error_message=serializer.errors, status_code=status.HTTP_400_BAD_REQUEST) serializer.save() return self.send_success()
# -*- coding: utf-8 -*- # Import installed modules # Import installed packages from webargs import fields from flask_apispec import doc, use_kwargs, marshal_with from flask_jwt_extended import jwt_required # Import app code from app.main import app from app.api.api_v1.api_docs import docs, security_params from app.core import config from app.core.celery_app import celery_app # Import Schemas from app.schemas.msg import MsgSchema # Import models @docs.register @doc(description="Test Celery worker", security=security_params, tags=["utils"]) @app.route(f"{config.API_V1_STR}/test-celery/", methods=["POST"]) @use_kwargs({"word": fields.String(required=True)}) @marshal_with(MsgSchema()) @jwt_required def route_test_celery(word): celery_app.send_task("app.worker.test_celery", args=[word]) return ({"msg": "Word received"}, 201)
class SuperShopView(SuperBaseView): """总后台-商铺-商铺创建&商铺详情""" @use_args( { "sign": fields.String(required=True, comment="加密认证"), "timestamp": fields.Integer(required=True, comment="时间戳"), "user_id": fields.Integer(required=True, comment="用户ID"), "shop_name": fields.String(required=True, validate=[validate.Length(0, 128)], comment="店铺名"), "shop_img": fields.String( required=True, validate=[validate.Length(0, 300)], comment="店铺logo", ), "shop_province": fields.Integer(required=True, comment="省份编码"), "shop_city": fields.Integer(required=True, comment="城市编码"), "shop_county": fields.Integer(required=True, comment="区份编码"), "shop_address": fields.String( required=True, validate=[validate.Length(0, 100)], comment="详细地址", ), "description": fields.String(required=True, validate=[validate.Length(0, 200)], comment="描述"), "inviter_phone": fields.String( required=False, validate=[validate.Length(0, 32)], comment="推荐人手机号", ), "longitude": fields.Decimal( required=False, data_key="lng", allow_none=True, validate=[validate.Range(-180, 180)], comment="经度", ), "latitude": fields.Decimal( required=False, data_key="lat", allow_none=True, validate=[validate.Range(-90, 90)], comment="纬度", ), "realname": fields.String( required=False, allow_none=True, validate=[validate.Length(0, 32)], comment="历史真实姓名", ), }, location="json", ) @SuperBaseView.validate_sign("sign", ("user_id", "timestamp")) def post(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 = ShopCreateSerializer(data=args, context={'user': user}) 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(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"), "shop_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": "用户未登录"}) shop_id = args.get("shop_id") shop = get_shop_by_shop_id(shop_id) if not shop: return self.send_fail(error_text="店铺不存在") shop = get_shop_by_shop_id(shop_id) super_admin_data = get_user_by_id_interface(shop.super_admin.id) shop.super_admin_data = super_admin_data serializer = SuperShopSerializer(shop) return self.send_success(data=serializer.data)
class ComputerList(Resource): request_args = { 'room': fields.String(), 'detailed_response': fields.Bool() } ## GET method endpoint @use_args(request_args) def get(self, args): if 'room' in args: print(args['room']) if args['room'] != 'Not Set' and args['room'] != 'not set': ## Check the room exists room = Room.query.filter_by(room_name=args['room']).first() if room is None: abort(404, message="Room not found") ## Get a list of all our machines computers = Computer.query.all() computerArray = [] if computers is not None: now = datetime.now() for computer in computers: computer.updateStatus(now) if args['room'] == 'Not Set' or args['room'] == 'not set': ## If the detailed response flag is present if 'detailed_response' in args: ## Check if the response wants full details or trimmed responses if args['detailed_response'] == True: computerArray.append(computer.serialize) else: computerArray.append( computer.trimmed_serialize) else: computerArray.append(computer.trimmed_serialize) else: if computer.room_name == args['room']: ## If the detailed response flag is present if 'detailed_response' in args: ## Check if the response wants full details or trimmed responses if args['detailed_response'] == True: computerArray.append(computer.serialize) else: computerArray.append( computer.trimmed_serialize) else: computerArray.append( computer.trimmed_serialize) db.session.commit() ## Generate our response response = { "meta": {}, "links": { "self": request.url }, "data": { "computers": computerArray } } return jsonify(response) else: ## Get a list of all our machines computers = Computer.query.all() computersArray = [] ## Check we found any computers if computers is not None: now = datetime.now() for computer in computers: computer.updateStatus(now) db.session.commit() computerArray = [] ## Check if the response wants full details or trimmed responses if 'detailed_response' in args: ## Check if the response wants full details or trimmed responses if args['detailed_response'] == True: computerArray = [ computer.serialize for computer in computers ] else: computerArray = [ computer.trimmed_serialize for computer in computers ] else: computerArray = [ computer.trimmed_serialize for computer in computers ] ## Generate our response response = { "meta": {}, "links": { "self": request.url }, "data": { "computers": computerArray } } return jsonify(response)
participant_set_id = None participant = Participant.query.join( Participant.participant_set).filter( ParticipantSet.id == participant_set_id, ParticipantSet.deployment_id == deployment_id, Participant.id == participant_id, Participant.participant_set_id == ParticipantSet.id).first_or_404() return participant @use_kwargs({ 'event_id': fields.Int(), 'q': fields.String() }, locations=['query']) class ParticipantListResource(BaseListResource): schema = ParticipantSchema() def get_items(self, **kwargs): event_id = kwargs.get('event_id') lookup_item = kwargs.get('q') deployment = getattr(g, 'deployment', None) if event_id is None: event = getattr(g, 'event', None) else: event = Event.query.filter_by(id=event_id).one()
from flask import jsonify from webargs import fields from webargs.flaskparser import use_args from src.blueprints import host from src.core import database, helpers from src.core.auth_helpers import authorize_route @host.get("/") @use_args( { "uid": fields.String(missing=""), "handle": fields.String(missing=""), "all": fields.Boolean(), }, location="query", ) def get(args: dict): """Get a Host by their Twitter ID or handle.""" # Return a list of all Hosts if "all" in args and args["all"]: return helpers.make_response(200, jsonify(database.host.get_all())) # We need something to search by if not args["uid"] and not args["handle"]: return helpers.make_error_response( 422, "Either a Host id or handle must be provided!") # Both a host ID and handle cannot be provided
@app.route('/') def home(): return json_response(data={'hostname': app.config['HOSTNAME']}) @app.route('/v1/orders/', methods=['GET']) @auth_context() def get_orders(ctx: AuthContext): return json_response(data=GetOrdersStory().execute(ctx)) @app.route('/v1/orders/', methods=['POST']) @use_kwargs( { 'total_price': fields.String(required=True), 'if_match': fields.Int(required=True), }, location='form') @auth_context() def create_order(total_price, ctx: AuthContext, if_match: int): try: schema = order_store_schema(OrderSaga().create(total_price, ctx, if_match)) return json_response(data=schema) except StoreValidation as e: raise BadRequest(message=str(e)) @app.route('/health') def health():
class MediaList(Resource): "MediaList resource" args_required = { 'category': fields.String( required=True, error_messages={"required": "Media category cannot be blank"}), } args_optional = { 'category': fields.String(required=False), } # GET @swagger.operation(notes='Get a media list you may use category as filter', responseClass=[MediaModel.__name__], nickname='get', parameters=[ { "name": "category", "description": "Media category", "required": False, "allowMultiple": False, "dataType": "string", "paramType": "query" }, ], responseMessages=[{ "code": 200, "message": "Media(s) found" }, { "code": 404, "message": "Media(s) not found" }]) @use_args(args_optional) def get(self, args): medias = MediaModel.find(**args) if medias: mediasJSON = [] for media in medias: mediasJSON.append(media.json()) return {"medias": mediasJSON}, 200 # OK else: return {"message": "Media not found"}, 404 #not found # POST @swagger.operation(notes='Insert a media, category is required', responseClass=[MediaModel.__name__], nickname='post', parameters=[ { "name": "category", "description": "Media category", "required": True, "allowMultiple": False, "dataType": "string", "paramType": "form" }, ], responseMessages=[{ "code": 201, "message": "Media inserted" }, { "code": 400, "message": "Media already exists" }]) @use_args(args_required) def post(self, args): if MediaModel.find_by_category(args['category']): return { "message": "this media {} already exists".format(args['category']) }, 400 media = MediaModel(**args) # media = MediaModel(data['name']) # for each of the keys in data say key = value # ie name = value media.save_to_db() return { "message": "media {} created successfully".format(args['category']) }, 201 # created
fields.Nested({ 'lat': fields.Float(), 'lng': fields.Float() }, required=True), 'south_west': fields.Nested({ 'lat': fields.Float(), 'lng': fields.Float() }, required=True) }, required=True) } _create_args = dict(_base_args, **{'name': fields.String(required=True)}) _update_args = { 'areas': fields.List( fields.Nested(dict( _base_args, **{ 'id': fields.Int(required=True), 'name': fields.String() }), required=True)) } class RHMapAreas(RHRoomBookingAdminBase): @use_args(_create_args)
class Media(Resource): "Media resource" args_required = { 'category': fields.String( required=True, error_messages={"required": "Media category cannot be blank"}), } # GET @swagger.operation(notes='Get a media item by ID', responseClass=MediaModel.__name__, nickname='get', parameters=[{ "name": "_id", "description": "Media id", "required": True, "allowMultiple": False, "dataType": "integer", "paramType": "path" }], responseMessages=[{ "code": 200, "message": "Media found" }, { "code": 404, "message": "Media not found" }]) #@jwt_required() def get(self, _id): media = MediaModel.find_by_id(_id) if media: return media.json(), 200 else: return {"message": "Media not found"}, 404 # DELETE @swagger.operation(notes='Delete a media item by id', responseClass=MediaModel.__name__, nickname='delete', parameters=[{ "name": "_id", "description": "Media id", "required": True, "allowMultiple": False, "dataType": "integer", "paramType": "path" }], responseMessages=[{ "code": 200, "message": "Media deleted" }, { "code": 404, "message": "Media to delete not found" }]) def delete(self, _id): media = MediaModel.find_by_id(_id) if media: media.delete_from_db() return {'message': "media {} has been deleted".format(_id)}, 200 return {'message': "No media {} to delete".format(_id)}, 200 # PUT @swagger.operation(notes='Update a media, id is required', responseClass=[MediaModel.__name__], nickname='put', parameters=[ { "name": "_id", "description": "Media id", "required": True, "allowMultiple": False, "dataType": "integer", "paramType": "path" }, { "name": "category", "description": "Media category", "required": True, "allowMultiple": False, "dataType": "string", "paramType": "form" }, ], responseMessages=[{ "code": 200, "message": "Media updated" }, { "code": 400, "message": "Media to update not found" }]) @use_args(args_required) def put(self, args, _id): if MediaModel.find_by_category(args['category']): return { "message": "Media category {} already exists".format(args['category']) }, 400 # category exists media = MediaModel.find_by_id(_id) if media: media.category = args['category'] media.save_to_db() return { "message": "Media category {} has been updated".format(_id) }, 200 return { "message": "Media id {} doesn't exists".format(_id) }, 400 # media to update not found
if not prompts: return helpers.make_error_response( 404, f"No prompt exists for date {date}!") # Find out if we have a Prompt for the surrounding days for day_prompt in prompts: day_prompt["previous"] = prompt_exists(day_prompt.date, "previous") day_prompt["next"] = prompt_exists(day_prompt.date, "next") return jsonify(prompts) @authorize_route @prompt.post("/") @use_args( { "id": fields.String(required=True), "uid": fields.String(required=True), "date": fields.DateTime(required=True), "word": fields.String(required=True), "content": fields.String(required=True), "media": fields.String(missing=None, allow_none=True), "media_alt_text": fields.String(missing=None, allow_none=True), "is_duplicate_date": fields.Boolean(required=False, missing=False), }, location="json", ) def post(args: dict): """Create a new Prompt.""" # Format the date in the proper format before writing args["date"] = helpers.format_datetime_ymd(args["date"])
# Media files @api_blueprint.route("/media/<string:handle>/file") @jwt_required_ifauth def download_file(handle): """Download a file.""" base_dir = current_app.config.get("MEDIA_BASE_DIR") handler = LocalFileHandler(handle, base_dir) return handler.send_file() # Thumbnails @api_blueprint.route("/media/<string:handle>/thumbnail/<int:size>") @jwt_required_ifauth @use_args( {"square": fields.Boolean(missing=False), "jwt": fields.String(required=False)}, location="query", ) @thumbnail_cache.cached(make_cache_key=make_cache_key_thumbnails) def get_thumbnail(args, handle, size): """Get a file's thumbnail.""" base_dir = current_app.config.get("MEDIA_BASE_DIR") handler = LocalFileHandler(handle, base_dir) return handler.send_thumbnail(size=size, square=args["square"]) @api_blueprint.route( "/media/<string:handle>/cropped/<int:x1>/<int:y1>/<int:x2>/<int:y2>" ) @jwt_required_ifauth @use_args(
def send_reset_link_args(): """Defines and validates params for sending a password reset link""" return { "email_or_username": fields.String(required=True), "base_url": fields.URL(required=True) }
class SuperShopStatusView(UserBaseView): """总后台-通过shop_status查询所有的店铺&修改店铺的shop_status""" pagination_class = StandardResultsSetPagination # 弄个假的操作人信息 class Operator: operate_id = 1 operate_name = "" operate_img = "" @use_args( { "sign": fields.String(required=True, comment="加密认证"), "timestamp": fields.Integer(required=True, comment="时间戳"), "user_id": fields.Integer(required=True, comment="用户ID"), "shop_status": fields.Integer( required=True, validate=[ validate.OneOf([ ShopStatus.CHECKING, ShopStatus.NORMAL, ShopStatus.REJECTED ]) ], comment="店铺状态", ), }, location="query") @SuperBaseView.validate_sign("sign", ("user_id", "timestamp")) def get(self, request, args): shop_status = args.get("shop_status") shop_list = list_shop_by_shop_status(shop_status) # 店铺创建者信息, 与店铺ID creator_ids = set() shop_ids = set() for slq in shop_list: creator_ids.add(slq.super_admin_id) shop_ids.add(slq.id) creator_ids = list(creator_ids) shop_ids = list(shop_ids) # 店铺创建者 creator_list = list_user_by_ids_interface(creator_ids) creator_id_2_creator = {clq.id: clq for clq in creator_list} # 历史真实姓名 shop_realname_list = list_shop_creator_history_realname(shop_ids) shop_realname_map = { srl.id: srl.realname for srl in shop_realname_list } if shop_status == ShopStatus.CHECKING: for slq in shop_list: slq.creator = creator_id_2_creator.get(slq.super_admin_id) slq.current_realname = shop_realname_map.get(slq.id, "") elif shop_status == ShopStatus.NORMAL: for slq in shop_list: slq.creator = creator_id_2_creator.get(slq.super_admin_id) slq.current_realname = shop_realname_map.get(slq.id, "") slq.operator = self.Operator else: reject_reason_list = list_shop_reject_reason(shop_ids) shop_id_2_reject_reason = { rrl.id: rrl.reject_reason for rrl in reject_reason_list } for slq in shop_list: slq.creator = creator_id_2_creator.get(slq.super_admin_id) slq.current_realname = shop_realname_map.get(slq.id, "") slq.operator = self.Operator slq.reject_reason = shop_id_2_reject_reason.get(slq.id, "") shop_list = self._get_paginated_data(shop_list, SuperShopStatusSerializer) return self.send_success(data_list=shop_list) @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(0)], comment="店铺ID"), "shop_status": fields.Integer( required=True, validate=[ validate.OneOf([ShopStatus.NORMAL, ShopStatus.REJECTED]) ], comment="店铺状态", ), "reject_reason": fields.String( required=False, missing="", validate=[validate.Length(0, 200)], comment="拒绝理由,尽在拒绝的时候需要", ), }, location="json", ) @SuperBaseView.validate_sign("sign", ("user_id", "timestamp")) def put(self, request, args): shop_id = args.pop("shop_id") shop = get_shop_by_shop_id(shop_id) if not shop: return self.send_fail(error_text="店铺不存在") # 更改店铺状态 serializer = SuperShopStatusSerializer(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()
class BookingHandler(Resource): get_and_delete_args = { 'id': fields.Integer(required=True) } post_args = { 'timetable': fields.String(required=True), 'name': fields.String(required=True), 'start': fields.DateTime(required=True), 'end': fields.DateTime(required=True), 'colour': fields.String(required=True) } put_args = { 'id': fields.Integer(required=True), 'name': fields.String(), 'colour': fields.String() } @use_args(get_and_delete_args) def get(self, args): ## Get the booking with the supplied id, thats on the chosen timetable booking = Booking.query.filter_by(identifier=args['id']).first() ## Check we found the booking if booking is None: abort(404, message="Booking not found") ## Return the bookings information response = { "meta": {}, "links": { "self": request.url }, "data": { "booking": booking.serialize } } return jsonify(response) @use_args(post_args) def post(self, args): ## Check if the Timetable already exists timetable = Timetable.query.filter_by(name=args['timetable']).first() if timetable is None: abort(404, message='Timetable not found') ## Check the start date and end date of the session is the same if args['start'].date() != args['end'].date(): abort(422, message="Start and End date must match") ## Check the end time is after the start time if args['start'].time() >= args['end'].time(): abort(422, message="The session must end after its start time") ## Strip timezone data if its present args['start'] = args['start'].replace(tzinfo=None) args['end'] = args['end'].replace(tzinfo=None) ## Conflict check isConflicting = timetable.checkBookingConflict(args['start'], args['end']) if isConflicting: abort(422, message="Booking Conflict, A sessions already exists at this time") ## Parse the parameters to a dictionary for SQLAlchemy bookingData = {} bookingData['name'] = args['name'] bookingData['start'] = args['start'] bookingData['end'] = args['end'] bookingData['cell_colour'] = args['colour'] ## Create the booking object booking = Booking(**bookingData) booking.timetable_id = timetable.identifier ## Set the bookings timetable to the found supplied one db.session.add(booking) db.session.commit() return "", 201 @use_args(put_args) def put(self, args): ## Check the booking exists booking = Booking.query.filter_by(identifier=args['id']).first() if booking is None: abort(404, message='Booking not found') ## Update the supplied fields if 'name' in args: booking.name = args['name'] if 'colour' in args: booking.cell_colour = args['colour'] ## Commit to database booking.updated_at = datetime.now() db.session.commit() return "", 202 @use_args(get_and_delete_args) def delete(self, args): booking = Booking.query.filter_by(identifier=args['id']).first() if booking is None: abort(404, message='Booking not found') ## Execute the delete db.session.delete(booking) db.session.commit() return "", 202
class BookShelfSchema(ma.Schema): name = fields.String()