EsmeraldAPISettings
class¶
Warning
The current page still doesn't have a translation for this language.
But you can help translating it: Contributing.
Reference for the EsmeraldAPISettings
class object and how to use it.
Read more about how to use the settings in your application and leverage the system.
The settings are used by any Esmerald application and used as the defaults for the Esmerald class instance if nothing is provided.
How to import¶
from esmerald import settings
Via conf
from esmerald.conf import settings
Via application instance
from esmerald import Esmerald
app = Esmerald()
app.settings
esmerald.EsmeraldAPISettings
¶
Bases: BaseSettings
EsmeraldAPISettings
settings object. The main entry-point for any settings
used by any Esmerald application.
Usually, when creating an application you will need some sort of organisation and some sort of settings. Esmerald comes with a native settings system where you will only need to inherit, override and add your own extra settings and use them anywhere.
When no values are provided upon an instantiation of an Esmerald
object, these
settings are used as the defaults.
The settings can be done via ESMERALD_SETTINGS_MODULE
or settings_module
parameter
in the Esmerald instantiation.
Learn more about settings.
Tip
The settings system is extremely powerful and must be leveraged accordingly. Read more about how to use the settings and how you can take advantage of the system.
Example
from esmerald import EsmeraldAPISettings
from esmerald.conf.enums import EnvironmentType
class AppSettings(EsmeraldAPISettings):
'''
Create your own custom settings.
'''
debug: bool = False
environment: Optional[str] = EnvironmentType.TESTING
debug
class-attribute
instance-attribute
¶
debug = False
Boolean indicating if the application should return the debug tracebacks on server errors, in other words, if you want to have debug errors being displayed.
Read more about this in the official Lilya documentation.
Tip
Do not use this in production as True
.
environment
class-attribute
instance-attribute
¶
environment = PRODUCTION
Optional string indicating the environment where the settings are running. You won't probably need this but it is here in case you might want to use.
app_name
class-attribute
instance-attribute
¶
app_name = 'Esmerald'
The name of the Esmerald application/API. This name is displayed when the OpenAPI documentation is used.
title
class-attribute
instance-attribute
¶
title = 'Esmerald'
The title of the Esmerald application/API. This title is displayed when the OpenAPI documentation is used.
version
class-attribute
instance-attribute
¶
version = __version__
The version of the Esmerald application/API. This version is displayed when the OpenAPI documentation is used.
Note: This is the version of your application/API and not th version of the OpenAPI specification being used by Esmerald.
summary
class-attribute
instance-attribute
¶
summary = 'Esmerald application'
The summary of the Esmerald application/API. This short summary is displayed when the OpenAPI documentation is used.
description
class-attribute
instance-attribute
¶
description = 'Highly scalable, performant, easy to learn and for every application.'
The description of the Esmerald application/API. This description is displayed when the OpenAPI documentation is used.
contact
class-attribute
instance-attribute
¶
contact = Contact(name='admin', email='admin@myapp.com')
A dictionary or an object of type esmerald.openapi.schemas.v3_1_0.Contact
containing the contact information of the application/API.
Both dictionary and object contain several fields.
- name - String name of the contact.
- url - String URL of the contact. It must be in the format of a URL.
- email - String email address of the contact. It must be in the format of an email address.
terms_of_service
class-attribute
instance-attribute
¶
terms_of_service = None
A URL pointing to the Terms of Service of the application. This description is displayed when the OpenAPI documentation is used.
license
class-attribute
instance-attribute
¶
license = None
A dictionary or an object of type esmerald.openapi.schemas.v3_1_0.License
containing the license information of the application/API.
Both dictionary and object contain several fields.
- name - String name of the license.
- identifier - An SPDX license expression.
- url - String URL of the contact. It must be in the format of a URL.
security
class-attribute
instance-attribute
¶
security = None
Used by OpenAPI definition, the security must be compliant with the norms. Esmerald offers some out of the box solutions where this is implemented.
The Esmerald security is available to automatically used.
The security can be applied also on a level basis.
For custom security objects, you must subclass
esmerald.openapi.security.base.HTTPBase
object.
servers
class-attribute
instance-attribute
¶
servers = [{'url': '/'}]
A list
of python dictionaries with the information regarding the connectivity
to the target.
This can be useful, for example, if your application is served from different domains and you want a shared OpenAPI documentation to test it all.
Esmerald automatically handles the OpenAPI documentation generation for you but sometimes you might want to add an extra custom domain to it.
For example, when using ChildEsmerald
modules, since the object itself subclasses
Esmerald, that also means you can have independent documentation directly in the
ChildEsmerald or access the top level
documentation (the application itself) where you can select the server to test it.
If the servers list
is not provided or an is an empty list
, the default value
will be a dict
with the url
pointing to /
.
Each dict
of the list
follows the following format for the parameters:
- url - A URL string to the target host/domain. The URL may support server
variables and it may be also a relative server (for example, the domain/path of a
ChildEsmerald
). - description - An optional string description of the host/domain.
- variables - A dictionary between the variable and its value. The value
is used for substitution in the servers URL template. E.g.:
/my-domain/{age: int}
.
You can read more about how the OpenAPI documentation is used.
secret_key
class-attribute
instance-attribute
¶
secret_key = 'my secret'
A unique string value used for the cryptography. This value is also used internally by Esmerald with the JWT as well the CSRFConfig.
Tip
Make sure you do not reuse the same secret key across environments as this can lead to security issues that you can easily avoid.
openapi_version
class-attribute
instance-attribute
¶
openapi_version = '3.1.0'
The string version of the OpenAPI.
Esmerald will generate the OpenAPI 3.1.0 by default and will output that as the OpenAPI version.
If you need to somehow trick some of the tools you are using by setting a different version of the OpenAPI, this is the field you can use to do it so.
allowed_hosts
class-attribute
instance-attribute
¶
allowed_hosts = ['*']
A list
of allowed hosts for the application. The allowed hosts when not specified
defaults to ["*"]
but when specified.
The allowed hosts are also what controls the TrustedHostMiddleware and you can read more about how to use it.
allow_origins
class-attribute
instance-attribute
¶
allow_origins = None
A list
of allowed origins hosts for the application.
The allowed origins is used by the CORSConfig and controls the CORSMiddleware.
Tip
If you create your own CORSConfig, this setting is ignored and your custom config takes priority.
response_class
class-attribute
instance-attribute
¶
response_class = None
Global default response class to be used within the Esmerald application.
Read more about the Responses and how to use them.
response_cookies
class-attribute
instance-attribute
¶
response_cookies = None
A global sequence of esmerald.datastructures.Cookie
objects.
Read more about the Cookies.
response_headers
class-attribute
instance-attribute
¶
response_headers = None
A global mapping of esmerald.datastructures.ResponseHeader
objects.
Read more about the ResponseHeader.
include_in_schema
class-attribute
instance-attribute
¶
include_in_schema = True
Boolean flag indicating if all the routes of the application should be included in the OpenAPI documentation.
Note almost everything in Esmerald can be done in levels, which means when the application
level is set to include_in_schema=False
, no schemas will be
displayed in the OpenAPI documentation.
Tip
This can be particularly useful if you have, for example, a ChildEsmerald
and
you don't want to include in the schema the routes of the said ChildEsmerald
.
This way there is no reason to do it route by route and instead you can
simply do it directly in the application level.
tags
class-attribute
instance-attribute
¶
tags = None
A list of strings tags to be applied to the path operation.
It will be added to the generated OpenAPI documentation.
Note almost everything in Esmerald can be done in levels, which means these tags on a Esmerald instance, means it will be added to every route even if those routes also contain tags.
timezone
class-attribute
instance-attribute
¶
timezone = 'UTC'
Object of time datetime.timezone
or string indicating the
timezone for the application.
Note - The timezone is internally used for the supported scheduler.
root_path
class-attribute
instance-attribute
¶
root_path = ''
A path prefix that is handled by a proxy not seen in the application but seen by external libraries.
This affects the tools like the OpenAPI documentation.
enable_sync_handlers
class-attribute
instance-attribute
¶
enable_sync_handlers = True
Boolean flag indicating the the sync handlers should be allowed in the application or not.
When the enable_sync_handlers
is set to False
then only
async
handlers are allowed in the application.
Warning
Be careful when disabling the enable_sync_handlers
. When this happens,
only async
is allowed in the handlers.
enable_scheduler
class-attribute
instance-attribute
¶
enable_scheduler = False
Boolean flag indicating if the internal scheduler should be enabled or not.
enable_openapi
class-attribute
instance-attribute
¶
enable_openapi = True
Boolean flag indicating if the OpenAPI documentation should be generated or not.
When False
, no OpenAPI documentation is accessible.
Tip
Disable this option if you run in production and no one should access the documentation unless behind an authentication.
redirect_slashes
class-attribute
instance-attribute
¶
redirect_slashes = True
Boolean flag indicating if the redirect slashes are enabled for the routes or not. ```
x_frame_options
class-attribute
instance-attribute
¶
x_frame_options = None
Set the X-Frame-Options HTTP header in HTTP responses.
To enable the response to be loaded on a frame within the same site, set x_frame_options to 'SAMEORIGIN'.
This flag is to be used when XFrameOptionsMiddleware
is added to the
application.
root_path_in_servers
class-attribute
instance-attribute
¶
root_path_in_servers = True
Boolean flag use to disable the automatic URL generation in the servers
field
in the OpenAPI documentation.
webhooks
class-attribute
instance-attribute
¶
webhooks = None
This is the same principle of the routes
but for OpenAPI webhooks.
Read more about webhooks.
When a webhook is added, it will automatically add them into the OpenAPI documentation.
openapi_url
class-attribute
instance-attribute
¶
openapi_url = '/openapi.json'
The URL where the OpenAPI schema will be served from.
The default is /openapi.json
.
Example
from esmerald import Esmerald
app = Esmerald(openapi_url="/api/v1/openapi.json")
docs_url
class-attribute
instance-attribute
¶
docs_url = '/docs/swagger'
String default relative URL where the Swagger documentation shall be accessed in the application.
This is used as the default if no OpenAPIConfig is provided.
redoc_url
class-attribute
instance-attribute
¶
redoc_url = '/docs/redoc'
String default relative URL where the ReDoc documentation shall be accessed in the application.
This is used as the default if no OpenAPIConfig is provided.
swagger_ui_oauth2_redirect_url
class-attribute
instance-attribute
¶
swagger_ui_oauth2_redirect_url = '/docs/oauth2-redirect'
String default relative URL where the Swagger UI OAuth Redirect URL shall be accessed in the application.
This is used as the default if no OpenAPIConfig is provided.
redoc_js_url
class-attribute
instance-attribute
¶
redoc_js_url = 'https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js'
String default URL where the ReDoc Javascript is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
redoc_favicon_url
class-attribute
instance-attribute
¶
redoc_favicon_url = 'https://esmerald.dev/statics/images/favicon.ico'
String default URL where the ReDoc favicon is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
swagger_ui_init_oauth
class-attribute
instance-attribute
¶
swagger_ui_init_oauth = None
String default relative URL where the Swagger Init Auth documentation shall be accessed in the application.
This is used as the default if no OpenAPIConfig is provided.
swagger_ui_parameters
class-attribute
instance-attribute
¶
swagger_ui_parameters = None
A mapping with parameters to be passed onto Swagger.
This is used as the default if no OpenAPIConfig is provided.
swagger_js_url
class-attribute
instance-attribute
¶
swagger_js_url = 'https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.4/swagger-ui-bundle.min.js'
String default URL where the Swagger Javascript is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
swagger_css_url
class-attribute
instance-attribute
¶
swagger_css_url = 'https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.4/swagger-ui.min.css'
String default URL where the Swagger CSS is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
swagger_favicon_url
class-attribute
instance-attribute
¶
swagger_favicon_url = 'https://esmerald.dev/statics/images/favicon.ico'
String default URL where the Swagger favicon is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
with_google_fonts
class-attribute
instance-attribute
¶
with_google_fonts = True
Boolean flag indicating if the google fonts shall be used in the ReDoc OpenAPI Documentation.
This is used as the default if no OpenAPIConfig is provided.
stoplight_js_url
class-attribute
instance-attribute
¶
stoplight_js_url = 'https://unpkg.com/@stoplight/elements/web-components.min.js'
String default URL where the Stoplight Javascript is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
stoplight_css_url
class-attribute
instance-attribute
¶
stoplight_css_url = 'https://unpkg.com/@stoplight/elements/styles.min.css'
String default URL where the Stoplight CSS is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
stoplight_url
class-attribute
instance-attribute
¶
stoplight_url = '/docs/elements'
String default relative URL where the Stoplight documentation shall be accessed in the application.
This is used as the default if no OpenAPIConfig is provided.
stoplight_favicon_url
class-attribute
instance-attribute
¶
stoplight_favicon_url = 'https://esmerald.dev/statics/images/favicon.ico'
String default URL where the Stoplight favicon is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
rapidoc_url
class-attribute
instance-attribute
¶
rapidoc_url = '/docs/rapidoc'
String default relative URL where the Rapidoc documentation shall be accessed in the application.
Example: /docs/rapidoc
.
rapidoc_js_url
class-attribute
instance-attribute
¶
rapidoc_js_url = 'https://unpkg.com/rapidoc@9.3.4/dist/rapidoc-min.js'
String default URL where the RapiDoc Javascript is located and used within OpenAPI documentation,
This is used as the default if no OpenAPIConfig is provided.
rapidoc_favicon_url
class-attribute
instance-attribute
¶
rapidoc_favicon_url = 'https://esmerald.dev/statics/images/favicon.ico'
String default URL where the RapiDoc favicon is located and used within OpenAPI documentation,
Example: https://esmerald.dev/statics/images/favicon.ico
.
password_hashers
property
¶
password_hashers
List of available password hashers of Esmerald.
These password hashers are used withing the esmerald.contrib.*
and aims
to simplify the process of creating and validating password.
Read more about the password hashers.
Return
List of strings with the module and object location of the password hashers.
Default
[
"esmerald.contrib.auth.hashers.PBKDF2PasswordHasher",
"esmerald.contrib.auth.hashers.PBKDF2SHA1PasswordHasher",
]
Example
from esmerald import EsmeraldAPISettings
from esmerald.contrib.auth.hashers import PBKDF2PasswordHasher
# myapp.hashers.py
class CustomHasher(PBKDF2PasswordHasher):
'''
All the hashers inherit from BasePasswordHasher
'''
salt_entropy = 3000
# settings.py
class AppSettings(EsmeraldAPISettings):
@property
def password_hashers(self) -> List[str]:
return ["myapp.hashers.CustomHasher"]
```
routes
property
¶
routes
A global list
of esmerald routes. Those routes may vary and those can
be Gateway
, WebSocketGateWay
or even Include
.
This is also the entry-point for the routes of the application itself but it does not rely on only one level.
Read more about how to use and leverage the Esmerald routing system.
RETURNS | DESCRIPTION |
---|---|
List[Union[APIGateHandler, Include]]
|
List of routes |
Default
[]
Example
from esmerald import Esmerald, Gateway, Request, get, Include, EsmeraldAPISettings
@get()
async def homepage(request: Request) -> str:
return "Hello, home!"
@get()
async def another(request: Request) -> str:
return "Hello, another!"
class APPSettings(EsmeraldAPISettings):
@property
def routes(self) -> List[Union[APIGateHandler, "Include"]]:
return [
Gateway(handler=homepage)
Include("/nested",
routes=[
Gateway(handler=another)
]
)
]
csrf_config
property
¶
csrf_config
An instance of CRSFConfig.
This configuration is passed to the CSRFMiddleware and enables the middleware.
Tip
You can creatye your own CRSFMiddleware
version and pass your own
configurations. You don't need to use the built-in version although it
is recommended to do it so.
Example
Default
None
Example
from esmerald import EsmeraldAPISettings
class AppSettings(EsmeraldAPISettings):
secret: str = "n(0t=%_amauq1m&6sde4z#3mkdmfcad1942ny&#sjp1oygk-5_"
@property
def csrf_config(self) -> CSRFConfig:
if not self.secret_key:
raise ImproperlyConfigured("`secret` setting not configured.")
return CSRFConfig(secret=self.secret_key)
template_config
property
¶
template_config
An instance of TemplateConfig. This configuration is a simple set of configurations that when passed enables the template engine.
Note
You might need to install the template engine before
using this. You can always run
pip install esmerald[templates]
to help you out.
Default
JinjaTemplateEngine
Example
from esmerald import EsmeraldAPISettings
class AppSettings(EsmeraldAPISettings):
@property
def template_config(self) -> TemplateConfig:
TemplateConfig(directory='templates')
static_files_config
property
¶
static_files_config
An instance of StaticFilesConfig.
This configuration is used to enable and serve static files via Esmerald application.
Default
None
Example
from esmerald import EsmeraldAPISettings
class AppSettings(EsmeraldAPISettings):
@property
def static_files_config(self) -> StaticFilesConfig:
StaticFilesConfig(path='/', directories=...)
cors_config
property
¶
cors_config
An instance of CORSConfig.
This configuration is passed to the CORSMiddleware and enables the middleware.
Default
CORSConfig
Example
from esmerald import EsmeraldAPISettings
class AppSettings(EsmeraldAPISettings):
allow_origins: List[str] = ['www.example.com', 'www.foobar.com']
@property
def cors_config(self) -> CORSConfig:
...
session_config
property
¶
session_config
An instance of SessionConfig.
This configuration is passed to the SessionMiddleware and enables the middleware.
Default
None
Example
from esmerald import EsmeraldAPISettings
class AppSettings(EsmeraldAPISettings):
@property
def session_config(self) -> SessionConfig:
SessionConfig(
secret_key=self..secret_key,
session_cookie="session"
)
openapi_config
property
¶
openapi_config
An instance of OpenAPIConfig.
This object is then used by Esmerald to create the OpenAPI documentation.
Note: Here is where the defaults for Esmerald OpenAPI are overriden and if this object is passed, then the previous defaults of the settings are ignored.
Tip
This is the way you could override the defaults all in one go instead of doing attribute by attribute.
Default
OpenAPIConfig
Example
from esmerald import EsmeraldAPISettings
class AppSettings(EsmeraldAPISettings):
@property
def openapi_config(self) -> OpenAPIConfig:
...
middleware
property
¶
middleware
A global sequence of Lilya middlewares or esmerald.middlewares
that are
used by the application.
Read more about the Middleware.
Defaults
[]
Example
from esmerald import EsmeraldAPISettings
from esmerald.middleware import HTTPSRedirectMiddleware, TrustedHostMiddleware
from lilya.middleware import Middleware as StarletteMiddleware
class AppSettings(EsmeraldAPISettings):
@property
def middleware(self) -> List[Middleware]:
return [
StarletteMiddleware(
TrustedHostMiddleware, allowed_hosts=["example.com", "*.example.com"]
)
]
scheduler_config
property
¶
scheduler_config
Esmerald comes with an internal scheduler connfiguration that can be used to schedule tasks with any scheduler at your choice.
Esmerald also integrates out of the box with Asyncz
and the scheduler class is nothing more than the AsyncIOScheduler
provided
by the library.
Tip
You can create your own scheduler class and use it with Esmerald. For that you must read the Asyncz documentation and how to make it happen.
Note - To enable the scheduler, you must set the enable_scheduler=True
.
interceptors
property
¶
interceptors
A list
of global interceptors from objects inheriting from
esmerald.interceptors.interceptor.EsmeraldInterceptor
.
Read more about how to implement the Interceptors in Esmerald and to leverage them.
Note almost everything in Esmerald can be done in levels, which means these interceptors on a Esmerald instance, means the whole application.
RETURNS | DESCRIPTION |
---|---|
List[Interceptor]
|
List of interceptors |
Default
[]
Example
from loguru import logger
from lilya.types import Receive, Scope, Send
from esmerald import Esmerald, EsmeraldInterceptor, EsmeraldAPISettings
class LoggingInterceptor(EsmeraldInterceptor):
async def intercept(self, scope: "Scope", receive: "Receive", send: "Send") -> None:
# Log a message here
logger.info("This is my interceptor being called before reaching the handler.")
class AppSettings(EsmeraldAPISettings):
def interceptors(self) -> List[Interceptor]:
return [LoggingInterceptor]
permissions
property
¶
permissions
A list
of global permissions from objects inheriting from
esmerald.permissions.BasePermission
.
Read more about how to implement the Permissions in Esmerald and to leverage them.
Note almost everything in Esmerald can be done in levels, which means these permissions on a Esmerald instance, means the whole application.
Default
[]
RETURNS | DESCRIPTION |
---|---|
List[Permission]
|
List of global permissions (not permissions on levels). |
Example
from esmerald import Esmerald, EsmeraldAPISettings, BasePermission, Request
from esmerald.types import APIGateHandler
class IsAdmin(BasePermission):
'''
Permissions for admin
'''
async def has_permission(self, request: "Request", apiview: "APIGateHandler"):
is_admin = request.headers.get("admin", False)
return bool(is_admin)
class AppSettings(EsmeraldAPISettings):
def permissions(self) -> List[Permission]:
return [IsAdmin]
dependencies
property
¶
dependencies
A dictionary of global dependencies. These dependencies will be applied to each path of the application.
Read more about Dependencies.
RETURNS | DESCRIPTION |
---|---|
Dependencies
|
A dictionary of global dependencies. |
Default
{}
Example
from esmerald import Esmerald, EsmeraldAPISettings, Inject
def is_valid(number: int) -> bool:
return number >= 5
class AppSettings(EsmeraldAPISettings):
def dependencies(self) -> Dependencies:
return {
"is_valid": Inject(is_valid)
}
exception_handlers
property
¶
exception_handlers
A global dictionary with handlers for exceptions.
Note almost everything in Esmerald can be done in levels, which means these exception handlers on a Esmerald instance, means the whole application.
Read more about the Exception handlers.
RETURNS | DESCRIPTION |
---|---|
ExceptionHandlerMap
|
Mapping of exception handlers where the key is the exception object and the value |
ExceptionHandlerMap
|
is the callable. |
Example
from pydantic.error_wrappers import ValidationError
from esmerald import (
Esmerald,
EsmeraldAPISettings,
JSONResponse,
Request,
ValidationErrorException,
)
async def validation_error_exception_handler(
request: Request, exc: ValidationError
) -> JSONResponse:
extra = getattr(exc, "extra", None)
if extra:
return JSONResponse(
{"detail": exc.detail, "errors": exc.extra.get("extra", {})},
status_code=status.HTTP_400_BAD_REQUEST,
)
else:
return JSONResponse(
{"detail": exc.detail},
status_code=status.HTTP_400_BAD_REQUEST,
)
class AppSettings(EsmeraldAPISettings):
@property
def exception_handlers(self) -> ExceptionHandlerMap:
return {
ValidationErrorException: validation_error_exception_handler,
}
on_startup
property
¶
on_startup
A list
of events that are trigger upon the application
starts.
Read more about the events.
RETURNS | DESCRIPTION |
---|---|
Union[List[LifeSpanHandler], None]
|
List of events |
Default
None
Example
from pydantic import BaseModel
from saffier import Database, Registry
from esmerald import Esmerald, EsmeraldAPISettings, Gateway, post
database = Database("postgresql+asyncpg://user:password@host:port/database")
registry = Registry(database=database)
class AppSettings(EsmeraldAPISettings):
@property
def on_startup(self) -> Union[List[LifeSpanHandler], None]:
return [
database.connect
]
on_shutdown
property
¶
on_shutdown
A list
of events that are trigger upon the application
shuts down.
Read more about the events.
RETURNS | DESCRIPTION |
---|---|
Union[List[LifeSpanHandler], None]
|
List of events |
Default
None
Example
from pydantic import BaseModel
from saffier import Database, Registry
from esmerald import Esmerald, EsmeraldAPISettings, Gateway, post
database = Database("postgresql+asyncpg://user:password@host:port/database")
registry = Registry(database=database)
class AppSettings(EsmeraldAPISettings):
@property
def on_shutdown(self) -> Union[List[LifeSpanHandler], None]:
return [
database.connect
]
lifespan
property
¶
lifespan
A lifespan
context manager handler. This is an alternative
to on_startup
and on_shutdown
and you cannot used all combined.
Read more about the lifespan.
extensions
property
¶
extensions
A list
of global extensions from objects inheriting from
esmerald.interceptors.interceptor.EsmeraldInterceptor
.
Read more about how to implement the Plugables in Esmerald and to leverage them.
RETURNS | DESCRIPTION |
---|---|
dict[str, Union[Extension, Pluggable, type[Extension]]]
|
Mapping of extensions |
Defaults
{}
Example
from typing import Optional
from loguru import logger
from pydantic import BaseModel
from esmerald import Esmerald, EsmeraldAPISettings, Extension, Pluggable
from esmerald.types import DictAny
class PluggableConfig(BaseModel):
name: str
class MyExtension(Extension):
def extend(self, config: PluggableConfig = None) -> None:
logger.success(f"Successfully passed a config {config.name}")
class AppSettings(EsmeraldAPISettings):
@property
def extensions(self) -> dict[str, Union["Extension", "Pluggable", type["Extension"]]]:
my_config = PluggableConfig(name="my extension")
return {
"my-extension": Pluggable(MyExtension, config=my_config),
"my-extension": MyExtension,
}
encoders
property
¶
encoders
A list
of encoders to be used by the application once it
starts.
RETURNS | DESCRIPTION |
---|---|
Union[List[Encoder], None]
|
List of encoders |
Example
from typing import Any
from attrs import asdict, define, field, has
from esmerald.encoders import Encoder
class AttrsEncoder(Encoder):
def is_type(self, value: Any) -> bool:
return has(value)
def serialize(self, obj: Any) -> Any:
return asdict(obj)
def encode(self, annotation: Any, value: Any) -> Any:
return annotation(**value)
class AppSettings(EsmeraldAPISettings):
@property
def encoders(self) -> Union[List[Encoder], None]:
return [AttrsEncoder]
__hash__
¶
__hash__()
Source code in esmerald/conf/global_settings.py
1418 1419 1420 1421 1422 1423 1424 1425 1426 |
|