示例#1
0
    def __init__(
        self: object,
        host: str,
        port: int,
        character_domain: CharacterManagementInterface,
        dataset_domain: DatasetManagementInterface,
        garment_domain: GarmentManagementInterface,
        debug: bool = False,
    ) -> object:
        logging.debug("FlaskApplication.__init__")
        self.app = Flask(__name__)
        self.api = Api(self.app)
        self.host = host
        self.port = port
        self.debug = debug
        self.character_domain = character_domain
        self.dataset_domain = dataset_domain
        self.garment_domain = garment_domain

        # Character namespace
        character_namespace = Namespace("character")
        character_namespace.add_resource(
            CharacterHandler,
            "",
            resource_class_kwargs={"domain": character_domain})
        self.api.add_namespace(character_namespace,
                               path="/characters/<uuid:character_id>")
        # Characters namespace
        characters_namespace = Namespace("characters")
        characters_namespace.add_resource(
            CharactersHandler,
            "",
            resource_class_kwargs={"domain": character_domain})
        self.api.add_namespace(characters_namespace, path="/characters")
        # Datasets namespace
        datasets_namespace = Namespace("datasets")
        datasets_namespace.add_resource(
            DatasetsHandler,
            "",
            resource_class_kwargs={"domain": dataset_domain})
        self.api.add_namespace(datasets_namespace, path="/datasets")
        # Garment namespace
        garment_namespace = Namespace("garment")
        garment_namespace.add_resource(
            GarmentHandler,
            "",
            resource_class_kwargs={"domain": garment_domain})
        self.api.add_namespace(garment_namespace,
                               path="/clothes/<uuid:garment_id>")
        # Clothes namespace
        clothes_namespace = Namespace("clothes")
        clothes_namespace.add_resource(
            ClothesHandler,
            "",
            resource_class_kwargs={"domain": garment_domain})
        self.api.add_namespace(clothes_namespace, path="/clothes")
示例#2
0
def initialize(graph):
    api = Namespace('ingestor', description='Ingestor API')
    api.add_resource(
        Prometheus,
        '/prometheus',
        resource_class_args=[prometheus.AlertHandler.create(graph)])
    api.add_resource(Falco,
                     '/falco',
                     resource_class_args=[falco.AlertHandler.create(graph)])
    api.add_resource(
        Elastalert,
        '/elastalert',
        resource_class_args=[elastalert.AlertHandler.create(graph)])
    return api
示例#3
0
        """get a ride(passenger)"""

        response = rides.get_ride(ride_id=ride_id)
        return response


class RequestRide(Resource):
    """Contain PATCH method"""
    @api.expect(request_model)
    @api.doc(security='apikey')
    @token_required
    def post(self, ride_id):
        """Request ride"""
        parser = reqparse.RequestParser()
        parser.add_argument('pickup_point',
                            required=True,
                            type=str,
                            help='Pickup_point is required',
                            location=['json'])

        args = parser.parse_args()
        pickup_point = args['pickup_point']

        res = rides.request_ride(ride_id=ride_id, pickup_point=pickup_point)
        return res


api.add_resource(RideList, '/rides', endpoint='ridelist')
api.add_resource(Ride, '/rides/<int:ride_id>')
api.add_resource(RequestRide, '/users/rides/<int:ride_id>/request')
示例#4
0
            all_repositories = github_repositories + bit_bucket_repositories

            profile = self.aggregate_data(all_repositories)

            # Retrieve user followers
            followers = self.get_followers_count(username)
            profile["followers"] = len(followers)

            return jsonify(profile)
        except Exception as e:
            return jsonify({"message": "There is not network connetion"})

    def get_followers_count(self, username=''):
        """
        Retrieves user github followers

        Parameters:
          username (str): name of the user, organization or team

        Returns:
          followers(list): A list dict objects containing details of each
              follower
        """
        followers = requests.get(
            '{}/{}/followers'.format(GITHUB_URL, username)).json()

        return followers


