Beispiel #1
0
class AnalyticsDto:
    api = Namespace("analytics", description="API for Analytics", ordered=True)
    analytics_post = api.model(
        "analytics",
        {
            "event_name":
            fields.String(
                required=True,
                description="Name of the event for which data is recorded",
                example="USER_LOGIN",
            ),
            "user_data":
            fields.Raw(
                required=False,
                description=
                "A json object stored as string to pass all the related information",
                example={"data": "something"}),
            "device_info":
            fields.Raw(
                required=False,
                description="A json object to store the device info",
                example={
                    "device": "mobile",
                    "browser": "Chrome 80"
                },
            ),
            "network_info":
            fields.Raw(
                required=False,
                description="A json object to store the network info",
                example={"network": "3G"},
            )
        },
    )
Beispiel #2
0
class WorkflowsDto:
    api = Namespace("workflows", description="API for workflows", ordered=True)
    workflows = api.model(
        "workflows",
        {
            "en":
            fields.Raw(
                required=True,
                description="English language details",
                example={
                    "name": "Test workflow",
                    "description": "Some help text about workflow",
                    "description_image": ""
                },
            ),
            "ru":
            fields.Raw(
                required=True,
                description='Language',
                example={
                    "name": "Рабочий процесс тестирования",
                    "description": "Некоторая справка о рабочем процессе",
                    "description_image": ""
                },
            )
        },
    )
Beispiel #3
0
class GetHySDSIOType(Resource):
    """Get list of job queues and return as JSON."""

    resp_model = hysds_io_ns.model(
        'HySDS IO Response(JSON)', {
            'success':
            fields.Boolean(
                required=True,
                description="Boolean, whether the API was successful"),
            'message':
            fields.String(required=True,
                          description="message describing success or failure"),
            'result':
            fields.Raw(required=True, description="HySDS IO Object")
        })
    parser = hysds_io_ns.parser()
    parser.add_argument('id', required=True, type=str, help="HySDS IO Type ID")

    @hysds_io_ns.expect(parser)
    @hysds_io_ns.marshal_with(resp_model)
    def get(self):
        """Gets a HySDS-IO specification by ID"""
        _id = request.form.get('id', request.args.get('id', None))
        if _id is None:
            return {'success': False, 'message': 'missing parameter: id'}, 400

        hysds_io = mozart_es.get_by_id(index=HYSDS_IOS_INDEX,
                                       id=_id,
                                       ignore=404)
        if hysds_io['found'] is False:
            return {'success': False, 'message': ""}, 404

        return {'success': True, 'message': "", 'result': hysds_io['_source']}
Beispiel #4
0
 def test_nested_object(self, mocker):
     foo = mocker.Mock()
     bar = mocker.Mock()
     bar.value = 42
     foo.bar = bar
     field = fields.Raw()
     assert field.output("bar.value", foo) == 42
Beispiel #5
0
class GetContainerInfo(Resource):
    """Info a container"""

    resp_model = container_ns.model(
        'Container Info Response(JSON)', {
            'success':
            fields.Boolean(required=True,
                           description="if 'false', encountered exception; "
                           "otherwise no errors occurred"),
            'message':
            fields.String(required=True,
                          description="message describing success or failure"),
            'result':
            fields.Raw(required=True, description="Container Info")
        })
    parser = container_ns.parser()
    parser.add_argument('id', required=True, type=str, help="Container ID")

    @container_ns.expect(parser)
    @container_ns.marshal_with(resp_model)
    def get(self):
        """Get information on container by ID"""
        _id = request.form.get('id', request.args.get('id', None))

        container = mozart_es.get_by_id(index=CONTAINERS_INDEX,
                                        id=_id,
                                        ignore=404)
        if container['found'] is False:
            return {'success': False, 'message': ""}, 404

        return {'success': True, 'message': "", 'result': container['_source']}
Beispiel #6
0
 def get_restx_model() -> Model:
     return Model(
         "recipe_model",
         {
             "id": restxFields.Integer(readonly=True),
             "time_created": restxFields.DateTime(readonly=True),
             "time_updated": restxFields.DateTime(readonly=True),
             "name": restxFields.String(),
             "macros": restxFields.Raw(readonly=True),
             "directions": restxFields.List(restxFields.String),
             "image_url": restxFields.String(),
             "recipe_url": restxFields.String(),
             "thumbnail_url": restxFields.String(),
             "author": restxFields.String(),
             "servings": restxFields.Integer(),
             "rating": restxFields.Integer(),
             "prep_time": restxFields.Integer(),
             "cook_time": restxFields.Integer(),
             "source_name": restxFields.String(),
             "diets": restxFields.List(restxFields.String),
             "dish_types": restxFields.List(restxFields.String),
             "tags": restxFields.List(restxFields.String),
             "cuisines": restxFields.List(restxFields.String),
             "ingredients": restxFields.List(restxFields.Raw),
         },
     )
Beispiel #7
0
class EdgeDetectorDto:
    api = Namespace("detect_edges",
                    description="detect edges in image",
                    authorizations=authorizations)
    image = api.model(
        "image",
        {
            "image":
            fields.String(required=True,
                          description="base64 encode content of the image")
        },
    )
    # TODO should be possible to specify exact output type via fields.List
    response = api.model(
        "edge_detector_response",
        {
            "data":
            fields.Raw(required=True,
                       description="coordinate of edges as a 4x2 list "
                       "of integers ")
        },
    )
    headers = api.parser().add_argument("Authorization",
                                        location="headers",
                                        help="server to server token")
Beispiel #8
0
class BirdViewDto:
    api = Namespace(
        "bird_view",
        description="make an bird view of the image using edges",
        authorizations=authorizations,
    )
    # TODO should be possible to specify exact output type via fields.List in both
    image = api.model(
        "image_and_points",
        {
            "image":
            fields.String(required=True,
                          description="base64 encode content of the image"),
            "points":
            fields.Raw(required=True,
                       description="coordinate of edges as a 4x2 list "
                       "of integers "),
        },
    )
    response = api.model(
        "bird_view_response",
        {
            "data":
            fields.String(required=True,
                          description="base64 encode content of the "
                          "transformed image")
        },
    )
    headers = api.parser().add_argument("Authorization",
                                        location="headers",
                                        help="server to server token")
Beispiel #9
0
class UserResponsesDto:
    api = Namespace("user_responses", description="data filled by the user")
    user_responses = api.inherit(
        "user_responses", {
            "user_id":
            fields.Integer(
                required=False,
                description="User Id who has submitted the response",
                example=2),
            "user_workflow_id":
            fields.Integer(
                required=True,
                description="User Id who has submitted the response",
                example=2),
            "workflow_details_id":
            fields.Integer(
                required=True,
                description="User Id who has submitted the response",
                example=2),
            "response":
            fields.Raw(required=True,
                       description="{'<question_id>:'<response>'}",
                       example={"<question_id>": "<response>"}),
            "response_status":
            fields.String(required=False,
                          description="user response status",
                          example="REVIEW")
        })
Beispiel #10
0
class EvaluatedSkillsDto:
    user_skill = api_namespace.model(
        'evaluated_skill', {
            'name':
            fields.String(required=True, description='profile name'),
            'scores':
            fields.Raw(required=True,
                       description='map shaped { -skill_name- : -value-}')
        })

    skill_list = api_namespace.model(
        'skill_list', {
            'skills':
            fields.List(fields.Nested(user_skill),
                        required=True,
                        description='list of profiles')
        })

    @staticmethod
    def build_json_from_skills(evaluated_skills):
        response = []
        skill_data = evaluated_skills.get_skills_data()
        for skill in skill_data:
            response.append(skill_data[skill])
        return {'skills': response}
def getLoginPostDataModel(appObj):
    return appObj.flastRestPlusAPIObject.model(
        'LoginPostData', {
            'authProviderGUID':
            fields.String(
                default=None,
                description='Unique identifier of AuthProvider to log in with',
                required=True),
            'credentialJSON':
            fields.Raw(
                description=
                'JSON structure required depends on the Auth Provider type',
                required=True),
            'UserID':
            fields.String(
                default=None,
                description=
                'If a person has access to mutiple Users then they specify the UserID of the one they need to login with'
            ),
            'ticket':
            fields.String(
                default=None,
                description=
                'If a user has a ticket to grant them extra roles on the tenant'
            )
        })
