fastapi icon indicating copy to clipboard operation
fastapi copied to clipboard

How can I pass the configuration in the app?

Open Anti-user opened this issue 7 years ago • 28 comments

How can I pass the configuration in the app? Can I do it in some way like it was in Flask with app.config, or this framework manages it differently?

Anti-user avatar Sep 05 '19 15:09 Anti-user

You will be able to pass anything you want to app.state I've starlette is on 0.12.9

Le jeu. 5 sept. 2019 à 5:14 PM, Artsiom Dolatau [email protected] a écrit :

How can I pass the configuration in the app? Can I do it in some simple way like it was in Flask with app.config, or this framework doesn't support even this?

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/tiangolo/fastapi/issues/508?email_source=notifications&email_token=AAINSPVIGGYSLBWKF7TYFOLQIEO3PA5CNFSM4IT7DHBKYY3PNVWWK3TUL52HS4DFUVEXG43VMWVGG33NNVSW45C7NFSM4HJSGYQA, or mute the thread https://github.com/notifications/unsubscribe-auth/AAINSPQ5XZ73CSBHDJMJSPTQIEO3PANCNFSM4IT7DHBA .

euri10 avatar Sep 05 '19 16:09 euri10

I typically use a subclass of pydantic.BaseSettings so I can read config from the environment, then create an lru_cached function that returns a config instance, then wherever I need access to a config setting I just call the lru_cached function to get the config and read the setting off of it.

dmontagu avatar Sep 05 '19 20:09 dmontagu

i have the same question here - what is the equivalent of app.config in flask ? https://flask.palletsprojects.com/en/1.1.x/config/

to specific, are there any convenience functions similar to

app.config.from_object('yourapplication.default_settings')
app.config.from_envvar('YOURAPPLICATION_SETTINGS')

we need to load different configurations based on production or staging environment.

sandys avatar Sep 17 '19 17:09 sandys

No there are no convenience functions like that.

Le mar. 17 sept. 2019 à 7:53 PM, Sandeep Srinivasa [email protected] a écrit :

i have the same question here - what is the equivalent of app.config in flask ? https://flask.palletsprojects.com/en/1.1.x/config/

to specific, are there any convenience functions similar to

app.config.from_object('yourapplication.default_settings') app.config.from_envvar('YOURAPPLICATION_SETTINGS')

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/tiangolo/fastapi/issues/508?email_source=notifications&email_token=AAINSPVXCBZNPHZZCCHLVVDQKEKQFA5CNFSM4IT7DHBKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD65LOMA#issuecomment-532330288, or mute the thread https://github.com/notifications/unsubscribe-auth/AAINSPQKZC5QSJGFW5YRFKDQKEKQFANCNFSM4IT7DHBA .

euri10 avatar Sep 17 '19 17:09 euri10

@sandys does pydantic BaseSettings not work for you? It allows you to pass values at instantiation time or via environment variable (and is type safe to boot!).

A more complete example:

from functools import lru_cache
from typing import List

from pydantic import BaseSettings


class APISettings(BaseSettings):
    api_v1_route: str = "/api/v1"
    openapi_route: str = "/api/v1/openapi.json"

    backend_cors_origins_str: str = ""  # Should be a comma-separated list of origins

    debug: bool = False
    debug_exceptions: bool = False
    disable_superuser_dependency: bool = False
    include_admin_routes: bool = False

    @property
    def backend_cors_origins(self) -> List[str]:
        return [x.strip() for x in self.backend_cors_origins_str.split(",") if x]

    class Config:
        env_prefix = ""


@lru_cache()
def get_api_settings() -> APISettings:
    return APISettings()  # reads variables from environment

If you want something more fundamentally different as a function of the production vs. staging vs. testing environment (e.g., rather than setting each environment variable differently), you could just put some logic inside get_api_settings based on the environment variable value.

Accessing the config in your app is then as simple as, for example, debug = get_api_settings().debug.

dmontagu avatar Sep 17 '19 19:09 dmontagu

thanks for replying. im not sure how to use it. i read on other issues by @tiangolo that app.state should be used. So I'm not entirely sure what is the right way to configure and setup a global configuration object in fastapi.

On Wed, Sep 18, 2019 at 12:40 AM dmontagu [email protected] wrote:

@sandys https://github.com/sandys does pydantic BaseSettings not work for you? It allows you to pass values at instantiation time or via environment variable (and is type safe to boot!).

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/tiangolo/fastapi/issues/508?email_source=notifications&email_token=AAASYU3BXVI7PJLKLUUMOY3QKETRHA5CNFSM4IT7DHBKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD65SYBQ#issuecomment-532360198, or mute the thread https://github.com/notifications/unsubscribe-auth/AAASYU65KG3K4DPGXPRGVU3QKETRHANCNFSM4IT7DHBA .

sandys avatar Sep 17 '19 19:09 sandys

