示例#1
0
    def test_marshal_does_not_hit_unrequired_attributes(self, app, client):
        api = Api(app)

        model = api.model(
            'Person', {
                'name': fields.String,
                'age': fields.Integer,
                'boolean': fields.Boolean,
            })

        class Person(object):
            def __init__(self, name, age):
                self.name = name
                self.age = age

            @property
            def boolean(self):
                raise Exception()

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            async def get(self, request):
                return Person('John Doe', 42)

        data = client.get_json('/test/', headers={'X-Fields': '{name,age}'})
        assert data == {'name': 'John Doe', 'age': 42}
    def test_api_payload(self, app, client):
        api = Api(app, validate=True)
        ns = Namespace('apples')
        api.add_namespace(ns)

        f = ns.model(
            'Person', {
                'name': fields.String(required=True),
                'age': fields.Integer,
                'birthdate': fields.DateTime,
            })

        @ns.route('/validation/')
        class Payload(Resource):
            payload = None

            @ns.expect(f)
            async def post(self, request):
                Payload.payload = ns.payload
                return {}

        data = {
            'name': 'John Doe',
            'age': 15,
        }

        client.post_json('/apples/validation/', data)

        assert Payload.payload == data
示例#3
0
    def test_marshal_handle_inheritance(self, app):
        api = Api(app)

        person = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer,
        })

        child = api.inherit('Child', person, {
            'extra': fields.String,
        })

        data = {'name': 'John Doe', 'age': 42, 'extra': 'extra'}

        values = (
            ('name', {
                'name': 'John Doe'
            }),
            ('name,extra', {
                'name': 'John Doe',
                'extra': 'extra'
            }),
            ('extra', {
                'extra': 'extra'
            }),
        )

        for value, expected in values:
            result = marshal(data, child, mask=value)
            assert result == expected
    def test_marshal_with_disabling_mask_header(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }

        app.config['RESTPLUS_MASK_SWAGGER'] = False
        specs = client.get_specs()

        op = specs['paths']['/test/']['get']

        assert 'parameters' not in op
示例#5
0
    def test_marshal_with_expose_mask_header(self, app, client):
        api = Api(app)

        model = api.model(
            'Test', {
                'name': fields.String,
                'age': fields.Integer,
                'boolean': fields.Boolean,
            })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            async def get(self, request):
                return {'name': 'John Doe', 'age': 42, 'boolean': True}

        specs = client.get_specs()
        op = specs['paths']['/test/']['get']

        assert 'parameters' in op
        assert len(op['parameters']) == 1

        param = op['parameters'][0]

        assert param['name'] == 'X-Fields'
        assert param['type'] == 'string'
        assert param['format'] == 'mask'
        assert param['in'] == 'header'
        assert 'required' not in param
        assert 'default' not in param
    def test_list_fields_with_nested_inherited(self, app):
        api = Api(app)

        person = api.model('Person', {
            'name': fields.String,
            'age': fields.Integer
        })
        child = api.inherit('Child', person, {
            'attr': fields.String
        })

        family = api.model('Family', {
            'children': fields.List(fields.Nested(child))
        })

        result = mask.apply(family.resolved, 'children{name,attr}')

        data = {'children': [
            {'name': 'John', 'age': 5, 'attr': 'value-john'},
            {'name': 'Jane', 'age': 42, 'attr': 'value-jane'},
        ]}
        expected = {'children': [
            {'name': 'John', 'attr': 'value-john'},
            {'name': 'Jane', 'attr': 'value-jane'},
        ]}

        assert_data(marshal(data, result), expected)
        # Should leave th original mask untouched
        assert_data(marshal(data, family), data)
示例#7
0
    def test_marshal_with_expose_custom_mask_header(self, app, client):
        api = Api(app)

        model = api.model(
            'Test', {
                'name': fields.String,
                'age': fields.Integer,
                'boolean': fields.Boolean,
            })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            async def get(self, request):
                return {'name': 'John Doe', 'age': 42, 'boolean': True}

        app.config['RESTPLUS_MASK_HEADER'] = 'X-Mask'
        specs = client.get_specs()

        op = specs['paths']['/test/']['get']
        assert 'parameters' in op
        assert len(op['parameters']) == 1

        param = op['parameters'][0]
        assert param['name'] == 'X-Mask'
示例#8
0
    def test_marshal_with_honour_field_mask_list(self, app, client):
        api = Api(app)

        model = api.model(
            'Test', {
                'name': fields.String,
                'age': fields.Integer,
                'boolean': fields.Boolean,
            })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            async def get(self, request):
                return [{
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }, {
                    'name': 'Jane Doe',
                    'age': 33,
                    'boolean': False
                }]

        data = client.get_json('/test/', headers={'X-Fields': '{name,age}'})
        assert data == [{
            'name': 'John Doe',
            'age': 42,
        }, {
            'name': 'Jane Doe',
            'age': 33,
        }]