api.add_resource(Profile, '/profile')
示例#5
0
                }).first()
            if cur_parent_event:  # if found update the deleted field of the sub_event
                received_data = {'deleted': True}
                result = update_sub_event(received_data, cur_parent_event,
                                          objectid.ObjectId(event_id))
                logging.debug("Edited sub_event deleted")
            else:
                abort(404)
        elif rec_id:  # if this is a sub_event of a recurring event that has not been created yet
            sub_event_dummy = placeholder_recurring_creation(
                rec_id, [], result, True)
            sub_event_dummy['deleted'] = True
            # create a sub_event with the deleted field set to true
            create_sub_event(sub_event_dummy, result)
            logging.debug("Deleted sub_event for the first time")
        else:  # if a normal event is to be deleted
            received_data = request_to_dict(request)
            logging.debug("Received DELETE data: %s", received_data)
            result.delete()
            return mongo_to_dict(result)


api.add_resource(EventApi, '/', methods=['GET', 'POST'], endpoint='event')
api.add_resource(EventApi,
                 '/<string:event_id>',
                 methods=['GET', 'PUT', 'PATCH', 'DELETE'],
                 endpoint='event_id')
# api.add_resource(EventApi, '/<string:event_id>/<string:rec_id>',
#                  methods=['GET', 'PUT', 'PATCH', 'DELETE'],
#                  endpoint='rec_id')  # TODO: add route for string/gphycat links
示例#6
0
            if not is_localized(execution_date):
                execution_date = execution_date.replace(tzinfo=timezone.utc)
        except ValueError:
            abort(
                BAD_REQUEST_RESPONSE_CODE,
                "Couldn't parse execution date: {execution_date}".format(
                    execution_date=api.payload[DAG_RUN_EXECUTION_DATE_KEY]
                )
            )

        dag_id = api.payload[DAG_ID_KEY]
        if check_for_dag_id(dag_id) is None:
            abort(NOT_FOUND_RESPONSE_CODE, message=DAG_NOT_FOUND_MESSAGE)
        try:
            dr = trigger_dag(
                dag_id=dag_id,
                execution_date=execution_date
            )
            response_data = _process_dag_run_to_response_object(dr)
            return Response(
                json.dumps(response_data),
                status=POST_RESPONSE_SUCCESS_CODE,
                mimetype=JSON_MIME_TYPE
            )
        except DagRunAlreadyExists:
            abort(CONFLICT_RESPONSE_CODE, DAG_RUN_CONFLICT_MESSAGE)


dag_runs.add_resource(PostDagRun, '')
dag_runs.add_resource(GetDagRun, '/<string:dag_run_id>')
示例#7
0
    @users_namespace.response(404, "User <user_id> does not exist")
    def put(self, user_id):
        """Updates a user."""
        post_data = request.get_json()
        username = post_data.get("username")
        email = post_data.get("email")
        response_object = {}

        user = get_user_by_id(user_id)
        if not user:
            users_namespace.abort(404, f"User {user_id} does not exist")
        update_user(user, username, email)
        response_object["message"] = f"{user.id} was updated!"
        return response_object, 200

    @users_namespace.response(200, "<user_id> was removed!")
    @users_namespace.response(404, "User <user_id> does not exist")
    def delete(self, user_id):
        """Updates a user."""
        response_object = {}
        user = get_user_by_id(user_id)
        if not user:
            users_namespace.abort(404, f"User {user_id} does not exist")
        delete_user(user)
        response_object["message"] = f"{user.email} was removed!"
        return response_object, 200


users_namespace.add_resource(UsersList, "")
users_namespace.add_resource(Users, "/<int:user_id>")
示例#8
0
文件: mines.py 项目: jlaplante333/mds
from ..mine.resources.mine_type import MineTypeResource
from ..mine.resources.mine_type_detail import MineTypeDetailResource
from ..mine.resources.mine_tenure_type_code import MineTenureTypeCodeResource
from ..mine.resources.mine_disturbance_code import MineDisturbanceCodeResource
from ..mine.resources.mine_commodity_code import MineCommodityCodeResource
from ..location.resources.location import MineLocationResource
from ..status.resources.status import MineStatusResource
from ..region.resources.region import MineRegionResource
from ..tailings.resources.tailings import MineTailingsStorageFacilityResource
from ..compliance.resources.compliance import MineComplianceResource
from ..mine.resources.mine_basicinfo import MineBasicInfoResource
from app.api.mines.mine.resources.mine_verified_status import MineVerifiedStatusResource

