Description
I no longer pass a "context" to my templates but rather the view itself. If something must be available within a template I simply add it as an attribute to the view, self.ATTRIBUTE=DATA
. Flask seems to clear these attributes for each request and haven't encountered any persistence issues so far. In some cases it is handy to know what other routes the view serves e.g. the template served by VIEW:index
might need to reference VIEW:get
as an example. Is there a means of accessing a list of such routes ?
I went through the documentation and the source code and it seems the routes are generated by the method register
but the result of this is not retained for later reference. Is it perhaps possible to provide a property for this ? Presently I am using the following :
class BaseView(FlaskView):
...
@property
def _routes_(self):
predicate = lambda item: inspect.ismethod(item) \
and (hasattr(item, "__self__") and not item.__self__ in inspect.getmro(self.__class__)) \
and not item.__name__.startswith("_") \
and not item.__name__.startswith("before_") \
and not item.__name__.startswith("after_") \
and not item.__name__ == "<lambda>" \ # ignore lambdas (Their names `<lambda>` do not match against `self.excluded_methods`, Alternatively compare the keys from `getmembers` against `excluded_methods`)
and not item.__name__ in self.excluded_methods
# hasattr(item, "_rule_cache")
endpoints = inspect.getmembers(self, predicate=predicate)
return [(member, endpoint or key, list(paths))
for _, member in inspect.getmembers(self, predicate=predicate)
for key, rules in member._rule_cache.items()
for endpoint, paths in groupby(rules, key=lambda item: item[-1]['endpoint']) if
hasattr(member, "_rule_cache")]
However this requires one to decorate all their endpoints with @route
as there is no _rule_set
for routes that do not have this decoration.
Alternatively is it possible to return the endpoint for a given method e.g. VIEW.endpoint(VIEW.METHOD) => view:method
to pass to url_for
?
Activity