Skip to content

Instantly share code, notes, and snippets.

@connebs
Last active April 7, 2021 14:01
Show Gist options
  • Select an option

  • Save connebs/d9ab23a29bd149115c25a17023717c55 to your computer and use it in GitHub Desktop.

Select an option

Save connebs/d9ab23a29bd149115c25a17023717c55 to your computer and use it in GitHub Desktop.
Subclass of `flask_rest_api.Blueprint` that is compatible with `flask_classful`
from flask_rest_api import Blueprint
class ClassfulBlueprint(Blueprint):
"""A subclass of flask_rest_api.Blueprint that stores endpoint documentation
not using :meth: `Blueprint.route` but instead with :meth: `Blueprint.add_url_rule`.
Since :meth: `Blueprint.route` should never be used from a `ClassfulBlueprint`
instance, it throws an error if you try to call it.
"""
def __getattribute__(self, name):
if name in ['route']:
raise AttributeError(name)
else:
return super(ClassfulBlueprint, self).__getattribute__(name)
def __dir__(self):
return sorted(
(set(dir(self.__class__)) | set(self.__dict__.keys())) - set(['route'])
)
def add_url_rule(self, rule, endpoint, view_func, **options):
""" Like :meth: `Flask.Blueprint.add_url_rule, but with a small difference;
it does the job that :meth: `Blueprint.route` would normally do in flask_rest_api
by storing the endpoint documentation on the `Blueprint` instance.
Additionally, `flask_classful` *always* calls `Blueprint.add_url_rule` with both
an endpoint and a view_func specified, so those are no longer optional.
"""
assert '.' not in endpoint, "Blueprint endpoints should not contain dots"
if hasattr(view_func, '__name__'):
assert '.' not in view_func.__name__, "Blueprint view function name should not contain dots"
self.record(lambda s: s.add_url_rule(rule, endpoint, view_func, **options))
# store endpoint documentation (as `Blueprint.route` would've)
self._store_endpoint_docs(endpoint, view_func, **options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment