Changeset View
Changeset View
Standalone View
Standalone View
swh/core/api/negotiation.py
Show All 18 Lines | |||||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||||
# SOFTWARE. | # SOFTWARE. | ||||
# | # | ||||
from collections import defaultdict | from collections import defaultdict | ||||
import functools | |||||
from inspect import getcallargs | from inspect import getcallargs | ||||
from typing import Any, Callable, DefaultDict, List, NoReturn, Optional, Type | from typing import Any, Callable, DefaultDict, List, NoReturn, Optional, Type | ||||
from decorator import decorator | |||||
from requests import Response | from requests import Response | ||||
class FormatterNotFound(Exception): | class FormatterNotFound(Exception): | ||||
pass | pass | ||||
class Formatter: | class Formatter: | ||||
▲ Show 20 Lines • Show All 99 Lines • ▼ Show 20 Lines | def _abort(self, status_code: int, err: Optional[str] = None) -> NoReturn: | ||||
"_abort() should be implemented in framework-specific " | "_abort() should be implemented in framework-specific " | ||||
"subclasses of Negotiator" | "subclasses of Negotiator" | ||||
) | ) | ||||
def negotiate( | def negotiate( | ||||
negotiator_cls: Type[Negotiator], formatter_cls: Type[Formatter], *args, **kwargs | negotiator_cls: Type[Negotiator], formatter_cls: Type[Formatter], *args, **kwargs | ||||
) -> Callable: | ) -> Callable: | ||||
def _negotiate(f, *args, **kwargs): | def decorator(f): | ||||
return f.negotiator(*args, **kwargs) | |||||
def decorate(f): | |||||
if not hasattr(f, "negotiator"): | if not hasattr(f, "negotiator"): | ||||
f.negotiator = negotiator_cls(f) | f.negotiator = negotiator_cls(f) | ||||
f.negotiator.register_formatter(formatter_cls, *args, **kwargs) | f.negotiator.register_formatter(formatter_cls, *args, **kwargs) | ||||
return decorator(_negotiate, f) | |||||
return decorate | @functools.wraps(f) | ||||
def newf(*args, **kwargs): | |||||
return f.negotiator(*args, **kwargs) | |||||
return newf | |||||
return decorator |