示例#9
0
 def test_with_readonly(self, app):
     api = Api(app)
     nested_fields = api.model('NestedModel', {'name': fields.String})
     field = fields.Nested(nested_fields, readonly=True)
     assert field.__schema__ == {
         '$ref': '#/definitions/NestedModel',
         'readOnly': True
     }
示例#10
0
    def test_no_crossdomain(self, app, client):
        class Foo(Resource):
            def get(self):
                return "data"

        api = Api(app)
        api.add_resource(Foo, '/test/')

        res = client.get('/test/')
        assert res.status_code == 200
        assert 'Access-Control-Allow-Origin' not in res.headers
        assert 'Access-Control-Allow-Methods' not in res.headers
        assert 'Access-Control-Max-Age' not in res.headers
示例#11
0
    async def test_json_float_marshalled(self, app, client):
        api = Api(app)

        class FooResource(Resource):
            fields = {'foo': fields.Float}

            async def get(self, request):
                return marshal({"foo": 3.0}, self.fields)

        api.add_resource(FooResource, '/api')

        resp = await client.get('/api')
        assert resp.status_code == 200
        assert resp.data.decode('utf-8') == '{"foo": 3.0}\n'
示例#12
0
    def test_access_control_expose_headers(self, app, client):
        class Foo(Resource):
            @cors.crossdomain(
                origin='*', expose_headers=['X-My-Header', 'X-Another-Header'])
            def get(self):
                return "data"

        api = Api(app)
        api.add_resource(Foo, '/test/')

        res = client.get('/test/')
        assert res.status_code == 200
        assert 'X-MY-HEADER' in res.headers['Access-Control-Expose-Headers']
        assert 'X-ANOTHER-HEADER' in res.headers[
            'Access-Control-Expose-Headers']
示例#13
0
 def api(self, app):
     blueprint = Blueprint('api', __name__)
     realm = SanicPluginRealm(blueprint)
     plugin, reg = realm.register_plugin(restplus)
     api = Api(reg)
     app.register_blueprint(blueprint)
     yield api
示例#14
0
    def test_crossdomain(self, app, client):
        class Foo(Resource):
            @cors.crossdomain(origin='*')
            def get(self):
                return "data"

        api = Api(app)
        api.add_resource(Foo, '/test/')

        res = client.get('/test/')
        assert res.status_code == 200
        assert res.headers['Access-Control-Allow-Origin'] == '*'
        assert res.headers['Access-Control-Max-Age'] == '21600'
        assert 'HEAD' in res.headers['Access-Control-Allow-Methods']
        assert 'OPTIONS' in res.headers['Access-Control-Allow-Methods']
        assert 'GET' in res.headers['Access-Control-Allow-Methods']
示例#15
0
 def api(self, app):
     blueprint = Blueprint('api', __name__)
     spf = SanicPluginsFramework(blueprint)
     plugin, reg = spf.register_plugin(restplus)
     api = Api(reg)
     app.register_blueprint(blueprint)
     yield api
示例#16
0
    def test_raise_400_on_invalid_mask(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                pass

        response = client.get('/test/', headers={'X-Fields': 'name{,missing}'})
        assert response.status_code == 400
        assert response.content_type == 'application/json'
示例#17
0
    def test_marshal_honour_field_mask(self, app):
        api = Api(app)

        model = api.model(
            'Test', {
                'name': fields.String,
                'age': fields.Integer,
                'boolean': fields.Boolean,
            })

        data = {'name': 'John Doe', 'age': 42, 'boolean': True}

        result = api.marshal(data, model, mask='{name,age}')

        assert result == {
            'name': 'John Doe',
            'age': 42,
        }
示例#18
0
    def test_marshal_with_honour_default_model_mask(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        },
                          mask='{name,age}')

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            async def get(self, request):
                return {'name': 'John Doe', 'age': 42, 'boolean': True}

        data = client.get_json('/test/')
        assert data == {'name': 'John Doe', 'age': 42}
示例#19
0
    def test_marshal_with_expose_default_model_mask_header(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        }, mask='{name,age}')

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                pass

        specs = client.get_specs()
        definition = specs['definitions']['Test']
        assert 'x-mask' in definition
        assert definition['x-mask'] == '{name,age}'