You should not use app.state yet -- I don't think it's even supported currently (@euri10 has a pull request to add support).

However, even if it were supported, I would advise against using app.state for configuration if possible -- it is intended for storing application state, which may change over time, and was created so that that state could be accessed and modified from requests. I am having a hard time imagining a scenario in which accessing/modifying the application configuration in that way is a good idea -- I think in most cases it would be an anti-pattern.

Also, it is not mypy / completion-friendly, which I think is especially useful for config settings.

dmontagu avatar Sep 17 '19 19:09 dmontagu

Thanks. That's super super helpful to know.

In that case, is there an example to show the right way to use pydantic in this way

On Wed, 18 Sep, 2019, 00:57 dmontagu, [email protected] wrote:

You should not use app.state yet -- I don't think it's even supported currently (@euri10 https://github.com/euri10 has a pull request to add support).

However, even if it were supported, I would advise against using app.state for configuration if possible -- it is intended for storing application state, which may change over time.

Also, it is not mypy / completion-friendly, which I think is especially useful for config settings.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/tiangolo/fastapi/issues/508?email_source=notifications&email_token=AAASYU5SKJAD3UNZMTPLURTQKEVR3A5CNFSM4IT7DHBKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOD65UHOQ#issuecomment-532366266, or mute the thread https://github.com/notifications/unsubscribe-auth/AAASYU4FTIM6CV5V7GGLYX3QKEVR3ANCNFSM4IT7DHBA .

sandys avatar Sep 17 '19 19:09 sandys

Is the example I posted above not clear enough?

Without going into all the nuances of everything my utility functions are doing, this is roughly what it looks like when I'm creating my server using configuration:

def get_app() -> FastAPI:
    app_settings = get_app_settings()
    api_settings = get_api_settings()  # see example above

    server = FastAPI(title=app_settings.project_name, openapi_url=api_settings.openapi_route, debug=api_settings.debug)
    server.include_router(get_api_router(), prefix=api_settings.api_v1_route)

    @server.get("/", include_in_schema=False)
    def redirect_to_docs() -> RedirectResponse:
        return RedirectResponse("/docs")

    @server.on_event("startup")
    async def connect_to_database() -> None:
        database = get_database()
        if not database.is_connected:
            await database.connect()

    @server.on_event("shutdown")
    async def shutdown() -> None:
        database = get_database()
        if database.is_connected:
            await database.disconnect()

    static_files_app = StaticFiles(directory=str(app_settings.static_dir))
    server.mount(path=app_settings.static_mount_path, app=static_files_app, name="static")

    setup_api(server, api_settings, use_session_middleware=app_settings.use_session_middleware)
    setup_openapi_schemas(server)
    add_timing_middleware(server, exclude="StaticFiles")
    return server

app = get_app()

(Placing the setup in a function like this makes it easy to modify the configuration and re-instantiate the app with the new configuration in tests.)

dmontagu avatar Sep 17 '19 19:09 dmontagu

Also, pydantic has docs about using BaseSettings that you might find useful.

dmontagu avatar Sep 17 '19 19:09 dmontagu

Classy and very elegant example of leveraging pydantic @dmontagu as always (I think the checks on whether the db is connected are unnecessary :wink:)! Another option is to use Starlette Config.

euri10 avatar Sep 17 '19 20:09 euri10

@dmontagu @euri10 which one would you both recommend ? Starlette Config or Pydantic ? Since fastapi is fundamentally based on Starlette, would Starlette Config be the more long-term safer way of doing this ?

sandys avatar Sep 20 '19 06:09 sandys

@dmontagu @euri10 which one would you both recommend ? Starlette Config or Pydantic ? Since fastapi is fundamentally based on Starlette, would Starlette Config be the more long-term safer way of doing this ?

I wouldn't recommend Config based only on the fact that FastAPI is based on Starlette since the BaseSettings class is from pydantic and FastAPI relies on it at least as much as it does on Starlette.

FastAPI is not opinionated, find what works best for you, if the real question about safety is : do you think one or the other has more or less chances to be maintained over a long period of time, then I think both have equal chances, if not more for pydantic BaseSettings, but that's pure guess.

euri10 avatar Sep 20 '19 07:09 euri10

@sandys I personally think pydantic's is more flexible, powerful, plays better with autocompletion/IDEs, and the list goes on. If you are already using fastapi, I'd definitely recommend it; might as well take advantage of the dependencies you are already including.

I now use pydantic in most of my projects (even if they aren't based on fastapi) because of how useful BaseModel (and BaseSettings) are.

The starlette config has no nice way of handling type-safety or autocompletion. It's not an unreasonable choice, and if you were only using pydantic for the settings I might drop it in favor of fewer dependencies (then again, I might not, but I'm biased :D). But I think pydantic has a lot to offer here.

Pydantic is very close to a 1.0 release right now (I think the target is some time in the next month); I think it will be safe to depend on pydantic in the long term.

dmontagu avatar Sep 20 '19 09:09 dmontagu

@tiangolo @euri10 Any chance to get app.state pull request https://github.com/tiangolo/fastapi/pull/502 fixed and merged? Thanks!

imsedim avatar Oct 02 '19 23:10 imsedim

I've got no merge powers, nor any powers at all, I could make use of this for sure too instead of having to install my fork, that said @tiangolo seems to be very busy at the moment and wishing him the best is all we can do !

On Thu, Oct 3, 2019 at 1:36 AM Dmitry [email protected] wrote:

@tiangolo https://github.com/tiangolo @euri10 https://github.com/euri10 Any chance to get app.state pull request #502 https://github.com/tiangolo/fastapi/pull/502 fixed and merged? Thanks!

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/tiangolo/fastapi/issues/508?email_source=notifications&email_token=AAINSPVCOPQFL5IHTOA5ARLQMUV75A5CNFSM4IT7DHBKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEAGQOHI#issuecomment-537724701, or mute the thread https://github.com/notifications/unsubscribe-auth/AAINSPVZP2P5VIS2EZDK3JDQMUV75ANCNFSM4IT7DHBA .

-- benoit barthelet http://pgp.mit.edu/pks/lookup?op=get&search=0xF150E01A72F6D2EE

euri10 avatar Oct 03 '19 07:10 euri10

For what it's worth, in the interim you can easily subclass FastAPI and add your own state class:

class State(object):
    """
    Straight out of Starlette
    """

    def __init__(self, state: typing.Dict = None):
        if state is None:
            state = {}
        super(State, self).__setattr__("_state", state)

    def __setattr__(self, key: typing.Any, value: typing.Any) -> None:
        self._state[key] = value

    def __getattr__(self, key: typing.Any) -> typing.Any:
        try:
            return self._state[key]
        except KeyError:
            message = "'{}' object has no attribute '{}'"
            raise AttributeError(message.format(self.__class__.__name__, key))

    def __delattr__(self, key: typing.Any) -> None:
        del self._state[key]

class MyFastAPI(FastAPI):
    if not typing.TYPE_CHECKING:  # ensures you still get init-signature type checking from mypy
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.state = State()

(I have done this myself.)

dmontagu avatar Oct 03 '19 08:10 dmontagu

@dmontagu Good idea! I guess I would subclass FastAPI and then just reuse starlette.datastructures.State directly.

UPD: starlette.requests.State for order version

imsedim avatar Oct 03 '19 09:10 imsedim

About config, you don't need to use app.state, you are not limited by that. You can use pure Python, and any package that you want. You can use it, it's available since some versions ago, but you don't have to use it.

You could use Starlette's config or Pydantic BaseSettings. Or even just os.getenv(). I would suggest Pydantic BaseSettings, we'll soon have docs with it.

I would also advise against using app.state for anything, the mentioned PR is already merged and you can use app.state if you want. But an APIRouter wouldn't have access to that state. And I don't really have a use case for anything in app.state yet that is not solvable in a simpler way.

Also, by not having to put anything through app.state makes your logic more independent of FastAPI. That way you could be able to use the same logic and configs in other environments. For example, in a task queue, that doesn't need to have FastAPI installed, but could still read settings from a Pydantic BaseSettings object to connect to a DB, etc.

tiangolo avatar Feb 10 '20 17:02 tiangolo

Thanks for your reply! This is very helpful.

Just one request - could you make this using Starlette instead of Pydantic ? It is more useful for us being in the base framework of Starlette itself and maintaining compatibility with how Starlette will do it in the long term

On Mon, 10 Feb, 2020, 23:16 Sebastián Ramírez, [email protected] wrote:

About config, you don't need to use app.state, you are not limited by that. You can use pure Python, and any package that you want. You can use it, it's available since some versions ago, but you don't have to use it.

You could use Starlette's config or Pydantic BaseSettings. Or even just os.getenv(). I would suggest Pydantic BaseSettings, we'll soon have docs with it.

I would also advise against using app.state for anything, the mentioned PR is already merged and you can use app.state if you want. But an APIRouter wouldn't have access to that state. And I don't really have a use case for anything in app.state yet that is not solvable in a simpler way.

Also, by not having to put anything through app.state makes your logic more independent of FastAPI. That way you could be able to use the same logic and configs in other environments. For example, in a task queue, that doesn't need to have FastAPI installed, but could still read settings from a Pydantic BaseSettings object to connect to a DB, etc.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/tiangolo/fastapi/issues/508?email_source=notifications&email_token=AAASYU6SCKVSBZVSOAA3J3TRCGHGPA5CNFSM4IT7DHBKYY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOELJOEXA#issuecomment-584245852, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAASYU6XPQYDR7R26X22RQDRCGHGPANCNFSM4IT7DHBA .

sandys avatar Feb 10 '20 17:02 sandys