|
1 | 1 | import re |
| 2 | +import warnings |
| 3 | +import typing |
2 | 4 |
|
3 | 5 | from collections import OrderedDict |
4 | 6 | from copy import deepcopy |
|
17 | 19 | "not_none", |
18 | 20 | "not_none_sorted", |
19 | 21 | "unpack", |
| 22 | + "import_check_view_func", |
20 | 23 | ) |
21 | 24 |
|
22 | 25 |
|
| 26 | +class FlaskCompatibilityWarning(DeprecationWarning): |
| 27 | + pass |
| 28 | + |
| 29 | + |
23 | 30 | def merge(first, second): |
24 | 31 | """ |
25 | 32 | Recursively merges two dictionaries. |
@@ -118,3 +125,43 @@ def unpack(response, default_code=HTTPStatus.OK): |
118 | 125 | return data, code or default_code, headers |
119 | 126 | else: |
120 | 127 | raise ValueError("Too many response values") |
| 128 | + |
| 129 | + |
| 130 | +def to_view_name(view_func: typing.Callable) -> str: |
| 131 | + """Helper that returns the default endpoint for a given |
| 132 | + function. This always is the function name. |
| 133 | +
|
| 134 | + Note: copy of simple flask internal helper |
| 135 | + """ |
| 136 | + assert view_func is not None, "expected view func if endpoint is not provided." |
| 137 | + return view_func.__name__ |
| 138 | + |
| 139 | + |
| 140 | +def import_check_view_func(): |
| 141 | + """ |
| 142 | + Resolve import flask _endpoint_from_view_func. |
| 143 | +
|
| 144 | + Show warning if function cannot be found and provide copy of last known implementation. |
| 145 | +
|
| 146 | + Note: This helper method exists because reoccurring problem with flask function, but |
| 147 | + actual method body remaining the same in each flask version. |
| 148 | + """ |
| 149 | + import importlib.metadata |
| 150 | + |
| 151 | + flask_version = importlib.metadata.version("flask").split(".") |
| 152 | + try: |
| 153 | + if flask_version[0] == "1": |
| 154 | + from flask.helpers import _endpoint_from_view_func |
| 155 | + elif flask_version[0] == "2": |
| 156 | + from flask.scaffold import _endpoint_from_view_func |
| 157 | + elif flask_version[0] == "3": |
| 158 | + from flask.sansio.scaffold import _endpoint_from_view_func |
| 159 | + else: |
| 160 | + warnings.simplefilter("once", FlaskCompatibilityWarning) |
| 161 | + _endpoint_from_view_func = None |
| 162 | + except ImportError: |
| 163 | + warnings.simplefilter("once", FlaskCompatibilityWarning) |
| 164 | + _endpoint_from_view_func = None |
| 165 | + if _endpoint_from_view_func is None: |
| 166 | + _endpoint_from_view_func = to_view_name |
| 167 | + return _endpoint_from_view_func |
0 commit comments