Last active
April 7, 2021 14:01
-
-
Save connebs/d9ab23a29bd149115c25a17023717c55 to your computer and use it in GitHub Desktop.
Subclass of `flask_rest_api.Blueprint` that is compatible with `flask_classful`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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