api = Namespace('mines', description='Mine related operations')

api.add_resource(MineResource, '', '/<string:mine_no_or_guid>')
api.add_resource(MineListSearch, '/search')
api.add_resource(MineTenureTypeCodeResource, '/mine-tenure-type-codes')
api.add_resource(MineDisturbanceCodeResource, '/disturbance-codes')
api.add_resource(MineCommodityCodeResource, '/commodity-codes')
api.add_resource(MineLocationResource, '/location',
                 '/location/<string:mine_location_guid>')
api.add_resource(MineStatusResource, '/status',
                 '/status/<string:mine_status_guid>')
api.add_resource(MineRegionResource, '/region',
                 '/region/<string:mine_region_guid>')
api.add_resource(MineTailingsStorageFacilityResource, '/tailings',
                 '/tailings/<string:mine_tailings_storage_facility_guid>')
api.add_resource(MineComplianceResource, '/compliance',
                 '/compliance/<string:mine_no>')
api.add_resource(MineTypeResource, '/mine-types',
示例#9
0
        user_security = auth.get_current_user_security()
        return user_security.is_restricted()

    @requires_any_of([VIEW_ALL, MINESPACE_PROPONENT])
    def delete(self):
        user_security = auth.get_current_user_security()
        return user_security.is_restricted()

    @requires_any_of([VIEW_ALL, MINESPACE_PROPONENT])
    def put(self):
        user_security = auth.get_current_user_security()
        return user_security.is_restricted()


api = Namespace('authtest')
api.add_resource(DummyAuthResource, '')
app_api.add_namespace(api)


@pytest.fixture(scope="function")
def setup_info(db_session):
    User._test_mode = False
    auth.clear_cache()
    MinespaceUserFactory(email_or_username='******')

    yield

    User._test_mode = True


# Test no role
示例#10
0
from flask_restplus import Namespace

from ..resources.document_manager import DocumentManagerResource

api = Namespace(
    'document-manager',
    description=
    'Document Manager for uploading and keeping track of files and then serving them to users.'
)

api.add_resource(DocumentManagerResource, '', '/<string:document_guid>')
示例#11
0
文件: permits.py 项目: w8896699/mds
from flask_restplus import Namespace

from ..permit.resources.permit import PermitResource
from ..permit.resources.permit_status_code import PermitStatusCodeResource
from ..permit_amendment.resources.permit_amendment import PermitAmendmentResource
from ..permit_amendment.resources.permit_amendment_document import PermitAmendmentDocumentResource

api = Namespace('permits', description='Permit related operations')

api.add_resource(PermitResource, '', '/<string:permit_guid>')
api.add_resource(PermitStatusCodeResource, '/status-codes')
api.add_resource(PermitAmendmentResource, '/<string:permit_guid>/amendments',
                 '/amendments/<string:permit_amendment_guid>',
                 '/<string:permit_guid>/amendments/<string:permit_amendment_guid>')

api.add_resource(
    PermitAmendmentDocumentResource,
    '/amendments/documents',
    '/amendments/documents/<string:document_guid>',
    '/amendments/<string:permit_amendment_guid>/documents',
    '/amendments/<string:permit_amendment_guid>/documents/<string:document_guid>',
    '/<string:permit_guid>/amendments/<string:permit_amendment_guid>/documents/<string:document_guid>',
    '/<string:permit_guid>/amendments/<string:permit_amendment_guid>/documents',
)
示例#12
0
# services/src/api/app.py

from flask_restplus import Namespace, Resource

app_namespace = Namespace("app")


class App(Resource):
    def get(self):
        return {"status": "success", "message": "app started"}


app_namespace.add_resource(App, "")
from flask_restplus import Namespace
from app.speedtest.views import (SimpleList, PaginatedList, Aggregation, Count,
                                 SelectList, Create, Update, Save,
                                 HeavyCodeList)

api = Namespace('speedtest', description='speedtest related operations')
api.add_resource(SimpleList, '/simple')
api.add_resource(PaginatedList, '/paginated')
api.add_resource(Aggregation, '/aggregation')
api.add_resource(Count, '/count')
api.add_resource(SelectList, '/select')
api.add_resource(Create, '/create')
api.add_resource(Save, '/save')
api.add_resource(Update, '/update')
api.add_resource(HeavyCodeList, '/algo')
# /aggregation/
示例#14
0
from flask_restplus import Namespace

from ..party.resources.party_resource import PartyResource
from ..party.resources.sub_division_code_resource import SubDivisionCodeResource
from ..party_appt.resources.mine_party_appt_resource import MinePartyApptResource
from ..party_appt.resources.mine_party_appt_type_resource import MinePartyApptTypeResource
from ..party.resources.party_list_resource import PartyListResource

api = Namespace('parties', description='Party related operations')

api.add_resource(PartyListResource, '')
api.add_resource(PartyResource, '/<string:party_guid>')

api.add_resource(SubDivisionCodeResource, '/sub-division-codes')

api.add_resource(MinePartyApptResource, '/mines',
                 '/mines/<string:mine_party_appt_guid>')
api.add_resource(
    MinePartyApptTypeResource, '/mines/relationship-types',
    '/mines/relationship-types/<string:mine_party_appt_type_code>')
示例#15
0
        error_msg = ''
        event_msg = ''
        error_code = -1

        if not user:
            error_msg = 'user not found'
            event_msg = '[Not Found] Login attempt, user not found [{0}]'.format(
                data['mail'])
            error_code = 404
        elif not user.check_password(data['password']):
            error_msg = 'Invalid password'
            event_msg = '[Login attempt] invalid password for user [{0}]'.format(
                data['mail'])
            error_code = 401

        # Check for error and save
        if error_code != -1:
            save_new_event(event_msg)
            return {'error': error_msg}, error_code

        # Generate token to send
        token = generate_auth_token_for_user(user)

        save_new_event('[Login] user with id [{0}] logged in'.format(user.id))

        return {'user': user.serialize(), 'auth_token': token}


auth_namespace.add_resource(AuthCollection, '/login', methods=['POST'])
示例#16
0
from app.api.mines.variances.resources.variance_uploaded_documents import MineVarianceUploadedDocumentsResource
from app.api.mines.incidents.resources.mine_incidents import MineIncidentListResource, MineIncidentResource
from app.api.mines.incidents.resources.mine_incident_document import MineIncidentDocumentListResource, MineIncidentDocumentResource
from app.api.mines.reports.resources.mine_report_document import MineReportDocumentListResource
from app.api.mines.reports.resources.mine_reports import MineReportListResource, MineReportResource
from app.api.mines.reports.resources.mine_report_definition import MineReportDefinitionListResource
from app.api.mines.reports.resources.mine_report_comment import MineReportCommentResource, MineReportCommentListResource
from app.api.mines.permits.permit.resources.permit import PermitResource, PermitListResource
from app.api.mines.permits.permit.resources.permit_status_code import PermitStatusCodeResource
from app.api.mines.permits.permit_amendment.resources.permit_amendment import PermitAmendmentResource, PermitAmendmentListResource
from app.api.mines.permits.permit_amendment.resources.permit_amendment_document import PermitAmendmentDocumentListResource, PermitAmendmentDocumentResource
from app.api.mines.now_submissions.resources.application_resource import MineApplicationResource

api = Namespace('mines', description='Mine related operations')

api.add_resource(MineResource, '/<string:mine_no_or_guid>')
api.add_resource(MineListResource, '')
api.add_resource(MineMapResource, '/map-list')

api.add_resource(MineListSearch, '/search')
api.add_resource(MineTenureTypeCodeResource, '/mine-tenure-type-codes')
api.add_resource(MineDisturbanceCodeResource, '/disturbance-codes')
api.add_resource(MineCommodityCodeResource, '/commodity-codes')
api.add_resource(MineStatusResource, '/status/<string:mine_status_guid>')
api.add_resource(MineStatusListResource, '/status')
api.add_resource(MineRegionResource, '/region')

api.add_resource(MineTailingsStorageFacilityListResource,
                 '/<string:mine_guid>/tailings')
api.add_resource(MineDocumentListResource, '/<string:mine_guid>/documents')
示例#17
0
    def delete(self, pk):
        ticket = Ticket.query.get_or_404(pk)
        return ticket.delete(), 202


class TicketResourceList(Resource):
    method_decorators = [
        roles_required(['ADMIN', 'USER', 'CLIENT']), jwt_required
    ]

    def get(self):
        if current_user.role == 'CLIENT':
            return pagination.paginate(
                Ticket.query.filter(
                    Ticket.project.has(user_id=current_user.id)), schema, True)
        return pagination.paginate(Ticket, schema, True)

    def post(self):
        parser.parse_args(strict=True)
        ticket = Ticket()
        obj = schema.load(data=request.json,
                          instance=ticket,
                          session=db.session,
                          unknown='exclude')
        obj.save()
        return schema.dump(obj), 201


ns_ticket.add_resource(TicketResource, '/<int:pk>', endpoint='ticket')
ns_ticket.add_resource(TicketResourceList, '/', endpoint='tickets')
示例#18
0
        comment.file = data.get('filename')
        for team in comment.project.project_team:
            rq_notify_team(
                team.users, "Project Notification",
                f"A new Project file has been uploaded on <a href='{request.url}'>Comment</a>"
            )
        return comment.save(filename=comment.file, id=comment.id), 201

    # @roles_required(['ADMIN'])
    # @jwt_required
    def delete(self, uuid, pk):
        # if current_user.role != 'ADMIN':
        comment = current_user.project_comments.filter(
            ProjectComment.id == pk,
            ProjectComment.project.has(uuid=uuid)).first_or_404()
        msg = delete_file(comment.file)
        comment.file = ""
        comment.save()
        return msg, 202


ns_proj_comment.add_resource(ProjectCommentResource,
                             '/comment/<uuid>/<int:pk>',
                             endpoint='projects_comment')
ns_proj_comment.add_resource(ProjectCommentResourceFile,
                             '/comment/file/<uuid>/<int:pk>',
                             endpoint='projects_comment_file')
ns_proj_comment.add_resource(ProjectCommentResourceList,
                             '/comments/<uuid>',
                             endpoint='projects_comments')
示例#19
0
# services/users/project/api/ping.py

from flask_restplus import Namespace, Resource

foo_namespace = Namespace("foo")


class Foo(Resource):
    def get(self):
        return {"status": "success", "message": "pong!"}


foo_namespace.add_resource(Foo, "")
        if option == 'img':
            profile_parser.add_argument(
                'files',
                required=True,
                location='files',
                type=werkzeug.datastructures.FileStorage)
            args = profile_parser.parse_args(strict=True)
            file = img_upload(args.file)
            if file.get('message'):
                return file, 400
            current_user.img = file.get('filename')
            file.get('upload').save(file.get('full_path'))
            return current_user.save(filename=current_user.img), 201
        return abort(404)


class MeResource(Resource):
    method_decorators = [jwt_required]

    @marshal_with(user_schema)
    def get(self):
        return current_user


ns_user.add_resource(UserResourceList, '/', endpoint='users')
ns_user.add_resource(MeResource, '/me', endpoint='me')
ns_user.add_resource(UserResource, '/<int:pk>', endpoint='user')
ns_user.add_resource(UserProfileResource,
                     '/profile/<string:option>',
                     endpoint='user_profile')
示例#21
0
    @token_required
    def put(self, email):
        """modify username"""

        parser = reqparse.RequestParser()
        parser.add_argument('username',
                            required=False,
                            help="No username provided",
                            location=['json'])
        parser.add_argument('password',
                            required=False,
                            help="No username provided",
                            location=['json'])

        args = parser.parse_args(strict=True)
        username = args['username']
        password = args['password']

        if username:

            res = user.modify_username(email=email, username=args['username'])
            return res

        if password:

            res = user.reset_password(email=email, password=password)
            return res


api.add_resource(User, '/auth/user/<string:email>')
from flask_restplus import Namespace

from app.api.well.resources.well import WellListResource

api = Namespace('well', description='Well endpoints')

api.add_resource(WellListResource, '')
        'Parâmetro opcional, caso queira a lista de colaboradores ativos e inativos com um cpf'
    )
    def get(self):
        if 'cpf' in request.args:
            return colaborador_service.getByCpf(request.args['cpf'])
        return colaborador_service.getAll()


