def traced_init(wrapped, instance, args, kwargs): mw = kwargs.pop("middleware", []) mw.insert( 0, Middleware(TraceMiddleware, integration_config=config.fastapi, span_modifier=span_modifier)) kwargs.update({"middleware": mw}) wrapped(*args, **kwargs)
def _wrapper(wrapped, instance, args, kwargs): """Set middleware to trace Fast api. Fastapi has been built on starlett and pydantic frameworks. Request and response flow has been handled by starlette that is a lightweight ASGI framework. Fastapi has an class called APIRouter that extends starlett Router class which is used to handle connections by starlette. The middleware should be an ASGI Middleware. Thus, the __call__(scope, receive, send) function should be implemented. By default, starlette add two middleware except user defined middlewares which are ServerErrorMiddleware and ExceptionMiddleware. Middleware list seems like [ServerErrorMiddleware, user_defined_middlewares, ExceptionMiddleware]. This list added in reversed order. Therefore, when we add our FastapiMiddleware to the zero index, it is placed top of middleware hierarchy. Args: wrapped (module): Wrapped module instance (function): Module enter point args (list): Wrapped function list of arguments kwargs (dict): Wrapped function key:value arguments """ from fastapi.middleware import Middleware from thundra.wrappers.fastapi.middleware import ThundraMiddleware from thundra.wrappers.fastapi.fastapi_wrapper import FastapiWrapper middlewares = kwargs.pop("middleware", []) middlewares.insert( 0, Middleware(ThundraMiddleware, wrapper=FastapiWrapper.get_instance())) kwargs.update({"middleware": middlewares}) wrapped(*args, **kwargs)
release=f"{os.getenv('CURRENT_PLATFORM')} Release " + (f"{os.getenv('GIT_REV', '00000000')[:8]}" if os.getenv("CURRENT_PLATFORM") != "Heroku" else f"{os.getenv('HEROKU_RELEASE_VERSION')}:{os.getenv('HEROKU_SLUG_DESCRIPTION')}" ), dsn=os.getenv("SENTRY_API_DSN"), integrations=[RedisIntegration()], ) FRONTEND_URL = os.getenv("FRONTEND_URL", "https://api.example.com") SESSION_COOKIE_EXPIRE = 259200 # 3 days DATABASE_SESSION_EXPIRE = 21600 # 6 hours DATABASE_SESSION_USER_EXPIRE = 259200 # 3 days middleware = [ Middleware(SentryAsgiMiddleware), Middleware( CORSMiddleware, allow_origins=[FRONTEND_URL], allow_methods=["GET", "POST"], allow_credentials=True, ), Middleware( SessionMiddleware, secret_key=os.getenv("SESSION_SECRET_KEY"), max_age=SESSION_COOKIE_EXPIRE, same_site="lax", https_only=True, ), Middleware(GZipMiddleware, minimum_size=1000) ]
from fastapi.middleware import Middleware from fastapi.middleware.cors import CORSMiddleware import pandas as pd from starlette.responses import FileResponse import matplotlib.pyplot as plt from matplotlib.figure import Figure import numpy as np import cnn_check DATA_DIR_NAME = 'datasets' middleware = [ Middleware(CORSMiddleware, allow_origins=['*'], allow_credentials=True, allow_methods=['*'], allow_headers=['*']) ] app = FastAPI( title='Blood classifier API', middleware=middleware, ) @app.post("/upload/") def infer(file: UploadFile = File(...)): f_name = file.filename.split('.') content_type = file.content_type.split('/') if 'zip' not in f_name and 'zip' not in content_type:
def init_dynatrace(wrapped, instance, args, kwargs): middlewares = kwargs.pop("middleware", []) middlewares.insert(0, Middleware(DynatraceASGIMiddleware)) kwargs.update({"middleware": middlewares}) return wrapped(*args, **kwargs)
train, wsi_infer, ) from monailabel.interfaces.utils.app import app_instance, clear_cache app = FastAPI( title=settings.MONAI_LABEL_PROJECT_NAME, openapi_url="/openapi.json", docs_url=None, redoc_url="/docs", middleware=[ Middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.MONAI_LABEL_CORS_ORIGINS] if settings.MONAI_LABEL_CORS_ORIGINS else ["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) ], ) static_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "endpoints", "static") project_root_absolute = pathlib.Path(__file__).parent.parent.resolve() app.mount( "/static", StaticFiles(directory=os.path.join(project_root_absolute, "monailabel", "endpoints", "static")), name="static", )
except RequestValidationError as exc: body = await request.body() detail = {"errors": exc.errors(), "body": body.decode()} logger.info("Request Validation Error: %s", str(exc)) raise HTTPException( # pylint: disable=raise-missing-from status_code=422, detail=detail) return custom_route_handler middleware = [ Middleware( CORSMiddleware, allow_origins=runtime_config.allowed_origins.split(","), allow_credentials=True, allow_methods=["GET", "POST"], allow_headers=["*"], ) ] app = FastAPI( title="Hetida Designer Runtime API", description="Hetida Designer Runtime Web Services API", version=VERSION, root_path=runtime_config.swagger_prefix, middleware=middleware, ) app.router.route_class = AdditionalLoggingRoute
from fastapi.middleware import Middleware from fastapi.middleware.cors import CORSMiddleware middlewares = [Middleware(CORSMiddleware, allow_origins=["*"])]
MultipleSourcesResponse, PostMetadatum, StructureResponse, StructureSink, StructureSource, StructureThingNode, TimeseriesRecord, ) logger = logging.getLogger(__name__) middleware = [ Middleware( CORSMiddleware, allow_origins=demo_adapter_config.allowed_origins.split(","), allow_credentials=True, allow_methods=["GET", "POST"], allow_headers=["*"], expose_headers=["Data-Attributes"], # is this necessary? ) ] app = FastAPI( title="Hetida Designer Python Demo Adapter API", description="Hetida Designer Python Demo Adapter Web Services API", version=VERSION, root_path=demo_adapter_config.swagger_prefix, middleware=middleware, ) class AdditionalLoggingRoute(APIRoute):
from fastapi.middleware import Middleware from fastapi.middleware.cors import CORSMiddleware middleware = [ Middleware( CORSMiddleware, allow_origin_regex=r'^.*$', allow_methods=['*'], allow_headers=[ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ], allow_credentials=True, ) ]