當前位置: 首頁>>代碼示例>>Python>>正文


Python views.MethodView方法代碼示例

本文整理匯總了Python中flask.views.MethodView方法的典型用法代碼示例。如果您正苦於以下問題:Python views.MethodView方法的具體用法?Python views.MethodView怎麽用?Python views.MethodView使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在flask.views的用法示例。


在下文中一共展示了views.MethodView方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_method_view

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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 
開發者ID:Flask-Middleware,項目名稱:flask-security,代碼行數:26,代碼來源:test_misc.py

示例2: test_blueprint_route_path_parameter_default

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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' 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:25,代碼來源:test_blueprint.py

示例3: test_blueprint_doc_method_view

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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) 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:23,代碼來源:test_blueprint.py

示例4: test_url_with_method

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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') 
開發者ID:chalasr,項目名稱:Flask-P2P,代碼行數:27,代碼來源:helpers.py

示例5: test_api_register_converter

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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] 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:38,代碼來源:test_api.py

示例6: test_blueprint_doc_merged_after_prepare_doc

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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'] 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:35,代碼來源:test_blueprint.py

示例7: test_blueprint_enforce_method_order

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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] 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:37,代碼來源:test_blueprint.py

示例8: test_blueprint_multiple_routes_per_view

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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'] 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:28,代碼來源:test_blueprint.py

示例9: pagination_blueprint

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:37,代碼來源:test_pagination.py

示例10: post_pagination_blueprint

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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 
開發者ID:marshmallow-code,項目名稱:flask-smorest,代碼行數:30,代碼來源:test_pagination.py

示例11: path_helper

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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) 
開發者ID:marshmallow-code,項目名稱:apispec-webframeworks,代碼行數:15,代碼來源:flask.py

示例12: test_path_from_method_view

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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" 
開發者ID:marshmallow-code,項目名稱:apispec-webframeworks,代碼行數:33,代碼來源:test_ext_flask.py

示例13: test_methods_from_rule

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
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"] 
開發者ID:marshmallow-code,項目名稱:apispec-webframeworks,代碼行數:32,代碼來源:test_ext_flask.py

示例14: get

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
def get(self, page=1, size=10):
        return 'MethodView get. 參數{},{}'.format(page, size) 
開發者ID:yangyuexiong,項目名稱:Flask_BestPractices,代碼行數:4,代碼來源:demo.py

示例15: post

# 需要導入模塊: from flask import views [as 別名]
# 或者: from flask.views import MethodView [as 別名]
def post(self, page=1, size=10):
        return 'MethodView post. 參數{},{}'.format(page, size) 
開發者ID:yangyuexiong,項目名稱:Flask_BestPractices,代碼行數:4,代碼來源:demo.py


注:本文中的flask.views.MethodView方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。