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
Provenance
- Commit
dcf2198- Tree
bf9428f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
1c8097b
3 files changed+147 added−3 removed
modified:flask/app.py+8 added-3 removed
640 unmodified lines641 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 = True44 unmodified lines695 """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 = True74 unmodified lines783 self.add_url_rule(rule, None, f, **options)784 return f785 return decorator786 781-787 def endpoint(self, endpoint):788 """A decorator to register a function as an endpoint.789 Example::790 510 unmodified linesadded:flask/views.py+102 added
1+# -*- coding: utf-8 -*-2+"""3+ flask.views4+ ~~~~~~~~~~~5+6+ This module provides class based views inspired by the ones in Django.7+8+ :copyright: (c) 2011 by Armin Ronacher.9+ :license: BSD, see LICENSE for more details.10+"""11+from .globals import request12+13+14+http_method_funcs = frozenset(['get', 'post', 'head', 'options',15+ 'delete', 'put', 'trace'])16+17+18+19+class 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::25+26+ class MyView(View):27+ methods = ['GET']28+29+ def dispatch_request(self, name):30+ return 'Hello %s!' % name31+32+ app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))33+ """34+35+ methods = None36+37+ def dispatch_request(self):38+ raise NotImplementedError()39+40+ @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.46+47+ 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 view58+59+60+class MethodViewType(type):61+62+ 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 rv76+77+78+class 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::85+86+ class CounterAPI(MethodView):87+88+ def get(self):89+ return session.get('counter', 0)90+91+ def post(self):92+ session['counter'] = session.get('counter', 0) + 193+ return 'OK'94+95+ app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))96+ """97+ __metaclass__ = MethodViewType98+99+ 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 lines13 import os14 import re15 import sys16 import flask17+import flask.views18 import unittest19 import warnings20 from threading import Thread21 from logging import StreamHandler1 unmodified line23 from functools import update_wrapper24 from datetime import datetime25 from werkzeug import parse_date, parse_options_header26 from werkzeug.exceptions import NotFound27+from werkzeug.http import parse_set_header28 from jinja2 import TemplateNotFound29 from cStringIO import StringIO30 31 example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')1722 unmodified lines1754 finally:1755 flask.got_request_exception.disconnect(record, app)1756 1757 1758+class ViewTestCase(unittest.TestCase):1759+1760+ def common_test(self, app):1761+ c = app.test_client()1762+1763+ 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'])1768+1769+ def test_basic_view(self):1770+ app = flask.Flask(__name__)1771+1772+ class Index(flask.views.View):1773+ methods = ['GET', 'POST']1774+ def dispatch_request(self):1775+ return flask.request.method1776+1777+ app.add_url_rule('/', view_func=Index.as_view('index'))1778+ self.common_test(app)1779+1780+ def test_method_based_view(self):1781+ app = flask.Flask(__name__)1782+1783+ class Index(flask.views.MethodView):1784+ def get(self):1785+ return 'GET'1786+ def post(self):1787+ return 'POST'1788+1789+ app.add_url_rule('/', view_func=Index.as_view('index'))1790+ self.common_test(app)1791+1792 class DeprecationsTestCase(unittest.TestCase):1793 1794 def test_init_jinja_globals(self):1795 class MyFlask(flask.Flask):24 unmodified lines1820 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