/
flask_classy.py
142 lines (110 loc) · 4.46 KB
/
flask_classy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""
Flask-Classy
------------
Class based views for the Flask microframework.
:copyright: (c) 2012 by Freedom Dumlao.
:license: BSD, see LICENSE for more details.
"""
import inspect
def route(rule, **options):
"""A decorator that is used to define custom routes for methods in
FlaskView subclasses. The format is exactly the same as Flask's
`@app.route` decorator.
"""
def decorator(f):
f.route = (rule, options)
return f
return decorator
class FlaskView(object):
"""Base view for any class based views implemented with Flask-Classy. Will
automatically configure routes when registered with a Flask app instance.
"""
@classmethod
def register(cls, app, route_base=None):
"""Registers a FlaskView class for use with a specific instance of a
Flask app. Any methods not prefixes with an underscore are candidates
to be routed and will have routes registered when this method is
called.
:param app: an instance of a Flask application
:param route_base: the base path to use for all routes registered for
this class
"""
if cls is FlaskView:
raise TypeError("cls must be a subclass of FlaskVew, not FlaskView itself")
if route_base:
cls.route_base = route_base
members = cls.find_member_methods()
special_methods = ["get", "put", "post", "delete", "index"]
id_methods = ["get", "put", "delete"]
for name, value in members:
proxy = cls.make_proxy_method(name)
route_name = cls.build_route_name(name)
if hasattr(value, "route"):
rule, options = value.route
rule = cls.build_rule(rule)
app.add_url_rule(rule, route_name, proxy, **options)
elif name in special_methods:
methods = None
if name in ["get", "index"]:
methods = ["GET"]
elif name == "put":
methods = ["PUT"]
elif name == "post":
methods = ["POST"]
elif name == "delete":
methods = ["DELETE"]
if name in id_methods:
rule = "/<id>/"
else:
rule = "/"
rule = cls.build_rule(rule)
app.add_url_rule(rule, route_name, proxy, methods=methods)
else:
rule = cls.build_rule('/%s/' % name)
app.add_url_rule(rule, route_name, proxy)
@classmethod
def make_proxy_method(cls, name):
"""Creates a proxy function that can be used by Flasks routing. The
proxy instantiates the FlaskView subclass and calls the appropriate
method.
:param name: the name of the method to create a proxy for
"""
def proxy(*args, **kwargs):
i = cls()
m = getattr(i, name)
return m(*args, **kwargs)
return proxy
@classmethod
def find_member_methods(cls):
"""Returns a list of methods that can be routed to"""
base_members = dir(FlaskView)
all_members = inspect.getmembers(cls, predicate=inspect.ismethod)
return [member for member in all_members
if not member[0] in base_members
and not member[0].startswith("_")]
@classmethod
def build_rule(cls, rule):
"""Creates a routing rule based on either the class name (minus the
'View' suffix) or the defined `route_base` attribute of the class
:param rule: the path portion that should be appended to the
route base
"""
if hasattr(cls, "route_base"):
route_base = cls.route_base
else:
if cls.__name__.endswith("View"):
route_base = cls.__name__[:-4].lower()
else:
route_base = cls.__name__.lower()
if not route_base.startswith("/"):
route_base = "/" + route_base
if route_base.endswith("/") and rule.startswith("/"):
rule = rule.lstrip("/")
return route_base + rule
@classmethod
def build_route_name(cls, method_name):
"""Creates a unique route name based on the combination of the class
name with the method name.
:param method_name: the method name to use when building a route name
"""
return cls.__name__ + ":%s" % method_name