Beispiel #12
0
class GetJobInfo(Resource):
    """Get info of job IDs."""

    resp_model = job_ns.model('Job Info Response(JSON)', {
        'success': fields.Boolean(required=True, description="if 'false' encountered exception; "
                                                             "otherwise no errors occurred"),
        'message': fields.String(required=True, description="message describing success or failure"),
        'result':  fields.Raw(required=True, description="Job Info Object")
    })
    parser = job_ns.parser()
    parser.add_argument('id', type=str, required=True, help="Job ID")

    @job_ns.expect(parser)
    @job_ns.marshal_with(resp_model)
    def get(self):
        """Get complete info for submitted job based on id"""
        _id = request.form.get('id', request.args.get('id', None))
        if _id is None:
            return {
                'success': False,
                'message': 'id must be supplied (as query param or url param)'
            }, 400

        info = mozart_es.get_by_id(index=JOB_STATUS_INDEX, id=_id, ignore=404)
        if info['found'] is False:
            return {
                'success': False,
                'message': 'job info not found: %s' % _id
            }, 404

        return {
            'success': True,
            'message': "",
            'result': info['_source']
        }
Beispiel #13
0
class GetQueueNames(Resource):
    """Get list of job queues and return as JSON."""

    resp_model = queue_ns.model('Queue Listing Response(JSON)', {
        'success': fields.Boolean(required=True, description="if 'false' encountered exception; "
                                                             "otherwise no errors occurred"),
        'message': fields.String(required=True, description="message describing success or failure"),
        'result':  fields.Raw(required=True, description="queue response")
    })
    parser = queue_ns.parser()
    parser.add_argument('id', type=str, help="Job Type Specification ID")

    @queue_ns.expect(parser)
    @queue_ns.marshal_with(resp_model)
    def get(self):
        """Gets a listing of non-celery queues handling jobs."""
        try:
            ident = request.form.get('id', request.args.get('id', None))
            queues = mozart.lib.queue_utils.get_queue_names(ident)
            app.logger.warn("Queues: " + str(queues))
        except Exception as e:
            message = "Failed to list job queues. {0}:{1}".format(type(e), str(e))
            app.logger.warning(message)
            app.logger.warning(traceback.format_exc(e))
            return {'success': False, 'message': message}, 500
        return {
            'success': True,
            'message': "",
            'result': queues
        }
    def _translate_attribute(self, name, attr, namespace):
        logger.debug('Translating {}.{}'.format(self.name, name))
        field = None

        if isinstance(attr, attributes.MapAttribute):
            if attr.__class__ == attributes.MapAttribute:
                map_name = name.title()
                field = PynamoMapAttribute(map_name)
            else:
                map_name = attr.__class__.__name__
                field = self._get_or_create_nested(map_name, attr, namespace)
        elif isinstance(attr, self.MAPMETA):
            field = self._get_or_create_nested(name, attr, namespace)
        elif isinstance(attr, attributes.ListAttribute):
            if attr.element_type:
                element_type = self._translate_attribute(attr.element_type.__name__, attr.element_type, namespace)
            else:
                element_type = fields.String()
            field = fields.List(element_type)
        else:
            for p_attr, r_field in self.TYPEMAP.items():
                if isinstance(attr, p_attr):
                    field = r_field
                    break
            else:
                logger.warn('Unhandled attribute {} mapped as Raw'.format(attr))
                field = fields.Raw()

        logger.debug('Translated {}.{}={} as {}'.format(self.name, name, attr.__class__, field.__class__))
        return field
Beispiel #15
0
def getAPIKeyModel(appObj):
  return appObj.flastRestPlusAPIObject.model('APIKeyModel', {
    'id': fields.String(default='DEFAULT', description='Unique identifier of APIKey'),
    'tenantName': fields.String(default='DEFAULT', description='Name of the Tenant this APIKey associated with'),
    'createdByUserID': fields.String(default='DEFAULT', description='UserGUID of user who created this ticket'),
    'restrictedRoles': fields.List(fields.String(default=None,description='If not an empty list a subset of the users roles to be inherited by this APIKey'),required=True),
    'externalData': fields.Raw(description='Any other data supplied during apikey creation', required=True),
    RepositoryObjBaseClass.getMetadataElementKey(): fields.Nested(RepositoryObjBaseClass.getMetadataModel(appObj, flaskrestplusfields=fields))
  })
