Python flask.views.MethodView() Examples

The following are 30 code examples of flask.views.MethodView(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module flask.views , or try the search function .
Example #1
Source File: test_misc.py    From flask-security with MIT License 8 votes vote down vote up
def test_method_view(app, client):
    # auth_required with flask method view
    from flask.views import MethodView
    from flask import render_template_string

    class MyView(MethodView):
        decorators = [auth_required("token", "session")]

        def get(self):
            return render_template_string("Hi view")

    myview = MyView.as_view("myview")

    app.add_url_rule("/myview", view_func=myview, methods=["GET"])

    response = client.get("/myview", follow_redirects=False)
    # should require login
    assert response.status_code == 302
    assert "/login" in response.location

    authenticate(client)
    response = client.get("/myview")
    assert response.status_code == 200
    assert b"Hi view" in response.data 
Example #2
Source File: helpers.py    From Flask with Apache License 2.0 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #3
Source File: helpers.py    From Flask with Apache License 2.0 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #4
Source File: helpers.py    From data with GNU General Public License v3.0 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #5
Source File: helpers.py    From data with GNU General Public License v3.0 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #6
Source File: helpers.py    From data with GNU General Public License v3.0 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #7
Source File: helpers.py    From data with GNU General Public License v3.0 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #8
Source File: helpers.py    From data with GNU General Public License v3.0 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #9
Source File: helpers.py    From syntheticmass with Apache License 2.0 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #10
Source File: helpers.py    From Flask-P2P with MIT License 6 votes vote down vote up
def test_url_with_method(self):
        from flask.views import MethodView
        app = flask.Flask(__name__)
        class MyView(MethodView):
            def get(self, id=None):
                if id is None:
                    return 'List'
                return 'Get %d' % id
            def post(self):
                return 'Create'
        myview = MyView.as_view('myview')
        app.add_url_rule('/myview/', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/<int:id>', methods=['GET'],
                         view_func=myview)
        app.add_url_rule('/myview/create', methods=['POST'],
                         view_func=myview)

        with app.test_request_context():
            self.assert_equal(flask.url_for('myview', _method='GET'),
                              '/myview/')
            self.assert_equal(flask.url_for('myview', id=42, _method='GET'),
                              '/myview/42')
            self.assert_equal(flask.url_for('myview', _method='POST'),
                              '/myview/create') 
Example #11
Source File: test_blueprint.py    From flask-smorest with MIT License 6 votes vote down vote up
def test_blueprint_route_path_parameter_default(self, app, as_method_view):
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')

        if as_method_view:
            @blp.route('/<int:user_id>')
            @blp.route('/', defaults={'user_id': 1})
            class Resource(MethodView):

                def get(self, user_id):
                    pass

        else:
            @blp.route('/<int:user_id>')
            @blp.route('/', defaults={'user_id': 1})
            def func(user_id):
                pass

        api.register_blueprint(blp)
        paths = api.spec.to_dict()['paths']

        assert 'parameters' not in paths['/test/']
        assert paths['/test/{user_id}']['parameters'][0]['name'] == 'user_id' 
Example #12
Source File: test_blueprint.py    From flask-smorest with MIT License 6 votes vote down vote up
def test_blueprint_doc_method_view(self, app):
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')

        @blp.route('/')
        class Resource(MethodView):

            @blp.doc(summary='Dummy put', description='Do dummy put')
            def put(self):
                pass

            @blp.doc(summary='Dummy patch', description='Do dummy patch')
            def patch(self):
                pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        path = spec['paths']['/test/']
        for method in ('put', 'patch', ):
            assert path[method]['summary'] == 'Dummy {}'.format(method)
            assert path[method]['description'] == 'Do dummy {}'.format(method) 
Example #13
Source File: test_pagination.py    From flask-smorest with MIT License 5 votes vote down vote up
def post_pagination_blueprint(
        collection, schemas, as_method_view, custom_params):
    """Return a basic API sample with post-pagination"""

    blp = Blueprint('test', __name__, url_prefix='/test')

    if custom_params:
        page, page_size, max_page_size = CUSTOM_PAGINATION_PARAMS
    else:
        page, page_size, max_page_size = None, None, None

    if as_method_view:
        @blp.route('/')
        class Resource(MethodView):
            @blp.response(schemas.DocSchema(many=True))
            @blp.paginate(Page, page=page,
                          page_size=page_size, max_page_size=max_page_size)
            def get(self):
                return collection.items
    else:
        @blp.route('/')
        @blp.response(schemas.DocSchema(many=True))
        @blp.paginate(Page, page=page,
                      page_size=page_size, max_page_size=max_page_size)
        def get_resources():
            return collection.items

    return blp 
Example #14
Source File: test_api.py    From flask-smorest with MIT License 5 votes vote down vote up
def test_api_register_converter(
            self, app, view_type, custom_format, openapi_version
    ):
        app.config['OPENAPI_VERSION'] = openapi_version
        api = Api(app)
        blp = Blueprint('test', 'test', url_prefix='/test')

        class CustomConverter(BaseConverter):
            pass

        app.url_map.converters['custom_str'] = CustomConverter
        api.register_converter(CustomConverter, 'custom string', custom_format)

        if view_type == 'function':
            @blp.route('/<custom_str:val>')
            def test_func(val):
                pass
        else:
            @blp.route('/<custom_str:val>')
            class TestMethod(MethodView):
                def get(self, val):
                    pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()

        schema = {'type': 'custom string'}
        # If custom_format is None (default), it does not appear in the spec
        if custom_format is not None:
            schema['format'] = 'custom'
        parameter = {'in': 'path', 'name': 'val', 'required': True}
        if openapi_version == '2.0':
            parameter.update(schema)
        else:
            parameter['schema'] = schema
        assert spec['paths']['/test/{val}']['parameters'] == [parameter] 
Example #15
Source File: test_blueprint.py    From flask-smorest with MIT License 5 votes vote down vote up
def test_blueprint_doc_merged_after_prepare_doc(self, app):
        app.config['OPENAPI_VERSION'] = '3.0.2'
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')

        # This is a dummy example. In real-life, use 'example' parameter.
        doc_example = {
            'content': {'application/json': {'example': {'test': 123}}}}

        class ItemSchema(ma.Schema):
            if MARSHMALLOW_VERSION_MAJOR < 3:
                class Meta:
                    strict = True
            test = ma.fields.Int()

        @blp.route('/')
        class Resource(MethodView):

            @blp.doc(**{'requestBody': doc_example})
            @blp.doc(**{'responses': {200: doc_example}})
            @blp.arguments(ItemSchema)
            @blp.response(ItemSchema)
            def get(self):
                pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        get = spec['paths']['/test/']['get']
        assert get['requestBody']['content']['application/json'][
            'example'] == {'test': 123}
        resp = get['responses']['200']
        assert resp['content']['application/json']['example'] == {'test': 123}
        assert 'schema' in resp['content']['application/json'] 
Example #16
Source File: test_blueprint.py    From flask-smorest with MIT License 5 votes vote down vote up
def test_blueprint_enforce_method_order(self, app, http_methods):
        api = Api(app)

        class MyBlueprint(Blueprint):
            HTTP_METHODS = http_methods

        blp = MyBlueprint('test', __name__, url_prefix='/test')

        @blp.route('/')
        class Resource(MethodView):

            def post(self):
                pass

            def put(self):
                pass

            def options(self):
                pass

            def patch(self):
                pass

            def head(self):
                pass

            def delete(self):
                pass

            def get(self):
                pass

        api.register_blueprint(blp)
        methods = list(api.spec.to_dict()['paths']['/test/'].keys())
        assert methods == [m.lower() for m in http_methods] 
Example #17
Source File: utils.py    From flasgger with MIT License 5 votes vote down vote up
def is_valid_method_view(endpoint):
    """
    Return True if obj is MethodView
    """
    klass = endpoint.__dict__.get('view_class', None)
    try:
        return issubclass(klass, MethodView)
    except TypeError:
        return False 
Example #18
Source File: default.py    From Flask-Via with MIT License 5 votes vote down vote up
def __init__(self, url, view, endpoint, **kwargs):
        """ Pluggable router constructor, stores passed arguments on instance.

        .. versionchanged:: 2014.05.19

            * Added ``view`` argument
            * Added ``endpoint`` argument

        Arguments
        ---------
        url : str
            The url to use for the route
        view : class
            The Flask pluggable view class, for example:
            * :class:`flask.views.View`
            * :class:`flask.views.MethodView`
        endpoint : str
            The Flask endpoint name for the view, this is required for Flask
            pluggable views.
        \*\*kwargs :
            Arbitrary keyword arguments for ``add_url_rule``
        """

        self.url = url
        self.view = view
        self.endpoint = endpoint
        self.kwargs = kwargs 
Example #19
Source File: test_default.py    From Flask-Via with MIT License 5 votes vote down vote up
def setUp(self):
        class View(MethodView):

            def get(self):
                return 'foo'

        self.View = View 
Example #20
Source File: test_blueprint.py    From flask-smorest with MIT License 5 votes vote down vote up
def test_blueprint_multiple_routes_per_view(self, app, as_method_view):
        api = Api(app)
        blp = Blueprint('test', __name__, url_prefix='/test')

        if as_method_view:
            # Blueprint.route ensures a different endpoint is used for each
            # route. Otherwise, this would break in Blueprint.route when
            # calling as_view for the second time with the same endpoint.
            @blp.route('/route_1')
            @blp.route('/route_2')
            class Resource(MethodView):

                def get(self):
                    pass

        else:
            @blp.route('/route_1')
            @blp.route('/route_2')
            def func():
                pass

        api.register_blueprint(blp)
        paths = api.spec.to_dict()['paths']

        assert 'get' in paths['/test/route_1']
        assert 'get' in paths['/test/route_2'] 
Example #21
Source File: test_views.py    From flask-allows with MIT License 5 votes vote down vote up
def test_requires_works_as_method_decorator(app, ismember, guest):
    class MembersCanPost(MethodView):
        @requires(ismember)
        def post(self):
            return "hello"

    Allows(app=app, identity_loader=lambda: guest)
    context = app.test_request_context("/", method="POST")

    with pytest.raises(Forbidden), app.app_context(), context:
        MembersCanPost.as_view("memberonly")() 
Example #22
Source File: demo.py    From Flask_BestPractices with MIT License 5 votes vote down vote up
def delete(self, page=1, size=10):
        return 'MethodView delete. 参数{},{}'.format(page, size) 
Example #23
Source File: demo.py    From Flask_BestPractices with MIT License 5 votes vote down vote up
def put(self, page=1, size=10):
        return 'MethodView put. 参数{},{}'.format(page, size) 
Example #24
Source File: demo.py    From Flask_BestPractices with MIT License 5 votes vote down vote up
def post(self, page=1, size=10):
        return 'MethodView post. 参数{},{}'.format(page, size) 
Example #25
Source File: demo.py    From Flask_BestPractices with MIT License 5 votes vote down vote up
def get(self, page=1, size=10):
        return 'MethodView get. 参数{},{}'.format(page, size) 
Example #26
Source File: test_ext_flask.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def test_methods_from_rule(self, app, spec):
        class HelloApi(MethodView):
            """Greeting API.
            ---
            x-extension: global metadata
            """

            def get(self):
                """A greeting endpoint.
                ---
                description: get a greeting
                responses:
                    200:
                        description: said hi
                """
                return "hi"

            def post(self):
                return "hi"

            def delete(self):
                return "hi"

        method_view = HelloApi.as_view("hi")
        app.add_url_rule("/hi", view_func=method_view, methods=("GET", "POST"))
        spec.path(view=method_view)
        paths = get_paths(spec)
        assert "get" in paths["/hi"]
        assert "post" in paths["/hi"]
        assert "delete" not in paths["/hi"] 
Example #27
Source File: test_ext_flask.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def test_path_from_method_view(self, app, spec):
        class HelloApi(MethodView):
            """Greeting API.
            ---
            x-extension: global metadata
            """

            def get(self):
                """A greeting endpoint.
                ---
                description: get a greeting
                responses:
                    200:
                        description: said hi
                """
                return "hi"

            def post(self):
                return "hi"

        method_view = HelloApi.as_view("hi")
        app.add_url_rule("/hi", view_func=method_view, methods=("GET", "POST"))
        spec.path(view=method_view)
        expected = {
            "description": "get a greeting",
            "responses": {"200": {"description": "said hi"}},
        }
        paths = get_paths(spec)
        assert paths["/hi"]["get"] == expected
        assert paths["/hi"]["post"] == {}
        assert paths["/hi"]["x-extension"] == "global metadata" 
Example #28
Source File: flask.py    From apispec-webframeworks with MIT License 5 votes vote down vote up
def path_helper(self, operations, *, view, app=None, **kwargs):
        """Path helper that allows passing a Flask view function."""
        rule = self._rule_for_view(view, app=app)
        operations.update(yaml_utils.load_operations_from_docstring(view.__doc__))
        if hasattr(view, "view_class") and issubclass(view.view_class, MethodView):
            for method in view.methods:
                if method in rule.methods:
                    method_name = method.lower()
                    method = getattr(view.view_class, method_name)
                    operations[method_name] = yaml_utils.load_yaml_from_docstring(
                        method.__doc__
                    )
        return self.flaskpath2openapi(rule.rule) 
Example #29
Source File: test_pagination.py    From flask-smorest with MIT License 5 votes vote down vote up
def pagination_blueprint(collection, schemas, as_method_view, custom_params):
    """Return a basic API sample with pagination"""

    blp = Blueprint('test', __name__, url_prefix='/test')

    if custom_params:
        page, page_size, max_page_size = CUSTOM_PAGINATION_PARAMS
    else:
        page, page_size, max_page_size = None, None, None

    if as_method_view:
        @blp.route('/')
        class Resource(MethodView):
            @blp.response(schemas.DocSchema(many=True))
            @blp.paginate(
                page=page, page_size=page_size, max_page_size=max_page_size)
            def get(self, pagination_parameters):
                pagination_parameters.item_count = len(collection.items)
                return collection.items[
                    pagination_parameters.first_item:
                    pagination_parameters.last_item + 1
                ]
    else:
        @blp.route('/')
        @blp.response(schemas.DocSchema(many=True))
        @blp.paginate(
            page=page, page_size=page_size, max_page_size=max_page_size)
        def get_resources(pagination_parameters):
            pagination_parameters.item_count = len(collection.items)
            return collection.items[
                pagination_parameters.first_item:
                pagination_parameters.last_item + 1
            ]

    return blp 
Example #30
Source File: test_blueprint.py    From flask-smorest with MIT License 4 votes vote down vote up
def test_blueprint_doc_info_from_docstring(self, app, delimiter):
        api = Api(app)

        class MyBlueprint(Blueprint):
            # Check delimiter default value
            if delimiter is not False:
                DOCSTRING_INFO_DELIMITER = delimiter

        blp = MyBlueprint('test', __name__, url_prefix='/test')

        @blp.route('/')
        class Resource(MethodView):

            def get(self):
                """Get summary"""

            def put(self):
                """Put summary

                Put description
                ---
                Private docstring
                """

            def patch(self):
                pass

        api.register_blueprint(blp)
        spec = api.spec.to_dict()
        path = spec['paths']['/test/']

        assert path['get']['summary'] == 'Get summary'
        assert 'description' not in path['get']
        assert path['put']['summary'] == 'Put summary'
        if delimiter is None:
            assert (
                path['put']['description'] ==
                'Put description\n---\nPrivate docstring'
            )
        else:
            assert path['put']['description'] == 'Put description'
        assert 'summary' not in path['patch']
        assert 'description' not in path['patch']