@colaborador_namespace.route('/<int:id>')
class ReadUpdateAndDelete(Resource):
    def get(self, id):
        return colaborador_service.getById(id)

    @colaborador_namespace.expect(colaboradorPutFields)
    def put(self, id):
        return colaborador_service.update(id, request.json)

    def delete(self, id):
        return colaborador_service.delete(id)


@colaborador_namespace.route('/hard_delete/<int:id>')
class HardDelete(Resource):
    def delete(self, id):
        return colaborador_service.hard_delete(id)


colaborador_namespace.add_resource(CreateAndReadOptions)
colaborador_namespace.add_resource(ReadUpdateAndDelete)
colaborador_namespace.add_resource(HardDelete)
示例#24
0
        'pick_up_point': fields.String('pick_up_point'),
        'destination': fields.String('destination')
    })


class Request(Resource):
    @request_api.expect(request)
    def post(self, ride_id):
        data = RequestParser.parser.parse_args()
        new_ride = Ride_object.get_single_ride(ride_id)
        if new_ride:
            if Ride_object.rides[ride_id]["seats_available"] >= data[
                    'number_of_seats']:
                Ride_object.join_request(ride_id, data['username'],
                                         data['number_of_seats'],
                                         data['pick_up_point'],
                                         data['destination'])
                return "Request made successfully", 201
            return "This ride is only limited to {} seats".format(
                Ride_object.rides[ride_id]['seats_available']), 400
        return "Ride does not exists", 404


