'How to pass a list of regex in allow_origin_regex in FastAPI CORS Middleware?

So, I have a list of very long and complicated regex which are all for my possible origins for my FastAPI APP. I am using the CORS Middleware as given here: https://fastapi.tiangolo.com/tutorial/cors/#use-corsmiddleware (usage given below)

However, allow_origin_regex argument takes only a string as input and allow_origins argument takes a list of strings as input which I would ideally want for allow_origin_regex as well.

So while I can do this:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins = [
    "http://localhost",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

I can not do this:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

origins_regex = [
    "regex1",
    "regex2",
]

app.add_middleware(
    CORSMiddleware,
    allow_origin_regex=origins_regex,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

How can I achieve this functionality?

I inspected CORS code too in Starlette rep and it confirms about the arguments here: https://github.com/encode/starlette/blob/master/starlette/middleware/cors.py

Code snippet:

class CORSMiddleware:
    def __init__(
        self,
        app: ASGIApp,
        allow_origins: typing.Sequence[str] = (),
        allow_methods: typing.Sequence[str] = ("GET",),
        allow_headers: typing.Sequence[str] = (),
        allow_credentials: bool = False,
        allow_origin_regex: typing.Optional[str] = None,
        expose_headers: typing.Sequence[str] = (),
        max_age: int = 600,
    ) -> None:

Workaround for now is, I am adding all regex using pipe character like "(regex1)|(regex2)".

However, sending a list of regex option exists in Django framework. Also I find combining all long complicated regex in one string as unreadable.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source