Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add the ability to combine MethodViews #1936

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion flask/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,12 +102,16 @@ def view(*args, **kwargs):
return view


def get_methods(cls):
return getattr(cls, 'methods', []) or []


class MethodViewType(type):

def __new__(cls, name, bases, d):
rv = type.__new__(cls, name, bases, d)
if 'methods' not in d:
methods = set(rv.methods or [])
methods = set(m for b in bases for m in get_methods(b))

This comment was marked as off-topic.

This comment was marked as off-topic.

This comment was marked as off-topic.

This comment was marked as off-topic.

for key in d:
if key in http_method_funcs:
methods.add(key.upper())
Expand Down
42 changes: 42 additions & 0 deletions tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,45 @@ def dispatch_request(self):

# But these tests should still pass. We just log a warning.
common_test(app)

def test_multiple_inheritance():
app = flask.Flask(__name__)

class GetView(flask.views.MethodView):
def get(self):
return 'GET'

class DeleteView(flask.views.MethodView):
def delete(self):
return 'DELETE'

class GetDeleteView(GetView, DeleteView):
pass

app.add_url_rule('/', view_func=GetDeleteView.as_view('index'))

c = app.test_client()
assert c.get('/').data == b'GET'
assert c.delete('/').data == b'DELETE'
assert sorted(GetDeleteView.methods) == ['DELETE', 'GET']

def test_remove_method_from_parent():
app = flask.Flask(__name__)

class GetView(flask.views.MethodView):
def get(self):
return 'GET'

class OtherView(flask.views.MethodView):
def post(self):
return 'POST'

class View(GetView, OtherView):
methods = ['GET']

app.add_url_rule('/', view_func=View.as_view('index'))

c = app.test_client()
assert c.get('/').data == b'GET'
assert c.post('/').status_code == 405
assert sorted(View.methods) == ['GET']