class Requests(Resource):
    def get(self):
        return Ride_object.requests


request_api.add_resource(Request, '/rides/<int:ride_id>/requests')
request_api.add_resource(Requests, '/requests')
    method_decorators = [roles_required(['ADMIN', 'USER', 'CLIENT']), jwt_required]

    def post(self, uuid, pk):
        comment = TicketComment.query.filter(TicketComment.ticket.has(uuid=uuid),
                                             TicketComment.id == pk,
                                             TicketComment.user_id == current_user.id).first_or_404()
        args = xparser.parse_args(strict=True)
        data = file_upload(args.file)
        if data.get('error'):
            return data, 400
        data.get('upload').save(data.get('full_path'))
        delete_file(comment.file)
        comment.file = data.get('filename')
        comment.save()
        return marshal(comment, ticket_comment_schema), 201

    def delete(self, uuid, pk):
        comment = TicketComment.query.filter(TicketComment.ticket.has(uuid=uuid),
                                             TicketComment.id == pk,
                                             TicketComment.user_id == current_user.id).first_or_404()
        data = delete_file(comment.file)
        if data.get('message'):
            return data, 400
        return data


ns_ticket_comments.add_resource(TicketCommentResource, '/comment/<uuid>/<pk>', endpoint='ticket_comment')
ns_ticket_comments.add_resource(TicketCommentResourceList, '/comments/<uuid>', endpoint='ticket_comments')
ns_ticket_comments.add_resource(TicketCommentResourceFile, '/comment/file/<uuid>/<int:pk>',
                                endpoint='ticket_comment_file')