Beispiel #16
0
    def test_with_partial_attribute(self, mocker):
        def f(x, suffix):
            return '{0}-{1}'.format(x.value, suffix)

        obj = mocker.Mock()
        obj.value = 42

        p = partial(f, suffix='whatever')
        field = fields.Raw(attribute=p)
        assert field.output('foo', obj) == '42-whatever'
Beispiel #17
0
    def test_with_partial_attribute(self, mocker):
        def f(x, suffix):
            return "{0}-{1}".format(x.value, suffix)

        obj = mocker.Mock()
        obj.value = 42

        p = partial(f, suffix="whatever")
        field = fields.Raw(attribute=p)
        assert field.output("foo", obj) == "42-whatever"
Beispiel #18
0
class MapsRoute(Resource):
    success_model = ns.model('Maps service route response - success', {})

    error_model = ns.model('Maps service route response - error',
                           {'error': fields.Raw({})})

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.date_now = datetime.datetime.utcnow() + datetime.timedelta(
            hours=1)

    @ns.response(200, 'OK', success_model)
    @ns.response(400, 'Error', error_model)
    @ns.doc(
        description=
        'Get a route from origin to destination with a optional arrival time.')
    def get(self):
        if ('origin' not in request.args or 'destination'
                not in request.args) or (not request.args.get('origin') or
                                         not request.args.get('destination')):
            return make_response(
                {
                    'error':
                    'Not all required arguments specified (origin, destination)'
                },
                400,
            )

        origin = request.args.get('origin')
        destination = request.args.get('destination')
        arrival_time = request.args.get('arrival_time')
        gmaps = googlemaps.Client(key=os.getenv('API_KEY'))

        # Request directions
        if 'arrival_time' not in request.args or not request.args.get(
                'arrival_time'):
            print(self.date_now)
            directions_result = gmaps.directions(
                origin,
                destination,
                # mode='transit',
                # departure_time=self.date_now,
                units='metric',
            )
        else:
            directions_result = gmaps.directions(
                origin,
                destination,
                arrival_time=arrival_time,
                # mode='transit',
                units='metric',
            )

        return make_response(jsonify(directions_result), 200)
def getAuthProviderModel(appObj):
    return appObj.flastRestPlusAPIObject.model(
        'AuthProviderInfo', {
            'guid':
            fields.String(default=None,
                          description='Unique identifier of AuthProvider'),
            'Type':
            fields.String(default='internal',
                          description='Authorization provider type'),
            'AllowUserCreation':
            fields.Boolean(
                default=False,
                description=
                'Allow unknown logins to create new users. (Must be set to true at this level AND Tenant level to work)'
            ),
            'AllowLink':
            fields.Boolean(
                default=None,
                description='Allow user to add this as a secondary auth method'
            ),
            'AllowUnlink':
            fields.Boolean(
                default=None,
                description=
                'Allow user to remove this auth method (As long as they have others availiable)'
            ),
            'LinkText':
            fields.String(
                default=None,
                description=
                'Text to show on link button in Security settings UI'),
            'MenuText':
            fields.String(
                default='click here',
                description='Item text used in login method selection screen'),
            'IconLink':
            fields.String(
                default=None,
                description='Image link used in login method selection screen'
            ),
            'ConfigJSON':
            fields.String(
                default=None,
                description='Extra configuration required per auth type'),
            'StaticlyLoadedData':
            fields.Raw(description='Other data loaded for this auth type'),
            'saltForPasswordHashing':
            fields.String(
                default=None,
                description=
                'Salt that can be used for password hashing (Depends on auth method)'
            )
        })
Beispiel #20
0
 def get_restx_model() -> Model:
     return Model(
         "User Model",
         {
             "id": restxFields.Integer(),
             "time_created": restxFields.DateTime(),
             "time_updated": restxFields.DateTime(),
             "username": restxFields.String(),
             "email": restxFields.String(),
             "active": restxFields.Boolean(),
             "first_name": restxFields.String(),
             "last_name": restxFields.String(),
             "birthday": restxFields.Date(),
             "height_inches": restxFields.Float(),
             "weight_lbs": restxFields.Float(),
             "gender": restxFields.String(),
             "household": restxFields.Raw(),
             "household_id": restxFields.Integer(),
             "roles": restxFields.List(restxFields.Raw()),
         },
     )