示例#20
0
    def test_marshal_with_skip_missing_fields(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            def get(self):
                return {
                    'name': 'John Doe',
                    'age': 42,
                }

        data = client.get_json('/test/', headers={'X-Fields': '{name,missing}'})
        assert data == {'name': 'John Doe'}
示例#21
0
    def test_marshal_with_honour_header_field_mask_with_default_mask_and_default_model_mask(
            self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        },
                          mask='{name,boolean}')

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model, mask='{name,age}')
            def get(self):
                return {'name': 'John Doe', 'age': 42, 'boolean': True}

        data = client.get_json('/test/', headers={'X-Fields': '{name}'})
        assert data == {'name': 'John Doe'}
示例#22
0
    def test_marshal_with_honour_custom_field_mask(self, app, client):
        api = Api(app)

        model = api.model(
            'Test', {
                'name': fields.String,
                'age': fields.Integer,
                'boolean': fields.Boolean,
            })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model)
            async def get(self, request):
                return {'name': 'John Doe', 'age': 42, 'boolean': True}

        app.config['RESTPLUS_MASK_HEADER'] = 'X-Mask'
        data = client.get_json('/test/', headers={'X-Mask': '{name,age}'})

        assert data == {'name': 'John Doe', 'age': 42}
示例#23
0
    def test_marshal_with_honour_default_mask(self, app, client):
        api = Api(app)

        model = api.model(
            'Test', {
                'name': fields.String,
                'age': fields.Integer,
                'boolean': fields.Boolean,
            })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(model, mask='{name,age}')
            def get(self):
                return {'name': 'John Doe', 'age': 42, 'boolean': True}

        data = self.get_json('/test/')
        self.assertEqual(data, {
            'name': 'John Doe',
            'age': 42,
        })
示例#24
0
    def test_is_only_exposed_on_marshal_with(self, app, client):
        api = Api(app)

        model = api.model('Test', {
            'name': fields.String,
            'age': fields.Integer,
            'boolean': fields.Boolean,
        })

        @api.route('/test/')
        class TestResource(Resource):
            def get(self):
                return api.marshal({
                    'name': 'John Doe',
                    'age': 42,
                    'boolean': True
                }, model)

        specs = client.get_specs()
        op = specs['paths']['/test/']['get']

        assert 'parameters' not in op
示例#25
0
    async def test_will_prettyprint_json_in_debug_mode(self, app, client):
        api = Api(app)

        class Foo1(Resource):
            async def get(self, request):
                return {'foo': 'bar', 'baz': 'asdf'}

        api.add_resource(Foo1, '/foo', endpoint='bar')

        foo = await client.get('/foo')

        # Python's dictionaries have random order (as of "new" Pythons,
        # anyway), so we can't verify the actual output here.  We just
        # assert that they're properly prettyprinted.
        lines = foo.data.splitlines()
        lines = [line.decode() for line in lines]
        assert "{" == lines[0]
        assert lines[1].startswith('    ')
        assert lines[2].startswith('    ')
        assert "}" == lines[3]

        # Assert our trailing newline.
        assert foo.data.endswith(b'\n')
示例#26
0
    def test_marshal_with_handle_polymorph(self, app, client):
        api = Api(app)

        parent = api.model('Person', {
            'name': fields.String,
        })

        child1 = api.inherit('Child1', parent, {
            'extra1': fields.String,
        })

        child2 = api.inherit('Child2', parent, {
            'extra2': fields.String,
        })

        class Child1(object):
            name = 'child1'
            extra1 = 'extra1'

        class Child2(object):
            name = 'child2'
            extra2 = 'extra2'

        mapping = {Child1: child1, Child2: child2}

        thing = api.model('Thing', {
            'owner': fields.Polymorph(mapping),
        })

        @api.route('/thing-1/')
        class Thing1Resource(Resource):
            @api.marshal_with(thing)
            async def get(self, request):
                return {'owner': Child1()}

        @api.route('/thing-2/')
        class Thing2Resource(Resource):
            @api.marshal_with(thing)
            async def get(self, request):
                return {'owner': Child2()}

        data = client.get_json('/thing-1/',
                               headers={'X-Fields': 'owner{name}'})
        assert data == {'owner': {'name': 'child1'}}

        data = client.get_json('/thing-1/',
                               headers={'X-Fields': 'owner{extra1}'})
        assert data == {'owner': {'extra1': 'extra1'}}

        data = client.get_json('/thing-2/',
                               headers={'X-Fields': 'owner{name}'})
        assert data == {'owner': {'name': 'child2'}}
