Sara Zan 96a538b182
Pylint (import related warnings) and REST API improvements (#2326)
* remove duplicate imports

* fix ungrouped-imports

* Fix wrong-import-position

* Fix unused-import

* pyproject.toml

* Working on wrong-import-order

* Solve wrong-import-order

* fix Pool import

* Move open_search_index_to_document_store and elasticsearch_index_to_document_store in elasticsearch.py

* remove Converter from modeling

* Fix mypy issues on adaptive_model.py

* create es_converter.py

* remove converter import

* change import path in tests

* Restructure REST API to not rely on global vars from search.apy and improve tests

* Fix openapi generator

* Move variable initialization

* Change type of FilterRequest.filters

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2022-04-12 16:41:05 +02:00

51 lines
1.3 KiB
Python

from typing import Type, NewType
import inspect
from contextlib import contextmanager
from threading import Semaphore
from fastapi import Form, HTTPException
from pydantic import BaseModel
class RequestLimiter:
def __init__(self, limit):
self.semaphore = Semaphore(limit - 1)
@contextmanager
def run(self):
acquired = self.semaphore.acquire(blocking=False)
if not acquired:
raise HTTPException(status_code=503, detail="The server is busy processing requests.")
try:
yield acquired
finally:
self.semaphore.release()
StringId = NewType("StringId", str)
def as_form(cls: Type[BaseModel]):
"""
Adds an as_form class method to decorated models. The as_form class method
can be used with FastAPI endpoints
"""
new_params = [
inspect.Parameter(
field.alias,
inspect.Parameter.POSITIONAL_ONLY,
default=(Form(field.default) if not field.required else Form(...)),
)
for field in cls.__fields__.values()
]
async def _as_form(**data):
return cls(**data)
sig = inspect.signature(_as_form)
sig = sig.replace(parameters=new_params)
_as_form.__signature__ = sig # type: ignore
setattr(cls, "as_form", _as_form)
return cls