Beispiel #21
0
def get_models_parsers(api):

    get_file_parser = reqparse.RequestParser()
    get_file_parser.add_argument('FileName',
                                 type=str,
                                 location='headers',
                                 required=True)

    post_file_model = api.model('admin_update_schema_fields', {
        'FileData': fields.Raw(required=True),
    })

    return get_file_parser, post_file_model
Beispiel #22
0
class EmployeeApi:
    api = Namespace('employee', description='Employee of the company')
    employee = api.model(
        'employee', {
            'id':
            fields.Integer(required=True, description='Id of the employee'),
            'first':
            fields.String(required=True,
                          description='First name of the person'),
            'last':
            fields.String(required=True, description='Surname of the person'),
            'department':
            fields.Raw(
                description=
                'Id or object of the department where the employee belongs'),
            'office':
            fields.Raw(
                description=
                'Id or object of the office where the employee belongs'),
            'manager':
            fields.Raw(
                description='Id or object of the manager of the employee')
        })
def getLoginResponseModel(appObj):
    jwtTokenModel = appObj.flastRestPlusAPIObject.model(
        'JWTTokenInfo', {
            'JWTToken':
            fields.String(description='JWTToken'),
            'TokenExpiry':
            fields.DateTime(dt_format=u'iso8601',
                            description='Time the JWTToken can be used until')
        })
    refreshTokenModel = appObj.flastRestPlusAPIObject.model(
        'RefreshTokenInfo', {
            'token':
            fields.String(description='Refresh Token'),
            'TokenExpiry':
            fields.DateTime(
                dt_format=u'iso8601',
                description='Time the Refresh token can be used until')
        })
    return appObj.flastRestPlusAPIObject.model(
        'LoginResponseData', {
            'possibleUsers':
            fields.List(fields.Nested(getUserModel(appObj))),
            'jwtData':
            fields.Nested(jwtTokenModel, skip_none=True),
            'refresh':
            fields.Nested(refreshTokenModel, skip_none=True),
            'userGuid':
            fields.String(
                description=
                'Unique identifier of user to be used by the application'),
            'authedPersonGuid':
            fields.String(
                description='Unique identifier of person for use with Auth APIs'
            ),
            'ThisTenantRoles':
            fields.List(
                fields.String(
                    description=
                    'Role the user has been assigned for this tenant')),
            'known_as':
            fields.String(description='User friendly identifier for username'),
            'other_data':
            fields.Raw(description='Any other data supplied by auth provider',
                       required=True),
            'currentlyUsedAuthProviderGuid':
            fields.String(
                description='GUID of auth provider used to login with'),
            'currentlyUsedAuthKey':
            fields.String(description='Key of auth used to login with')
        })
Beispiel #24
0
class TestDto:
    api = Namespace('test', description='test management operations')
    test_cases = api.model(
        'test_cases', {
            'test_cases': fields.List(fields.String()),
            'test_suite': fields.String(),
        })
    test_suite = api.model(
        'test_suite', {
            'id': fields.String(),
            'test_suite': fields.String(),
            'path': fields.String(),
            'test_cases': fields.List(fields.String()),
            'variables': fields.Raw(),
            'author': fields.String()
        })
def getRegisterPostDataModel(appObj):
    return appObj.flastRestPlusAPIObject.model(
        'RegisterPostData', {
            'authProviderGUID':
            fields.String(
                default='DEFAULT',
                description='Unique identifier of AuthProvider to log in with',
                required=True),
            'credentialJSON':
            fields.Raw(
                description=
                'JSON structure required depends on the Auth Provider type',
                required=True),
            'ticket':
            fields.String(default='DEFAULT',
                          description='If a user has a ticket to grant access')
        })