示例#27
0
    def test_marshal_with_honour_complex_field_mask_header(self, app, client):
        api = Api(app)

        person = api.model('Person', person_fields)
        child = api.inherit('Child', person, {
            'attr': fields.String
        })

        family = api.model('Family', {
            'father': fields.Nested(person),
            'mother': fields.Nested(person),
            'children': fields.List(fields.Nested(child)),
            'free': fields.List(fields.Raw),
        })

        house = api.model('House', {
            'family': fields.Nested(family, attribute='people')
        })

        @api.route('/test/')
        class TestResource(Resource):
            @api.marshal_with(house)
            def get(self):
                return {'people': {
                    'father': {'name': 'John', 'age': 42},
                    'mother': {'name': 'Jane', 'age': 42},
                    'children': [
                        {'name': 'Jack', 'age': 5, 'attr': 'value-1'},
                        {'name': 'Julie', 'age': 7, 'attr': 'value-2'},
                    ],
                    'free': [
                        {'key-1': '1-1', 'key-2': '1-2'},
                        {'key-1': '2-1', 'key-2': '2-2'},
                    ]
                }}

        data = client.get_json('/test/', headers={
            'X-Fields': 'family{father{name},mother{age},children{name,attr},free{key-2}}'
        })
        assert data == {'family': {
            'father': {'name': 'John'},
            'mother': {'age': 42},
            'children': [{'name': 'Jack', 'attr': 'value-1'}, {'name': 'Julie', 'attr': 'value-2'}],
            'free': [{'key-2': '1-2'}, {'key-2': '2-2'}]
        }}
    # X-API-Key: abcdef12345
    'APIKeyHeader': {
        'type': 'apiKey',
        'in': 'header',
        'name': 'X-API-Key'
    },
    'APIKeyQueryParam': {
        'type': 'apiKey',
        'in': 'query',
        'name': 'api_key'
    }
}

api = Api(title="CSIRO Cosmoz REST Interface",
          prefix='',
          doc='/doc',
          authorizations=security_defs,
          default_mediatype="application/json",
          additional_css="/static/material_swagger.css")
ns = api.default_namespace

MAX_RETURN_COUNT = 2147483647  # Highest 32bit signed int
EARLIEST_DATETIME = datetime.now(tz=timezone.utc) - timedelta(days=36525)


def get_jinja2_for_api(_a):
    if _a.spf_reg is None:
        raise RuntimeError("API is not registered on a Sanic App.")
    (s, _, _) = _a.spf_reg
    reg = sanic_jinja2.find_plugin_registration(s)
    assoc = sanic_jinja2.AssociatedTuple(sanic_jinja2, reg)
    return assoc
示例#29
0
import operator

from sanic import Sanic
from sanic import response
from sanic_restplus import Resource, Api, fields
from sanic_restplus.utils import get_accept_mimetypes


app = Sanic(__name__)

api = Api(app)

todos = {}


resource_fields = api.model('Resource', {
    'data': fields.String,
})

@api.route('/<todo_id:[A-z0-9]+>')
@api.doc(params={'todo_id': 'A TODO ID'})
class TodoSimple(Resource):
    """
    You can try this example as follow:
        $ curl http://localhost:5000/todo1 -d "data=Remember the milk" -X PUT
        $ curl http://localhost:5000/todo1
        {"todo1": "Remember the milk"}
        $ curl http://localhost:5000/todo2 -d "data=Change my breakpads" -X PUT
        $ curl http://localhost:5000/todo2
        {"todo2": "Change my breakpads"}
示例#30
0
# -*- coding: utf-8 -*-
#
from collections import OrderedDict
from sanic.response import json, text, HTTPResponse
from sanic.request import Request
from sanic.exceptions import ServiceUnavailable
from sanic_restplus import Api, Resource, fields

from functions import get_linksets, get_datasets, get_locations, get_location_is_within, get_location_contains, get_resource, get_location_overlaps_crosswalk, get_location_overlaps, get_at_location, search_location_by_label


url_prefix = '/v1'

api_v1 = Api(title="LOCI Integration API",
             version="1.2",
             prefix=url_prefix, doc='/'.join([url_prefix, "doc"]),
             default_mediatype="application/json",
             additional_css="/static/material_swagger.css")
ns = api_v1.default_namespace

TRUTHS = ("t", "T", "1")

@ns.route('/linksets')
class Linkset(Resource):
    """Operations on LOCI Linksets"""

    @ns.doc('get_linksets', params=OrderedDict([
        ("count", {"description": "Number of linksets to return.",
                   "required": False, "type": "number", "format": "integer", "default": 1000}),
        ("offset", {"description": "Skip number of linksets before returning count.",
                    "required": False, "type": "number", "format": "integer", "default": 0}),