本文整理汇总了Python中starlette.middleware.cors.CORSMiddleware方法的典型用法代码示例。如果您正苦于以下问题:Python cors.CORSMiddleware方法的具体用法?Python cors.CORSMiddleware怎么用?Python cors.CORSMiddleware使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类starlette.middleware.cors
的用法示例。
在下文中一共展示了cors.CORSMiddleware方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: use_cors
# 需要导入模块: from starlette.middleware import cors [as 别名]
# 或者: from starlette.middleware.cors import CORSMiddleware [as 别名]
def use_cors(app: "App"):
"""Enable CORS (Cross-Origin Resource Sharing) headers.
[constants.py]: /api/constants.md
[CORSMiddleware]: https://www.starlette.io/middleware/#corsmiddleware
Settings:
- `CORS` (bool or dict):
if `True`, the default configuration defined in [constants.py] is used.
Otherwise, the dictionary is passed to Starlette's [CORSMiddleware].
"""
cors: typing.Optional[typing.Union[bool, dict]] = settings.get("CORS")
if cors is None:
return
if cors is True:
cors = dict(DEFAULT_CORS_CONFIG)
app.add_middleware(CORSMiddleware, **cors)
示例2: __init__
# 需要导入模块: from starlette.middleware import cors [as 别名]
# 或者: from starlette.middleware.cors import CORSMiddleware [as 别名]
def __init__(self, units, **kwargs):
if not isinstance(units, list):
raise BootstrapError(
f"aioli.Application expects an iterable of Units, got: {type(units)}"
)
config = kwargs.pop("config", {})
self.__units = units
try:
self.config = ApplicationConfigSchema().load(config.get("aioli-core", {}))
except ValueError:
raise BootstrapError("Application `config` must be a collection")
except ValidationError as e:
raise BootstrapError(f"Configuration validation error: {e.messages}")
self.registry = ImportRegistry(self, config)
# Apply known settings from environment or provided `config`
super(Application, self).__init__(debug=self.config["debug"], **kwargs)
# Error handlers
self.add_exception_handler(AioliException, http_error)
self.add_exception_handler(HTTPException, http_error)
self.add_exception_handler(ValidationError, validation_error)
self.add_exception_handler(JSONDecodeError, decode_error)
# Middleware
self.add_middleware(CORSMiddleware, allow_origins=self.config["allow_origins"])
# Lifespan handlers
self.router.lifespan.add_event_handler("startup", self._startup)
self.router.lifespan.add_event_handler("shutdown", self._shutdown)