本文整理汇总了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
示例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'
示例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)
示例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')
示例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]
示例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']
示例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]
示例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']
示例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
示例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
示例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)
示例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"
示例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"]
示例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)
示例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)