示例#26
0
from flask_restplus import Namespace

from ..party.resources.party_resource import PartyResource
from ..party.resources.sub_division_code_resource import SubDivisionCodeResource
from ..party_appt.resources.mine_party_appt_resource import MinePartyApptResource
from ..party_appt.resources.mine_party_appt_admin_resource import MinePartyApptAdminResource
from ..party_appt.resources.mine_party_appt_type_resource import MinePartyApptTypeResource
from ..party.resources.party_advance_search_resource import PartyAdvancedSearchResource

api = Namespace('parties', description='Party related operations')

api.add_resource(PartyResource, '', '/<string:party_guid>')

api.add_resource(SubDivisionCodeResource, '/sub-division-codes')

api.add_resource(MinePartyApptResource, '/mines',
                 '/mines/<string:mine_party_appt_guid>')
api.add_resource(
    MinePartyApptTypeResource, '/mines/relationship-types',
    '/mines/relationship-types/<string:mine_party_appt_type_code>')

api.add_resource(MinePartyApptAdminResource, '/mines/manager-history/csv')

api.add_resource(PartyAdvancedSearchResource, '/search')
示例#27
0
from flask_restplus import Namespace

from ..resources.metabase import MetabaseDashboardResource

api = Namespace('reporting', description='Authenticated reports')