Beispiel #26
0
def getCreateAuthModel(appObj):
    return appObj.flastRestPlusAPIObject.model(
        'CreateAuthInfo', {
            'personGUID':
            fields.String(default='DEFAULT',
                          description='Unique identifier of Person',
                          required=True),
            'tenantName':
            fields.String(description='Name of Tenant'),
            'authProviderGUID':
            fields.String(default='DEFAULT',
                          description='Unique identifier of Person',
                          required=True),
            'credentialJSON':
            fields.Raw(
                description=
                'JSON structure required depends on the Auth Provider type',
                required=True),
        })
Beispiel #27
0
def getServerInfoModel(appObj):
    serverInfoServerModel = appObj.flastRestPlusAPIObject.model(
        'mainAPI', {
            'Version':
            fields.String(
                default='DEFAULT',
                description='Version of container running on server'),
            'APIAPP_APIDOCSURL':
            fields.String(default='',
                          description='Base endpoint for EBO docs'),
            'APIAPP_FRONTENDURL':
            fields.String(default='',
                          description='Base endpoint for frontend of app')
        })
    return appObj.flastRestPlusAPIObject.model(
        'ServerInfo', {
            'Server': fields.Nested(serverInfoServerModel),
            'Derived': fields.Raw(required=False)
        })
Beispiel #28
0
class PaymentRequest:
    """
    Payment request model.
    """
    api = Namespace('payment', description='payment related operations')
    body = api.model(
        'payment', {
            'source_address':
            fields.String(required=True,
                          min_length=25,
                          max_length=36,
                          description='source address'),
            'outputs':
            fields.Raw(required=True,
                       description='outputs to send transaction'),
            'fee_kb':
            fields.Integer(required=True,
                           unsigned=True,
                           description='the fee value in kb\'s'),
        })
Beispiel #29
0
class GetJobSpecType(Resource):
    """Get list of job queues and return as JSON."""

    resp_model = job_spec_ns.model(
        'Job Type Specification Response(JSON)', {
            'success':
            fields.Boolean(required=True,
                           description="if 'false', encountered exception; "
                           "otherwise no errors occurred"),
            'message':
            fields.String(required=True,
                          description="message describing success or failure"),
            'result':
            fields.Raw(required=True, description="Job Type Specification")
        })
    parser = job_spec_ns.parser()
    parser.add_argument('id', required=True, type=str, help="Job Type ID")

    @job_spec_ns.expect(parser)
    @job_spec_ns.marshal_with(resp_model)
    def get(self):
        """Gets a Job Type specification object for the given ID."""
        _id = request.form.get('id', request.args.get('id', None))
        if _id is None:
            return {'success': False, 'message': 'missing parameter: id'}, 400

        job_spec = mozart_es.get_by_id(index=JOB_SPECS_INDEX,
                                       id=_id,
                                       ignore=404)
        if job_spec['found'] is False:
            app.logger.error('job_spec not found %s' % _id)
            return {
                'success': False,
                'message': 'Failed to retrieve job_spec: %s' % _id
            }, 404

        return {
            'success': True,
            'message': "job spec for %s" % _id,
            'result': job_spec['_source']
        }
def getUserModel(appObj):
    TenantRoleModel = appObj.flastRestPlusAPIObject.model(
        'TenantRoleModel', {
            'TenantName':
            fields.String(default='DEFAULT', description='Tenant Name'),
            'ThisTenantRoles':
            fields.List(
                fields.String(
                    description=
                    'Role the user has been assigned for this tenant')),
        })

    return appObj.flastRestPlusAPIObject.model(
        'UserInfo', {
            'UserID':
            fields.String(default='DEFAULT',
                          description='Unique identifier of User'),
            'known_as':
            fields.String(description='User friendly identifier for username'),
            'TenantRoles':
            fields.List(fields.Nested(TenantRoleModel)),
            'other_data':
            fields.Raw(description='Any other data supplied by auth provider',
                       required=True),
            'associatedPersonGUIDs':
            fields.List(
                fields.String(
                    description='GUIDs of associated user accounts')),
            'ObjectVersion':
            fields.String(
                default='DEFAULT',
                description=
                'Obect version required to sucessfully preform updates'),
            'creationDateTime':
            fields.DateTime(dt_format=u'iso8601',
                            description='Datetime user was created'),
            'lastUpdateDateTime':
            fields.DateTime(dt_format=u'iso8601',
                            description='Datetime user was lastupdated')
        })