Skip to content
Myr

Added class based views

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 1c8097b · Browse files · 3 files+147 added−3 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+147 added−3 removed

  • tests:+37 added−0 removed
  • other:+110 added−3 removed

3 files+147 added−3 removed

modified:flask/app.py+8 added-3 removed
640 unmodified lines
641 first_registration = False642 if blueprint.name in self.blueprints:643 assert self.blueprints[blueprint.name] is blueprint, \644 'A blueprint\'s name collision ocurred between %r and ' \645 '%r. Both share the same name "%s"' % \645 '%r. Both share the same name "%s". Blueprints that ' \646 'are created on the fly need unique names.' % \647 (blueprint, self.blueprints[blueprint.name], blueprint.name)648 else:649 self.blueprints[blueprint.name] = blueprint650 first_registration = True
44 unmodified lines
695 """696 if endpoint is None:697 endpoint = _endpoint_from_view_func(view_func)698 options['endpoint'] = endpoint698 methods = options.pop('methods', ('GET',))699 methods = options.pop('methods', None)700 # if the methods are not given and the view_func object knows its701 # methods we can use that instead. If neither exists, we go with702 # a tuple of only `GET` as default.703 if methods is None:704 methods = getattr(view_func, 'methods', None) or ('GET',)705 provide_automatic_options = False706 if 'OPTIONS' not in methods:707 methods = tuple(methods) + ('OPTIONS',)708 provide_automatic_options = True
74 unmodified lines
783 self.add_url_rule(rule, None, f, **options)784 return f785 return decorator786781787 def endpoint(self, endpoint):788 """A decorator to register a function as an endpoint.789 Example::790
510 unmodified lines
added:flask/views.py+102 added
1# -*- coding: utf-8 -*-2"""3 flask.views4 ~~~~~~~~~~~56 This module provides class based views inspired by the ones in Django.78 :copyright: (c) 2011 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from .globals import request121314http_method_funcs = frozenset(['get', 'post', 'head', 'options',15 'delete', 'put', 'trace'])16171819class View(object):20 """Alternative way to use view functions. A subclass has to implement21 :meth:`dispatch_request` which is called with the view arguments from22 the URL routing system. If :attr:`methods` is provided the methods23 do not have to be passed to the :meth:`~flask.Flask.add_url_rule`24 method explicitly::2526 class MyView(View):27 methods = ['GET']2829 def dispatch_request(self, name):30 return 'Hello %s!' % name3132 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))33 """3435 methods = None3637 def dispatch_request(self):38 raise NotImplementedError()3940 @classmethod41 def as_view(cls, name, *class_args, **class_kwargs):42 """Converts the class into an actual view function that can be43 used with the routing system. What it does internally is generating44 a function on the fly that will instanciate the :class:`View`45 on each request and call the :meth:`dispatch_request` method on it.4647 The arguments passed to :meth:`as_view` are forwarded to the48 constructor of the class.49 """50 def view(*args, **kwargs):51 self = cls(*class_args, **class_kwargs)52 return self.dispatch_request(*args, **kwargs)53 view.__name__ = name54 view.__doc__ = cls.__doc__55 view.__module__ = cls.__module__56 view.methods = cls.methods57 return view585960class MethodViewType(type):6162 def __new__(cls, name, bases, d):63 rv = type.__new__(cls, name, bases, d)64 if rv.methods is None:65 methods = []66 for key, value in d.iteritems():67 if key in http_method_funcs:68 methods.append(key.upper())69 # if we have no method at all in there we don't want to70 # add a method list. (This is for instance the case for71 # the baseclass or another subclass of a base method view72 # that does not introduce new methods).73 if methods:74 rv.methods = methods75 return rv767778class MethodView(View):79 """Like a regular class based view but that dispatches requests to80 particular methods. For instance if you implement a method called81 :meth:`get` it means you will response to ``'GET'`` requests and82 the :meth:`dispatch_request` implementation will automatically83 forward your request to that. Also :attr:`options` is set for you84 automatically::8586 class CounterAPI(MethodView):8788 def get(self):89 return session.get('counter', 0)9091 def post(self):92 session['counter'] = session.get('counter', 0) + 193 return 'OK'9495 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))96 """97 __metaclass__ = MethodViewType9899 def dispatch_request(self, *args, **kwargs):100 meth = getattr(self, request.method.lower(), None)101 assert meth is not None, 'Not implemented method'102 return meth(*args, **kwargs)
modified:tests/flask_tests.py+37 added
12 unmodified lines
13import os14import re15import sys16import flask17import flask.views18import unittest19import warnings20from threading import Thread21from logging import StreamHandler
1 unmodified line
23from functools import update_wrapper24from datetime import datetime25from werkzeug import parse_date, parse_options_header26from werkzeug.exceptions import NotFound27from werkzeug.http import parse_set_header28from jinja2 import TemplateNotFound29from cStringIO import StringIO3031example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')
1722 unmodified lines
1754 finally:1755 flask.got_request_exception.disconnect(record, app)175617571758class ViewTestCase(unittest.TestCase):17591760 def common_test(self, app):1761 c = app.test_client()17621763 self.assertEqual(c.get('/').data, 'GET')1764 self.assertEqual(c.post('/').data, 'POST')1765 self.assertEqual(c.put('/').status_code, 405)1766 meths = parse_set_header(c.open('/', method='OPTIONS').headers['Allow'])1767 self.assertEqual(sorted(meths), ['GET', 'HEAD', 'OPTIONS', 'POST'])17681769 def test_basic_view(self):1770 app = flask.Flask(__name__)17711772 class Index(flask.views.View):1773 methods = ['GET', 'POST']1774 def dispatch_request(self):1775 return flask.request.method17761777 app.add_url_rule('/', view_func=Index.as_view('index'))1778 self.common_test(app)17791780 def test_method_based_view(self):1781 app = flask.Flask(__name__)17821783 class Index(flask.views.MethodView):1784 def get(self):1785 return 'GET'1786 def post(self):1787 return 'POST'17881789 app.add_url_rule('/', view_func=Index.as_view('index'))1790 self.common_test(app)17911792class DeprecationsTestCase(unittest.TestCase):17931794 def test_init_jinja_globals(self):1795 class MyFlask(flask.Flask):
24 unmodified lines
1820 suite.addTest(unittest.makeSuite(SendfileTestCase))1821 suite.addTest(unittest.makeSuite(LoggingTestCase))1822 suite.addTest(unittest.makeSuite(ConfigTestCase))1823 suite.addTest(unittest.makeSuite(SubdomainTestCase))1824 suite.addTest(unittest.makeSuite(ViewTestCase))1825 suite.addTest(unittest.makeSuite(DeprecationsTestCase))1826 if flask.json_available:1827 suite.addTest(unittest.makeSuite(JSONTestCase))1828 if flask.signals_available:
8 unmodified lines