api.add_resource(MetabaseDashboardResource, '/dashboard/<int:id>')
示例#28
0
        return notification.save(**args), 201


class UserNotificationResource(Resource):
    method_decorators = [
        roles_required(['CLIENT', 'ADMIN', 'USER', 'CLIENT']), jwt_required
    ]

    def get(self):
        return pagination.paginate(current_user.notifications,
                                   notification_schema)

    def put(self):
        xparser = RequestParser(trim=True, bundle_errors=True)
        xparser.add_argument('id', type=int, location='json')
        xparser.add_argument('read', type=inputs.boolean, location='json')
        args = xparser.parse_args(strict=True)
        notify = current_user.notifications.filter_by(
            id=args.id).first_or_404()
        notify.read = True
        return notify.save(**args), 202


ns_notify.add_resource(NotificationResource,
                       '/<int:pk>',
                       endpoint='notification')
ns_notify.add_resource(NotificationResourceList, '/', endpoint='notifications')
ns_notify.add_resource(UserNotificationResource,
                       '/user',
                       endpoint='user_notify')
示例#29
0
        return book.trades


@book_ns.route('/book/active_bids')
class BookActiveBidsView(Resource):
    @book_ns.marshal_list_with(order_model)
    def get(self):

        book = get_book()
        # Returning a set() does not serialize properly with Flask-RESTFul
        return list(book.active_bids)


@book_ns.route('/book/active_offers')
class BookActiveOffersView(Resource):
    @book_ns.marshal_list_with(order_model)
    def get(self):

        book = get_book()
        # Returning a set() does not serialize properly with Flask-RESTFul
        return list(book.active_offers)


book_ns.add_resource(BookView, '/book', endpoint='book')
book_ns.add_resource(BookOrderView, '/book/orders', endpoint='book_orders')
book_ns.add_resource(BookTraderOrderView,
                     '/book/traders/<trader>/orders',
                     endpoint='book_orders_per_trader')
book_ns.add_resource(BookStatsView, '/book/stats', endpoint='book_stats')
book_ns.add_resource(BookTradeView, '/book/trades', endpoint='book_trades')
示例#30
0
from flask_restplus import Namespace

from app.api.now_submissions.resources.application_resource import ApplicationResource
from app.api.now_submissions.resources.application_list_resource import ApplicationListResource
from app.api.now_submissions.resources.application_nda_resource import ApplicationNDAResource
from app.api.now_submissions.resources.application_nda_list_resource import ApplicationNDAListResource
from app.api.now_submissions.resources.application_document_resource import ApplicationDocumentResource, ApplicationDocumentTokenResource
from app.api.now_submissions.resources.application_status_resource import ApplicationStatusResource, ApplicationStatusListResource

api = Namespace('now-submissions',
                description='NROS/VFCBC Notice of Work submission operations')

api.add_resource(ApplicationListResource, '/applications')
api.add_resource(ApplicationResource,
                 '/applications/<string:application_guid>')
api.add_resource(ApplicationNDAListResource, '/applications-nda')
api.add_resource(ApplicationNDAResource,
                 '/applications-nda/<int:application_nda_guid>')
api.add_resource(ApplicationDocumentResource,
                 '/applications/<string:application_guid>/document/<int:id>')
api.add_resource(
    ApplicationDocumentTokenResource,
    '/applications/<string:application_guid>/document/<int:id>/token')
api.add_resource(ApplicationStatusResource,
                 '/applications/<string:messageid>/status')
api.add_resource(ApplicationStatusListResource, '/applications/status')