index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
10,353
tracking_numbers.definition
__repr__
null
def __repr__(self): return repr_with_args( self, courier=self.courier, product=self.product, number_regex=self.number_regex, tracking_url_template=self.tracking_url_template, serial_number_parser=self.serial_number_parser, checksum_validator=self.checksum_validator, additional_validations=self.additional_validations, )
(self)
10,354
tracking_numbers.definition
_get_additional_error
null
@staticmethod def _get_additional_error( validation: AdditionalValidation, match_data: MatchData, ) -> Optional[ValidationError]: group_key = validation.regex_group_name raw_value = match_data.get(group_key) if not raw_value: return validation.name, f"{group_key} not found" value = _remove_whitespace(raw_value) matches_any_value = any( value_matcher.matches(value) for value_matcher in validation.value_matchers ) if not matches_any_value: return validation.name, f"Match not found for {group_key}: {value}" return None
(validation: tracking_numbers.definition.AdditionalValidation, match_data: Dict[str, str]) -> Optional[Tuple[str, str]]
10,355
tracking_numbers.definition
_get_checksum_errors
null
def _get_checksum_errors( self, serial_number: Optional[SerialNumber], match_data: MatchData, ) -> Optional[ValidationError]: if not self.checksum_validator: return None if not serial_number: return "checksum", "SerialNumber not found" check_digit = match_data.get("CheckDigit") if not check_digit: return "checksum", "CheckDigit not found" passes_checksum = self.checksum_validator.passes( serial_number=serial_number, check_digit=int(check_digit), ) if not passes_checksum: return "checksum", "Checksum validation failed" return None
(self, serial_number: Optional[List[int]], match_data: Dict[str, str]) -> Optional[Tuple[str, str]]
10,356
tracking_numbers.definition
_get_serial_number
null
def _get_serial_number(self, match_data: MatchData) -> Optional[SerialNumber]: raw_serial_number = match_data.get("SerialNumber") if raw_serial_number: return self.serial_number_parser.parse( _remove_whitespace(raw_serial_number), ) return None
(self, match_data: Dict[str, str]) -> Optional[List[int]]
10,357
tracking_numbers.definition
_get_validation_errors
null
def _get_validation_errors( self, serial_number: Optional[SerialNumber], match_data: MatchData, ) -> List[ValidationError]: errors: List[ValidationError] = [] checksum_error = self._get_checksum_errors(serial_number, match_data) if checksum_error: errors.append(checksum_error) for validation in self.additional_validations: additional_error = self._get_additional_error(validation, match_data) if additional_error: errors.append(additional_error) return errors
(self, serial_number: Optional[List[int]], match_data: Dict[str, str]) -> List[Tuple[str, str]]
10,358
tracking_numbers.definition
test
null
def test(self, tracking_number: str) -> Optional[TrackingNumber]: match = self.number_regex.fullmatch(tracking_number) if not match: return None match_data = match.groupdict() if match else {} serial_number = self._get_serial_number(match_data) validation_errors = self._get_validation_errors(serial_number, match_data) return TrackingNumber( number=tracking_number, courier=self.courier, product=self.product, serial_number=serial_number, tracking_url=self.tracking_url(tracking_number), validation_errors=validation_errors, )
(self, tracking_number: str) -> Optional[tracking_numbers.types.TrackingNumber]
10,359
tracking_numbers.definition
tracking_url
null
def tracking_url(self, tracking_number: str) -> Optional[str]: if not self.tracking_url_template: return None return self.tracking_url_template % tracking_number
(self, tracking_number: str) -> Optional[str]
10,364
tracking_numbers
get_definition
null
def get_definition(product_name: str) -> Optional[TrackingNumberDefinition]: for tn_definition in DEFINITIONS: if tn_definition.product.name.lower() == product_name.lower(): return tn_definition return None
(product_name: str) -> Optional[tracking_numbers.definition.TrackingNumberDefinition]
10,365
tracking_numbers
get_tracking_number
null
def get_tracking_number(number: str) -> Optional[TrackingNumber]: for tn_definition in DEFINITIONS: tracking_number = tn_definition.test(number) if tracking_number and tracking_number.valid: return tracking_number return None
(number: str) -> Optional[tracking_numbers.types.TrackingNumber]
10,371
fastack.app
Fastack
null
class Fastack(FastAPI): cli = Typer() def set_settings(self, settings: ModuleType): self.state.settings = settings def get_setting(self, name: str, default: Any = None): assert self.state.settings is not None return getattr(self.state.settings, name, default) def load_plugins(self): for plugin in self.get_setting("PLUGINS", []): plugin += ".setup" plugin = import_attr(plugin) plugin(self) def load_commands(self): for command in self.get_setting("COMMANDS", []): command: Union[Callable, Typer] = import_attr(command) if isinstance(command, Typer): self.cli.add_typer(command) else: self.cli.command(command.__name__)(command) def include_controller( self, controller: Controller, *, prefix: str = "", tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, ): assert isinstance( controller, Controller ), f"Controller must be an instance of {controller!r}" router = controller.build( prefix=prefix, tags=tags, dependencies=dependencies, default_response_class=default_response_class, responses=responses, callbacks=callbacks, routes=routes, redirect_slashes=redirect_slashes, default=default, dependency_overrides_provider=dependency_overrides_provider, route_class=route_class, on_startup=on_startup, on_shutdown=on_shutdown, deprecated=deprecated, include_in_schema=include_in_schema, ) self.include_router(router) async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: try: _app_ctx_stack.push(self) scope_type = scope["type"] if scope_type == "http": request = Request(scope, receive, send) _request_ctx_stack.push(request) elif scope_type == "websocket": websocket = WebSocket(scope, receive, send) _websocket_ctx_stack.push(websocket) await super().__call__(scope, receive, send) finally: _websocket_ctx_stack.pop() _request_ctx_stack.pop() _app_ctx_stack.pop()
(*, debug: bool = False, routes: Optional[List[starlette.routing.BaseRoute]] = None, title: str = 'FastAPI', description: str = '', version: str = '0.1.0', openapi_url: Optional[str] = '/openapi.json', openapi_tags: Optional[List[Dict[str, Any]]] = None, servers: Optional[List[Dict[str, Union[Any, str]]]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, default_response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c41fb3a0>, docs_url: Optional[str] = '/docs', redoc_url: Optional[str] = '/redoc', swagger_ui_oauth2_redirect_url: Optional[str] = '/docs/oauth2-redirect', swagger_ui_init_oauth: Optional[Dict[str, Any]] = None, middleware: Optional[Sequence[starlette.middleware.Middleware]] = None, exception_handlers: Optional[Dict[Union[int, Type[Exception]], Callable[[starlette.requests.Request, Any], Coroutine[Any, Any, starlette.responses.Response]]]] = None, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, terms_of_service: Optional[str] = None, contact: Optional[Dict[str, Union[Any, str]]] = None, license_info: Optional[Dict[str, Union[Any, str]]] = None, openapi_prefix: str = '', root_path: str = '', root_path_in_servers: bool = True, responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, **extra: Any) -> None
10,372
fastack.app
__call__
null
def include_controller( self, controller: Controller, *, prefix: str = "", tags: Optional[List[str]] = None, dependencies: Optional[Sequence[params.Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, routes: Optional[List[routing.BaseRoute]] = None, redirect_slashes: bool = True, default: Optional[ASGIApp] = None, dependency_overrides_provider: Optional[Any] = None, route_class: Type[APIRoute] = APIRoute, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, ): assert isinstance( controller, Controller ), f"Controller must be an instance of {controller!r}" router = controller.build( prefix=prefix, tags=tags, dependencies=dependencies, default_response_class=default_response_class, responses=responses, callbacks=callbacks, routes=routes, redirect_slashes=redirect_slashes, default=default, dependency_overrides_provider=dependency_overrides_provider, route_class=route_class, on_startup=on_startup, on_shutdown=on_shutdown, deprecated=deprecated, include_in_schema=include_in_schema, ) self.include_router(router)
(self, scope: MutableMapping[str, Any], receive: Callable[[], Awaitable[MutableMapping[str, Any]]], send: Callable[[MutableMapping[str, Any]], Awaitable[NoneType]]) -> NoneType
10,373
fastapi.applications
__init__
null
def __init__( self, *, debug: bool = False, routes: Optional[List[BaseRoute]] = None, title: str = "FastAPI", description: str = "", version: str = "0.1.0", openapi_url: Optional[str] = "/openapi.json", openapi_tags: Optional[List[Dict[str, Any]]] = None, servers: Optional[List[Dict[str, Union[str, Any]]]] = None, dependencies: Optional[Sequence[Depends]] = None, default_response_class: Type[Response] = Default(JSONResponse), docs_url: Optional[str] = "/docs", redoc_url: Optional[str] = "/redoc", swagger_ui_oauth2_redirect_url: Optional[str] = "/docs/oauth2-redirect", swagger_ui_init_oauth: Optional[Dict[str, Any]] = None, middleware: Optional[Sequence[Middleware]] = None, exception_handlers: Optional[ Dict[ Union[int, Type[Exception]], Callable[[Request, Any], Coroutine[Any, Any, Response]], ] ] = None, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, terms_of_service: Optional[str] = None, contact: Optional[Dict[str, Union[str, Any]]] = None, license_info: Optional[Dict[str, Union[str, Any]]] = None, openapi_prefix: str = "", root_path: str = "", root_path_in_servers: bool = True, responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, **extra: Any, ) -> None: self._debug: bool = debug self.state: State = State() self.router: routing.APIRouter = routing.APIRouter( routes=routes, dependency_overrides_provider=self, on_startup=on_startup, on_shutdown=on_shutdown, default_response_class=default_response_class, dependencies=dependencies, callbacks=callbacks, deprecated=deprecated, include_in_schema=include_in_schema, responses=responses, ) self.exception_handlers: Dict[ Union[int, Type[Exception]], Callable[[Request, Any], Coroutine[Any, Any, Response]], ] = ( {} if exception_handlers is None else dict(exception_handlers) ) self.exception_handlers.setdefault(HTTPException, http_exception_handler) self.exception_handlers.setdefault( RequestValidationError, request_validation_exception_handler ) self.user_middleware: List[Middleware] = ( [] if middleware is None else list(middleware) ) self.middleware_stack: ASGIApp = self.build_middleware_stack() self.title = title self.description = description self.version = version self.terms_of_service = terms_of_service self.contact = contact self.license_info = license_info self.servers = servers or [] self.openapi_url = openapi_url self.openapi_tags = openapi_tags # TODO: remove when discarding the openapi_prefix parameter if openapi_prefix: logger.warning( '"openapi_prefix" has been deprecated in favor of "root_path", which ' "follows more closely the ASGI standard, is simpler, and more " "automatic. Check the docs at " "https://fastapi.tiangolo.com/advanced/sub-applications/" ) self.root_path = root_path or openapi_prefix self.root_path_in_servers = root_path_in_servers self.docs_url = docs_url self.redoc_url = redoc_url self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url self.swagger_ui_init_oauth = swagger_ui_init_oauth self.extra = extra self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {} self.openapi_version = "3.0.2" if self.openapi_url: assert self.title, "A title must be provided for OpenAPI, e.g.: 'My API'" assert self.version, "A version must be provided for OpenAPI, e.g.: '2.1.0'" self.openapi_schema: Optional[Dict[str, Any]] = None self.setup()
(self, *, debug: bool = False, routes: Optional[List[starlette.routing.BaseRoute]] = None, title: str = 'FastAPI', description: str = '', version: str = '0.1.0', openapi_url: Optional[str] = '/openapi.json', openapi_tags: Optional[List[Dict[str, Any]]] = None, servers: Optional[List[Dict[str, Union[Any, str]]]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, default_response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c41fb3a0>, docs_url: Optional[str] = '/docs', redoc_url: Optional[str] = '/redoc', swagger_ui_oauth2_redirect_url: Optional[str] = '/docs/oauth2-redirect', swagger_ui_init_oauth: Optional[Dict[str, Any]] = None, middleware: Optional[Sequence[starlette.middleware.Middleware]] = None, exception_handlers: Optional[Dict[Union[int, Type[Exception]], Callable[[starlette.requests.Request, Any], Coroutine[Any, Any, starlette.responses.Response]]]] = None, on_startup: Optional[Sequence[Callable[[], Any]]] = None, on_shutdown: Optional[Sequence[Callable[[], Any]]] = None, terms_of_service: Optional[str] = None, contact: Optional[Dict[str, Union[Any, str]]] = None, license_info: Optional[Dict[str, Union[Any, str]]] = None, openapi_prefix: str = '', root_path: str = '', root_path_in_servers: bool = True, responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, **extra: Any) -> NoneType
10,374
fastapi.applications
add_api_route
null
def add_api_route( self, path: str, endpoint: Callable[..., Coroutine[Any, Any, Response]], *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[Response], DefaultPlaceholder] = Default( JSONResponse ), name: Optional[str] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> None: self.router.add_api_route( path, endpoint=endpoint, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, openapi_extra=openapi_extra, )
(self, path: str, endpoint: Callable[..., Coroutine[Any, Any, starlette.responses.Response]], *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Union[Type[starlette.responses.Response], fastapi.datastructures.DefaultPlaceholder] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37b9cc0>, name: Optional[str] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> NoneType
10,375
fastapi.applications
add_api_websocket_route
null
def add_api_websocket_route( self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None ) -> None: self.router.add_api_websocket_route(path, endpoint, name=name)
(self, path: str, endpoint: Callable[..., Any], name: Optional[str] = None) -> NoneType
10,376
starlette.applications
add_event_handler
null
def add_event_handler(self, event_type: str, func: typing.Callable) -> None: self.router.add_event_handler(event_type, func)
(self, event_type: str, func: Callable) -> NoneType
10,377
starlette.applications
add_exception_handler
null
def add_exception_handler( self, exc_class_or_status_code: typing.Union[int, typing.Type[Exception]], handler: typing.Callable, ) -> None: self.exception_handlers[exc_class_or_status_code] = handler self.middleware_stack = self.build_middleware_stack()
(self, exc_class_or_status_code: Union[int, Type[Exception]], handler: Callable) -> NoneType
10,378
starlette.applications
add_middleware
null
def add_middleware(self, middleware_class: type, **options: typing.Any) -> None: self.user_middleware.insert(0, Middleware(middleware_class, **options)) self.middleware_stack = self.build_middleware_stack()
(self, middleware_class: type, **options: Any) -> NoneType
10,379
starlette.applications
add_route
null
def add_route( self, path: str, route: typing.Callable, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, ) -> None: self.router.add_route( path, route, methods=methods, name=name, include_in_schema=include_in_schema )
(self, path: str, route: Callable, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True) -> NoneType
10,380
starlette.applications
add_websocket_route
null
def add_websocket_route( self, path: str, route: typing.Callable, name: str = None ) -> None: self.router.add_websocket_route(path, route, name=name)
(self, path: str, route: Callable, name: Optional[str] = None) -> NoneType
10,381
fastapi.applications
api_route
null
def api_route( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.router.add_api_route( path, func, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, methods=methods, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, openapi_extra=openapi_extra, ) return func return decorator
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, methods: Optional[List[str]] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37baf20>, name: Optional[str] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,382
starlette.applications
build_middleware_stack
null
def build_middleware_stack(self) -> ASGIApp: debug = self.debug error_handler = None exception_handlers = {} for key, value in self.exception_handlers.items(): if key in (500, Exception): error_handler = value else: exception_handlers[key] = value middleware = ( [Middleware(ServerErrorMiddleware, handler=error_handler, debug=debug)] + self.user_middleware + [ Middleware( ExceptionMiddleware, handlers=exception_handlers, debug=debug ) ] ) app = self.router for cls, options in reversed(middleware): app = cls(app=app, **options) return app
(self) -> Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[NoneType]]], Awaitable[NoneType]]
10,383
fastapi.applications
delete
null
def delete( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.delete( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, operation_id=operation_id, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, )
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37b9fc0>, name: Optional[str] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,384
starlette.applications
exception_handler
null
def exception_handler( self, exc_class_or_status_code: typing.Union[int, typing.Type[Exception]] ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.add_exception_handler(exc_class_or_status_code, func) return func return decorator
(self, exc_class_or_status_code: Union[int, Type[Exception]]) -> Callable
10,385
fastapi.applications
get
null
def get( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.get( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, )
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37b92d0>, name: Optional[str] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,386
fastack.app
get_setting
null
def get_setting(self, name: str, default: Any = None): assert self.state.settings is not None return getattr(self.state.settings, name, default)
(self, name: str, default: Optional[Any] = None)
10,387
fastapi.applications
head
null
def head( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.head( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, )
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37b9420>, name: Optional[str] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,388
starlette.applications
host
null
def host(self, host: str, app: ASGIApp, name: str = None) -> None: self.router.host(host, app=app, name=name)
(self, host: str, app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[NoneType]]], Awaitable[NoneType]], name: Optional[str] = None) -> NoneType
10,390
fastapi.applications
include_router
null
def include_router( self, router: routing.APIRouter, *, prefix: str = "", tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, default_response_class: Type[Response] = Default(JSONResponse), callbacks: Optional[List[BaseRoute]] = None, ) -> None: self.router.include_router( router, prefix=prefix, tags=tags, dependencies=dependencies, responses=responses, deprecated=deprecated, include_in_schema=include_in_schema, default_response_class=default_response_class, callbacks=callbacks, )
(self, router: fastapi.routing.APIRouter, *, prefix: str = '', tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, include_in_schema: bool = True, default_response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37baec0>, callbacks: Optional[List[starlette.routing.BaseRoute]] = None) -> NoneType
10,391
fastack.app
load_commands
null
def load_commands(self): for command in self.get_setting("COMMANDS", []): command: Union[Callable, Typer] = import_attr(command) if isinstance(command, Typer): self.cli.add_typer(command) else: self.cli.command(command.__name__)(command)
(self)
10,392
fastack.app
load_plugins
null
def load_plugins(self): for plugin in self.get_setting("PLUGINS", []): plugin += ".setup" plugin = import_attr(plugin) plugin(self)
(self)
10,393
starlette.applications
middleware
null
def middleware(self, middleware_type: str) -> typing.Callable: assert ( middleware_type == "http" ), 'Currently only middleware("http") is supported.' def decorator(func: typing.Callable) -> typing.Callable: self.add_middleware(BaseHTTPMiddleware, dispatch=func) return func return decorator
(self, middleware_type: str) -> Callable
10,394
starlette.applications
mount
null
def mount(self, path: str, app: ASGIApp, name: str = None) -> None: self.router.mount(path, app=app, name=name)
(self, path: str, app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[NoneType]]], Awaitable[NoneType]], name: Optional[str] = None) -> NoneType
10,395
starlette.applications
on_event
null
def on_event(self, event_type: str) -> typing.Callable: return self.router.on_event(event_type)
(self, event_type: str) -> Callable
10,396
fastapi.applications
openapi
null
def openapi(self) -> Dict[str, Any]: if not self.openapi_schema: self.openapi_schema = get_openapi( title=self.title, version=self.version, openapi_version=self.openapi_version, description=self.description, terms_of_service=self.terms_of_service, contact=self.contact, license_info=self.license_info, routes=self.routes, tags=self.openapi_tags, servers=self.servers, ) return self.openapi_schema
(self) -> Dict[str, Any]
10,397
fastapi.applications
options
null
def options( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.options( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, )
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37b9f60>, name: Optional[str] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,398
fastapi.applications
patch
null
def patch( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.patch( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, )
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37b95a0>, name: Optional[str] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,399
fastapi.applications
post
null
def post( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.post( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, )
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37ba020>, name: Optional[str] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,400
fastapi.applications
put
null
def put( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.put( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, )
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37ba080>, name: Optional[str] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,401
starlette.applications
route
null
def route( self, path: str, methods: typing.List[str] = None, name: str = None, include_in_schema: bool = True, ) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.router.add_route( path, func, methods=methods, name=name, include_in_schema=include_in_schema, ) return func return decorator
(self, path: str, methods: Optional[List[str]] = None, name: Optional[str] = None, include_in_schema: bool = True) -> Callable
10,402
fastack.app
set_settings
null
def set_settings(self, settings: ModuleType): self.state.settings = settings
(self, settings: module)
10,403
fastapi.applications
setup
null
def setup(self) -> None: if self.openapi_url: urls = (server_data.get("url") for server_data in self.servers) server_urls = {url for url in urls if url} async def openapi(req: Request) -> JSONResponse: root_path = req.scope.get("root_path", "").rstrip("/") if root_path not in server_urls: if root_path and self.root_path_in_servers: self.servers.insert(0, {"url": root_path}) server_urls.add(root_path) return JSONResponse(self.openapi()) self.add_route(self.openapi_url, openapi, include_in_schema=False) if self.openapi_url and self.docs_url: async def swagger_ui_html(req: Request) -> HTMLResponse: root_path = req.scope.get("root_path", "").rstrip("/") openapi_url = root_path + self.openapi_url oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url if oauth2_redirect_url: oauth2_redirect_url = root_path + oauth2_redirect_url return get_swagger_ui_html( openapi_url=openapi_url, title=self.title + " - Swagger UI", oauth2_redirect_url=oauth2_redirect_url, init_oauth=self.swagger_ui_init_oauth, ) self.add_route(self.docs_url, swagger_ui_html, include_in_schema=False) if self.swagger_ui_oauth2_redirect_url: async def swagger_ui_redirect(req: Request) -> HTMLResponse: return get_swagger_ui_oauth2_redirect_html() self.add_route( self.swagger_ui_oauth2_redirect_url, swagger_ui_redirect, include_in_schema=False, ) if self.openapi_url and self.redoc_url: async def redoc_html(req: Request) -> HTMLResponse: root_path = req.scope.get("root_path", "").rstrip("/") openapi_url = root_path + self.openapi_url return get_redoc_html( openapi_url=openapi_url, title=self.title + " - ReDoc" ) self.add_route(self.redoc_url, redoc_html, include_in_schema=False)
(self) -> NoneType
10,404
fastapi.applications
trace
null
def trace( self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = "Successful Response", responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[Response] = Default(JSONResponse), name: Optional[str] = None, callbacks: Optional[List[BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None, ) -> Callable[[DecoratedCallable], DecoratedCallable]: return self.router.trace( path, response_model=response_model, status_code=status_code, tags=tags, dependencies=dependencies, summary=summary, description=description, response_description=response_description, responses=responses, deprecated=deprecated, operation_id=operation_id, response_model_include=response_model_include, response_model_exclude=response_model_exclude, response_model_by_alias=response_model_by_alias, response_model_exclude_unset=response_model_exclude_unset, response_model_exclude_defaults=response_model_exclude_defaults, response_model_exclude_none=response_model_exclude_none, include_in_schema=include_in_schema, response_class=response_class, name=name, callbacks=callbacks, openapi_extra=openapi_extra, )
(self, path: str, *, response_model: Optional[Type[Any]] = None, status_code: Optional[int] = None, tags: Optional[List[str]] = None, dependencies: Optional[Sequence[fastapi.params.Depends]] = None, summary: Optional[str] = None, description: Optional[str] = None, response_description: str = 'Successful Response', responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None, deprecated: Optional[bool] = None, operation_id: Optional[str] = None, response_model_include: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_exclude: Union[Set[Union[int, str]], Dict[Union[int, str], Any], NoneType] = None, response_model_by_alias: bool = True, response_model_exclude_unset: bool = False, response_model_exclude_defaults: bool = False, response_model_exclude_none: bool = False, include_in_schema: bool = True, response_class: Type[starlette.responses.Response] = <fastapi.datastructures.DefaultPlaceholder object at 0x7f52c37b9180>, name: Optional[str] = None, callbacks: Optional[List[starlette.routing.BaseRoute]] = None, openapi_extra: Optional[Dict[str, Any]] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,405
starlette.applications
url_path_for
null
def url_path_for(self, name: str, **path_params: str) -> URLPath: return self.router.url_path_for(name, **path_params)
(self, name: str, **path_params: str) -> starlette.datastructures.URLPath
10,406
fastapi.applications
websocket
null
def websocket( self, path: str, name: Optional[str] = None ) -> Callable[[DecoratedCallable], DecoratedCallable]: def decorator(func: DecoratedCallable) -> DecoratedCallable: self.add_api_websocket_route(path, func, name=name) return func return decorator
(self, path: str, name: Optional[str] = None) -> Callable[[~DecoratedCallable], ~DecoratedCallable]
10,407
starlette.applications
websocket_route
null
def websocket_route(self, path: str, name: str = None) -> typing.Callable: def decorator(func: typing.Callable) -> typing.Callable: self.router.add_websocket_route(path, func, name=name) return func return decorator
(self, path: str, name: Optional[str] = None) -> Callable
10,408
starlette.responses
JSONResponse
null
class JSONResponse(Response): media_type = "application/json" def render(self, content: typing.Any) -> bytes: return json.dumps( content, ensure_ascii=False, allow_nan=False, indent=None, separators=(",", ":"), ).encode("utf-8")
(content: Any = None, status_code: int = 200, headers: dict = None, media_type: str = None, background: starlette.background.BackgroundTask = None) -> None
10,409
starlette.responses
__call__
null
def delete_cookie(self, key: str, path: str = "/", domain: str = None) -> None: self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
(self, scope: MutableMapping[str, Any], receive: Callable[[], Awaitable[MutableMapping[str, Any]]], send: Callable[[MutableMapping[str, Any]], Awaitable[NoneType]]) -> NoneType
10,410
starlette.responses
__init__
null
def __init__( self, content: typing.Any = None, status_code: int = 200, headers: dict = None, media_type: str = None, background: BackgroundTask = None, ) -> None: self.status_code = status_code if media_type is not None: self.media_type = media_type self.background = background self.body = self.render(content) self.init_headers(headers)
(self, content: Optional[Any] = None, status_code: int = 200, headers: Optional[dict] = None, media_type: Optional[str] = None, background: Optional[starlette.background.BackgroundTask] = None) -> NoneType
10,412
starlette.responses
init_headers
null
def init_headers(self, headers: typing.Mapping[str, str] = None) -> None: if headers is None: raw_headers: typing.List[typing.Tuple[bytes, bytes]] = [] populate_content_length = True populate_content_type = True else: raw_headers = [ (k.lower().encode("latin-1"), v.encode("latin-1")) for k, v in headers.items() ] keys = [h[0] for h in raw_headers] populate_content_length = b"content-length" not in keys populate_content_type = b"content-type" not in keys body = getattr(self, "body", b"") if body and populate_content_length: content_length = str(len(body)) raw_headers.append((b"content-length", content_length.encode("latin-1"))) content_type = self.media_type if content_type is not None and populate_content_type: if content_type.startswith("text/"): content_type += "; charset=" + self.charset raw_headers.append((b"content-type", content_type.encode("latin-1"))) self.raw_headers = raw_headers
(self, headers: Optional[Mapping[str, str]] = None) -> NoneType
10,413
starlette.responses
render
null
def render(self, content: typing.Any) -> bytes: return json.dumps( content, ensure_ascii=False, allow_nan=False, indent=None, separators=(",", ":"), ).encode("utf-8")
(self, content: Any) -> bytes
10,414
starlette.responses
set_cookie
null
def set_cookie( self, key: str, value: str = "", max_age: int = None, expires: int = None, path: str = "/", domain: str = None, secure: bool = False, httponly: bool = False, samesite: str = "lax", ) -> None: cookie: http.cookies.BaseCookie = http.cookies.SimpleCookie() cookie[key] = value if max_age is not None: cookie[key]["max-age"] = max_age if expires is not None: cookie[key]["expires"] = expires if path is not None: cookie[key]["path"] = path if domain is not None: cookie[key]["domain"] = domain if secure: cookie[key]["secure"] = True if httponly: cookie[key]["httponly"] = True if samesite is not None: assert samesite.lower() in [ "strict", "lax", "none", ], "samesite must be either 'strict', 'lax' or 'none'" cookie[key]["samesite"] = samesite cookie_val = cookie.output(header="").strip() self.raw_headers.append((b"set-cookie", cookie_val.encode("latin-1")))
(self, key: str, value: str = '', max_age: Optional[int] = None, expires: Optional[int] = None, path: str = '/', domain: Optional[str] = None, secure: bool = False, httponly: bool = False, samesite: str = 'lax') -> NoneType
10,415
starlette.requests
Request
null
class Request(HTTPConnection): def __init__( self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send ): super().__init__(scope) assert scope["type"] == "http" self._receive = receive self._send = send self._stream_consumed = False self._is_disconnected = False @property def method(self) -> str: return self.scope["method"] @property def receive(self) -> Receive: return self._receive async def stream(self) -> typing.AsyncGenerator[bytes, None]: if hasattr(self, "_body"): yield self._body yield b"" return if self._stream_consumed: raise RuntimeError("Stream consumed") self._stream_consumed = True while True: message = await self._receive() if message["type"] == "http.request": body = message.get("body", b"") if body: yield body if not message.get("more_body", False): break elif message["type"] == "http.disconnect": self._is_disconnected = True raise ClientDisconnect() yield b"" async def body(self) -> bytes: if not hasattr(self, "_body"): chunks = [] async for chunk in self.stream(): chunks.append(chunk) self._body = b"".join(chunks) return self._body async def json(self) -> typing.Any: if not hasattr(self, "_json"): body = await self.body() self._json = json.loads(body) return self._json async def form(self) -> FormData: if not hasattr(self, "_form"): assert ( parse_options_header is not None ), "The `python-multipart` library must be installed to use form parsing." content_type_header = self.headers.get("Content-Type") content_type, options = parse_options_header(content_type_header) if content_type == b"multipart/form-data": multipart_parser = MultiPartParser(self.headers, self.stream()) self._form = await multipart_parser.parse() elif content_type == b"application/x-www-form-urlencoded": form_parser = FormParser(self.headers, self.stream()) self._form = await form_parser.parse() else: self._form = FormData() return self._form async def close(self) -> None: if hasattr(self, "_form"): await self._form.close() async def is_disconnected(self) -> bool: if not self._is_disconnected: message: Message = {} # If message isn't immediately available, move on with anyio.CancelScope() as cs: cs.cancel() message = await self._receive() if message.get("type") == "http.disconnect": self._is_disconnected = True return self._is_disconnected async def send_push_promise(self, path: str) -> None: if "http.response.push" in self.scope.get("extensions", {}): raw_headers = [] for name in SERVER_PUSH_HEADERS_TO_COPY: for value in self.headers.getlist(name): raw_headers.append( (name.encode("latin-1"), value.encode("latin-1")) ) await self._send( {"type": "http.response.push", "path": path, "headers": raw_headers} )
(scope: MutableMapping[str, Any], receive: Callable[[], Awaitable[MutableMapping[str, Any]]] = <function empty_receive at 0x7f52c382a560>, send: Callable[[MutableMapping[str, Any]], Awaitable[NoneType]] = <function empty_send at 0x7f52c382b910>)
10,417
starlette.requests
__getitem__
null
def __getitem__(self, key: str) -> str: return self.scope[key]
(self, key: str) -> str
10,418
starlette.requests
__init__
null
def __init__( self, scope: Scope, receive: Receive = empty_receive, send: Send = empty_send ): super().__init__(scope) assert scope["type"] == "http" self._receive = receive self._send = send self._stream_consumed = False self._is_disconnected = False
(self, scope: MutableMapping[str, Any], receive: Callable[[], Awaitable[MutableMapping[str, Any]]] = <function empty_receive at 0x7f52c382a560>, send: Callable[[MutableMapping[str, Any]], Awaitable[NoneType]] = <function empty_send at 0x7f52c382b910>)
10,419
starlette.requests
__iter__
null
def __iter__(self) -> typing.Iterator[str]: return iter(self.scope)
(self) -> Iterator[str]
10,420
starlette.requests
__len__
null
def __len__(self) -> int: return len(self.scope)
(self) -> int
10,421
starlette.requests
body
null
@property def receive(self) -> Receive: return self._receive
(self) -> bytes
10,431
starlette.requests
url_for
null
def url_for(self, name: str, **path_params: typing.Any) -> str: router = self.scope["router"] url_path = router.url_path_for(name, **path_params) return url_path.make_absolute_url(base_url=self.base_url)
(self, name: str, **path_params: Any) -> str
10,433
mongoengine.errors
ValidationError
Validation exception. May represent an error validating a field or a document containing fields with validation errors. :ivar errors: A dictionary of errors for fields within this document or list, or None if the error is for an individual field.
class ValidationError(AssertionError): """Validation exception. May represent an error validating a field or a document containing fields with validation errors. :ivar errors: A dictionary of errors for fields within this document or list, or None if the error is for an individual field. """ errors = {} field_name = None _message = None def __init__(self, message="", **kwargs): super().__init__(message) self.errors = kwargs.get("errors", {}) self.field_name = kwargs.get("field_name") self.message = message def __str__(self): return str(self.message) def __repr__(self): return f"{self.__class__.__name__}({self.message},)" def __getattribute__(self, name): message = super().__getattribute__(name) if name == "message": if self.field_name: message = "%s" % message if self.errors: message = f"{message}({self._format_errors()})" return message def _get_message(self): return self._message def _set_message(self, message): self._message = message message = property(_get_message, _set_message) def to_dict(self): """Returns a dictionary of all errors within a document Keys are field names or list indices and values are the validation error messages, or a nested dictionary of errors for an embedded document or list. """ def build_dict(source): errors_dict = {} if isinstance(source, dict): for field_name, error in source.items(): errors_dict[field_name] = build_dict(error) elif isinstance(source, ValidationError) and source.errors: return build_dict(source.errors) else: return str(source) return errors_dict if not self.errors: return {} return build_dict(self.errors) def _format_errors(self): """Returns a string listing all errors within a document""" def generate_key(value, prefix=""): if isinstance(value, list): value = " ".join([generate_key(k) for k in value]) elif isinstance(value, dict): value = " ".join([generate_key(v, k) for k, v in value.items()]) results = f"{prefix}.{value}" if prefix else value return results error_dict = defaultdict(list) for k, v in self.to_dict().items(): error_dict[generate_key(v)].append(k) return " ".join([f"{k}: {v}" for k, v in error_dict.items()])
(message='', **kwargs)
10,434
mongoengine.errors
__getattribute__
null
def __getattribute__(self, name): message = super().__getattribute__(name) if name == "message": if self.field_name: message = "%s" % message if self.errors: message = f"{message}({self._format_errors()})" return message
(self, name)
10,435
mongoengine.errors
__init__
null
def __init__(self, message="", **kwargs): super().__init__(message) self.errors = kwargs.get("errors", {}) self.field_name = kwargs.get("field_name") self.message = message
(self, message='', **kwargs)
10,436
mongoengine.errors
__repr__
null
def __repr__(self): return f"{self.__class__.__name__}({self.message},)"
(self)
10,437
mongoengine.errors
__str__
null
def __str__(self): return str(self.message)
(self)
10,438
mongoengine.errors
_format_errors
Returns a string listing all errors within a document
def _format_errors(self): """Returns a string listing all errors within a document""" def generate_key(value, prefix=""): if isinstance(value, list): value = " ".join([generate_key(k) for k in value]) elif isinstance(value, dict): value = " ".join([generate_key(v, k) for k, v in value.items()]) results = f"{prefix}.{value}" if prefix else value return results error_dict = defaultdict(list) for k, v in self.to_dict().items(): error_dict[generate_key(v)].append(k) return " ".join([f"{k}: {v}" for k, v in error_dict.items()])
(self)
10,439
mongoengine.errors
_get_message
null
def _get_message(self): return self._message
(self)
10,440
mongoengine.errors
_set_message
null
def _set_message(self, message): self._message = message
(self, message)
10,441
mongoengine.errors
to_dict
Returns a dictionary of all errors within a document Keys are field names or list indices and values are the validation error messages, or a nested dictionary of errors for an embedded document or list.
def to_dict(self): """Returns a dictionary of all errors within a document Keys are field names or list indices and values are the validation error messages, or a nested dictionary of errors for an embedded document or list. """ def build_dict(source): errors_dict = {} if isinstance(source, dict): for field_name, error in source.items(): errors_dict[field_name] = build_dict(error) elif isinstance(source, ValidationError) and source.errors: return build_dict(source.errors) else: return str(source) return errors_dict if not self.errors: return {} return build_dict(self.errors)
(self)
10,442
mongoengine.connection
connect
Connect to the database specified by the 'db' argument. Connection settings may be provided here as well if the database is not running on the default port on localhost. If authentication is needed, provide username and password arguments as well. Multiple databases are supported by using aliases. Provide a separate `alias` to connect to a different instance of: program: `mongod`. In order to replace a connection identified by a given alias, you'll need to call ``disconnect`` first See the docstring for `register_connection` for more details about all supported kwargs.
def connect(db=None, alias=DEFAULT_CONNECTION_NAME, **kwargs): """Connect to the database specified by the 'db' argument. Connection settings may be provided here as well if the database is not running on the default port on localhost. If authentication is needed, provide username and password arguments as well. Multiple databases are supported by using aliases. Provide a separate `alias` to connect to a different instance of: program: `mongod`. In order to replace a connection identified by a given alias, you'll need to call ``disconnect`` first See the docstring for `register_connection` for more details about all supported kwargs. """ if alias in _connections: prev_conn_setting = _connection_settings[alias] new_conn_settings = _get_connection_settings(db, **kwargs) if new_conn_settings != prev_conn_setting: err_msg = ( "A different connection with alias `{}` was already " "registered. Use disconnect() first" ).format(alias) raise ConnectionFailure(err_msg) else: register_connection(alias, db, **kwargs) return get_connection(alias)
(db=None, alias='default', **kwargs)
10,443
mongoengine.connection
disconnect_all
Close all registered database.
def disconnect_all(): """Close all registered database.""" for alias in list(_connections.keys()): disconnect(alias)
()
10,444
fastack_mongoengine
handle_validation_error
null
def handle_validation_error(request: Request, exc: ValidationError): content = {"detail": exc.message} return JSONResponse(content, status_code=status.HTTP_400_BAD_REQUEST)
(request: starlette.requests.Request, exc: mongoengine.errors.ValidationError)
10,445
fastack_mongoengine
setup
null
def setup(app: Fastack): def on_startup(): url = getattr(app.state.settings, "MONGODB_URI", None) if not url: raise RuntimeError("MONGODB_URI is not set") connect(host=url) def on_shutdown(): disconnect_all() app.add_event_handler("startup", on_startup) app.add_event_handler("shutdown", on_shutdown) app.add_exception_handler(ValidationError, handle_validation_error)
(app: fastack.app.Fastack)
10,447
rethinkdb
RethinkDB
null
class RethinkDB(builtins.object): def __init__(self): super(RethinkDB, self).__init__() from rethinkdb import ( _dump, _export, _import, _index_rebuild, _restore, ast, query, net, ) self._dump = _dump self._export = _export self._import = _import self._index_rebuild = _index_rebuild self._restore = _restore # Re-export internal modules for backward compatibility self.ast = ast self.errors = errors self.net = net self.query = query net.Connection._r = self for module in (self.net, self.query, self.ast, self.errors): for function_name in module.__all__: setattr(self, function_name, getattr(module, function_name)) self.set_loop_type(None) def set_loop_type(self, library=None): if library == "asyncio": from rethinkdb.asyncio_net import net_asyncio self.connection_type = net_asyncio.Connection if library == "gevent": from rethinkdb.gevent_net import net_gevent self.connection_type = net_gevent.Connection if library == "tornado": from rethinkdb.tornado_net import net_tornado self.connection_type = net_tornado.Connection if library == "trio": from rethinkdb.trio_net import net_trio self.connection_type = net_trio.Connection if library == "twisted": from rethinkdb.twisted_net import net_twisted self.connection_type = net_twisted.Connection if library is None or self.connection_type is None: self.connection_type = self.net.DefaultConnection return def connect(self, *args, **kwargs): return self.make_connection(self.connection_type, *args, **kwargs)
()
10,448
rethinkdb
__init__
null
def __init__(self): super(RethinkDB, self).__init__() from rethinkdb import ( _dump, _export, _import, _index_rebuild, _restore, ast, query, net, ) self._dump = _dump self._export = _export self._import = _import self._index_rebuild = _index_rebuild self._restore = _restore # Re-export internal modules for backward compatibility self.ast = ast self.errors = errors self.net = net self.query = query net.Connection._r = self for module in (self.net, self.query, self.ast, self.errors): for function_name in module.__all__: setattr(self, function_name, getattr(module, function_name)) self.set_loop_type(None)
(self)
10,449
rethinkdb
connect
null
def connect(self, *args, **kwargs): return self.make_connection(self.connection_type, *args, **kwargs)
(self, *args, **kwargs)
10,450
rethinkdb
set_loop_type
null
def set_loop_type(self, library=None): if library == "asyncio": from rethinkdb.asyncio_net import net_asyncio self.connection_type = net_asyncio.Connection if library == "gevent": from rethinkdb.gevent_net import net_gevent self.connection_type = net_gevent.Connection if library == "tornado": from rethinkdb.tornado_net import net_tornado self.connection_type = net_tornado.Connection if library == "trio": from rethinkdb.trio_net import net_trio self.connection_type = net_trio.Connection if library == "twisted": from rethinkdb.twisted_net import net_twisted self.connection_type = net_twisted.Connection if library is None or self.connection_type is None: self.connection_type = self.net.DefaultConnection return
(self, library=None)
10,467
alika
App
null
class App: def __init__(self) -> None: self.base_url = "https://keel.algida.me/electra/api" self.auth = AuthService(base_url=self.base_url) self.user = UserService(base_url=self.base_url) self.app = AppFunctionality(base_url=self.base_url, user_token=None) def set_user_token(self, user_token): self.user.user_token = user_token self.app.user_token = user_token
() -> None
10,468
alika
__init__
null
def __init__(self) -> None: self.base_url = "https://keel.algida.me/electra/api" self.auth = AuthService(base_url=self.base_url) self.user = UserService(base_url=self.base_url) self.app = AppFunctionality(base_url=self.base_url, user_token=None)
(self) -> NoneType
10,469
alika
set_user_token
null
def set_user_token(self, user_token): self.user.user_token = user_token self.app.user_token = user_token
(self, user_token)
10,470
alika.app_functionality
AppFunctionality
null
class AppFunctionality: def __init__(self, base_url: str, user_token: Optional[str] = None): self.api_service = APIService(base_url) self.user_token = user_token def perform_action(self, action_data: Dict) -> Dict: return self.api_service.perform_app_action(self.user_token, action_data)
(base_url: str, user_token: Optional[str] = None)
10,471
alika.app_functionality
__init__
null
def __init__(self, base_url: str, user_token: Optional[str] = None): self.api_service = APIService(base_url) self.user_token = user_token
(self, base_url: str, user_token: Optional[str] = None)
10,472
alika.app_functionality
perform_action
null
def perform_action(self, action_data: Dict) -> Dict: return self.api_service.perform_app_action(self.user_token, action_data)
(self, action_data: Dict) -> Dict
10,473
alika.auth_service
AuthService
null
class AuthService: def __init__(self, base_url: str): self.api_service = APIService(base_url) def send_verification_code(self, phone_number: str) -> Dict: return self.api_service.send_verification_code(phone_number) def verify_code(self, phone_number: str, verification_code: str) -> Dict: return self.api_service.verify_code(phone_number, verification_code) def login(self, phone_number: str, token: str) -> Dict: return self.api_service.login(phone_number, token)
(base_url: str)
10,474
alika.auth_service
__init__
null
def __init__(self, base_url: str): self.api_service = APIService(base_url)
(self, base_url: str)
10,475
alika.auth_service
login
null
def login(self, phone_number: str, token: str) -> Dict: return self.api_service.login(phone_number, token)
(self, phone_number: str, token: str) -> Dict
10,476
alika.auth_service
send_verification_code
null
def send_verification_code(self, phone_number: str) -> Dict: return self.api_service.send_verification_code(phone_number)
(self, phone_number: str) -> Dict
10,477
alika.auth_service
verify_code
null
def verify_code(self, phone_number: str, verification_code: str) -> Dict: return self.api_service.verify_code(phone_number, verification_code)
(self, phone_number: str, verification_code: str) -> Dict
10,478
alika.user_service
UserService
null
class UserService: def __init__(self, base_url: str, user_token: Optional[str] = None): self.api_service = APIService(base_url) self.user_token = user_token def get_user_data(self) -> Dict: return self.api_service.get_user_data(self.user_token) def update_user_settings(self, new_settings: Dict) -> Dict: return self.api_service.update_user_settings(self.user_token, new_settings)
(base_url: str, user_token: Optional[str] = None)
10,480
alika.user_service
get_user_data
null
def get_user_data(self) -> Dict: return self.api_service.get_user_data(self.user_token)
(self) -> Dict
10,481
alika.user_service
update_user_settings
null
def update_user_settings(self, new_settings: Dict) -> Dict: return self.api_service.update_user_settings(self.user_token, new_settings)
(self, new_settings: Dict) -> Dict
10,486
datclass
Datclass
null
def get_datclass( extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = get_identifier, empty_dict_as_none=False, nested: bool = True, ): """Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass. """ def to_item(v, ignore_none=False): """Convert v to a dictionary or a list. :param v: :param ignore_none: Ignore values that are None. :return: """ if isinstance(v, Datclass): v = v.to_dict(ignore_none=ignore_none) elif isinstance(v, list): v = [to_item(i, ignore_none=ignore_none) for i in v] return v def convert_attr_value(value, type_, cls): """Convert the value of the attribute. :param value: :param type_: :param cls: :return: """ if value is None: return None if empty_dict_as_none and value == {}: return None origin = get_origin(type_) if origin is None and isinstance(value, dict): if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, ForwardRef): type_ = sys.modules[cls.__module__].__dict__[type_.__forward_arg__] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__[type_] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, TypeVar): # Generic type_ = type_.__bound__ if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif origin is list: args_ = get_args(type_) if args_: type_ = args_[0] value = [convert_attr_value(i, type_, cls) for i in value] elif origin is Union: types_ = get_args(type_) if len(types_) == 2 and NoneType in types_: # Optional if types_[0] is NoneType: type_ = types_[1] else: type_ = types_[0] value = convert_attr_value(value, type_, cls) return value class Datclass: def __new__(cls, *args, **kwargs): """Modify the `__init__` function to support extended attributes.""" if _ORIGINAL_INIT_NAME not in cls.__dict__: # Each time an object is instantiated, it enters the `__new__` method; # let's add a conditional check here. setattr(cls, _ORIGINAL_INIT_NAME, cls.__init__) cls.__init__ = cls.__datclass_init__ return super().__new__(cls) def __datclass_init__(self, *args, **kwargs): """A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return: """ # All code assumes that "cls" is a dataclass and a subclass of "__dataclass__", # eliminating the need for further checks. cls = self.__class__ if cls is Datclass: # Handling Generic Types and Creating Objects Directly using DataClass. for attr, value in kwargs.items(): if empty_dict_as_none and value == {}: value = None setattr(self, attr, value) return # Map any field name to a valid Python field name. kwargs = {cls.__rename_attrs__.get(k, k): v for k, v in kwargs.items()} # Call the original constructor. original_init = getattr(self, _ORIGINAL_INIT_NAME) init_kwargs = {k: kwargs.pop(k) for k in self.__dataclass_fields__ if k in kwargs} # type: ignore original_init(*args, **init_kwargs) # Extend fields or log missing fields, including undefined fields. if extra or log: frozen = cls.__dataclass_params__.frozen # type: ignore for attr, value in kwargs.items(): ok_attr = identifier_transform(attr) if log: # Log missing fields, including undefined fields. # Facilitate Timely Data Updates log_message = f'{cls.__module__}.{cls.__name__}({ok_attr}: {type(value).__name__} = {value!r})' if ok_attr != attr: log_message += f' # rename from {attr!r}' _log.warning(log_message) if not frozen and extra: setattr(self, ok_attr, value) # Record the renaming of fields. if ok_attr != attr and attr not in self.__rename_attrs__: self.__rename_attrs__[attr] = ok_attr # noinspection PyUnusedLocal def __post_init__(self, *args, **kwargs): """Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ... """ if not nested: return for attr_name, field in self.__dataclass_fields__.items(): # type: ignore value = getattr(self, attr_name) new_value = convert_attr_value(value, field.type, self.__class__) if new_value is not value: setattr(self, attr_name, new_value) # Original field name -> Valid Python field name after renaming __rename_attrs__: ClassVar[Dict[str, str]] = {} @classmethod def from_str(cls, text: str): """Create an instance from a JSON string.""" return cls(**json.loads(text)) @classmethod def from_file(cls, file_path: str, encoding: str = 'utf8'): """Create an instance from a JSON file.""" text = Path(file_path).read_text(encoding=encoding) return cls.from_str(text) def to_dict(self, ignore_none=False, recursive_ignore=True) -> dict: """Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return: """ rename_attrs_inverse = {v: k for k, v in self.__rename_attrs__.items()} result_dict, object_attrs = {}, {} if hasattr(self, '__slots__'): object_attrs.update({k: getattr(self, k) for k in self.__slots__}) object_attrs.update(self.__dict__) for attr_name, attr_value in object_attrs.items(): # Exclude private attributes: # '__orig_class__' if attr_name.startswith('__'): continue if attr_value is None and ignore_none: continue target_attr_name = rename_attrs_inverse.get(attr_name, attr_name) transformed_value = to_item(attr_value, ignore_none=ignore_none and recursive_ignore) result_dict[target_attr_name] = transformed_value return result_dict def to_str( self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True ) -> str: """Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return: """ data_dict = self.to_dict( ignore_none=ignore_none, recursive_ignore=recursive_ignore ) json_str = json.dumps( data_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys ) return json_str def to_file(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False): """Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return: """ Path(file_path).write_text( self.to_str( ensure_ascii=ensure_ascii, indent=indent, ignore_none=ignore_none, sort_keys=sort_keys ), encoding=encoding, ) return Datclass
(*args, **kwargs)
10,487
datclass
__datclass_init__
A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return:
def get_datclass( extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = get_identifier, empty_dict_as_none=False, nested: bool = True, ): """Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass. """ def to_item(v, ignore_none=False): """Convert v to a dictionary or a list. :param v: :param ignore_none: Ignore values that are None. :return: """ if isinstance(v, Datclass): v = v.to_dict(ignore_none=ignore_none) elif isinstance(v, list): v = [to_item(i, ignore_none=ignore_none) for i in v] return v def convert_attr_value(value, type_, cls): """Convert the value of the attribute. :param value: :param type_: :param cls: :return: """ if value is None: return None if empty_dict_as_none and value == {}: return None origin = get_origin(type_) if origin is None and isinstance(value, dict): if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, ForwardRef): type_ = sys.modules[cls.__module__].__dict__[type_.__forward_arg__] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__[type_] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, TypeVar): # Generic type_ = type_.__bound__ if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif origin is list: args_ = get_args(type_) if args_: type_ = args_[0] value = [convert_attr_value(i, type_, cls) for i in value] elif origin is Union: types_ = get_args(type_) if len(types_) == 2 and NoneType in types_: # Optional if types_[0] is NoneType: type_ = types_[1] else: type_ = types_[0] value = convert_attr_value(value, type_, cls) return value class Datclass: def __new__(cls, *args, **kwargs): """Modify the `__init__` function to support extended attributes.""" if _ORIGINAL_INIT_NAME not in cls.__dict__: # Each time an object is instantiated, it enters the `__new__` method; # let's add a conditional check here. setattr(cls, _ORIGINAL_INIT_NAME, cls.__init__) cls.__init__ = cls.__datclass_init__ return super().__new__(cls) def __datclass_init__(self, *args, **kwargs): """A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return: """ # All code assumes that "cls" is a dataclass and a subclass of "__dataclass__", # eliminating the need for further checks. cls = self.__class__ if cls is Datclass: # Handling Generic Types and Creating Objects Directly using DataClass. for attr, value in kwargs.items(): if empty_dict_as_none and value == {}: value = None setattr(self, attr, value) return # Map any field name to a valid Python field name. kwargs = {cls.__rename_attrs__.get(k, k): v for k, v in kwargs.items()} # Call the original constructor. original_init = getattr(self, _ORIGINAL_INIT_NAME) init_kwargs = {k: kwargs.pop(k) for k in self.__dataclass_fields__ if k in kwargs} # type: ignore original_init(*args, **init_kwargs) # Extend fields or log missing fields, including undefined fields. if extra or log: frozen = cls.__dataclass_params__.frozen # type: ignore for attr, value in kwargs.items(): ok_attr = identifier_transform(attr) if log: # Log missing fields, including undefined fields. # Facilitate Timely Data Updates log_message = f'{cls.__module__}.{cls.__name__}({ok_attr}: {type(value).__name__} = {value!r})' if ok_attr != attr: log_message += f' # rename from {attr!r}' _log.warning(log_message) if not frozen and extra: setattr(self, ok_attr, value) # Record the renaming of fields. if ok_attr != attr and attr not in self.__rename_attrs__: self.__rename_attrs__[attr] = ok_attr # noinspection PyUnusedLocal def __post_init__(self, *args, **kwargs): """Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ... """ if not nested: return for attr_name, field in self.__dataclass_fields__.items(): # type: ignore value = getattr(self, attr_name) new_value = convert_attr_value(value, field.type, self.__class__) if new_value is not value: setattr(self, attr_name, new_value) # Original field name -> Valid Python field name after renaming __rename_attrs__: ClassVar[Dict[str, str]] = {} @classmethod def from_str(cls, text: str): """Create an instance from a JSON string.""" return cls(**json.loads(text)) @classmethod def from_file(cls, file_path: str, encoding: str = 'utf8'): """Create an instance from a JSON file.""" text = Path(file_path).read_text(encoding=encoding) return cls.from_str(text) def to_dict(self, ignore_none=False, recursive_ignore=True) -> dict: """Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return: """ rename_attrs_inverse = {v: k for k, v in self.__rename_attrs__.items()} result_dict, object_attrs = {}, {} if hasattr(self, '__slots__'): object_attrs.update({k: getattr(self, k) for k in self.__slots__}) object_attrs.update(self.__dict__) for attr_name, attr_value in object_attrs.items(): # Exclude private attributes: # '__orig_class__' if attr_name.startswith('__'): continue if attr_value is None and ignore_none: continue target_attr_name = rename_attrs_inverse.get(attr_name, attr_name) transformed_value = to_item(attr_value, ignore_none=ignore_none and recursive_ignore) result_dict[target_attr_name] = transformed_value return result_dict def to_str( self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True ) -> str: """Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return: """ data_dict = self.to_dict( ignore_none=ignore_none, recursive_ignore=recursive_ignore ) json_str = json.dumps( data_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys ) return json_str def to_file(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False): """Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return: """ Path(file_path).write_text( self.to_str( ensure_ascii=ensure_ascii, indent=indent, ignore_none=ignore_none, sort_keys=sort_keys ), encoding=encoding, ) return Datclass
(self, *args, **kwargs)
10,488
datclass
__new__
Modify the `__init__` function to support extended attributes.
def get_datclass( extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = get_identifier, empty_dict_as_none=False, nested: bool = True, ): """Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass. """ def to_item(v, ignore_none=False): """Convert v to a dictionary or a list. :param v: :param ignore_none: Ignore values that are None. :return: """ if isinstance(v, Datclass): v = v.to_dict(ignore_none=ignore_none) elif isinstance(v, list): v = [to_item(i, ignore_none=ignore_none) for i in v] return v def convert_attr_value(value, type_, cls): """Convert the value of the attribute. :param value: :param type_: :param cls: :return: """ if value is None: return None if empty_dict_as_none and value == {}: return None origin = get_origin(type_) if origin is None and isinstance(value, dict): if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, ForwardRef): type_ = sys.modules[cls.__module__].__dict__[type_.__forward_arg__] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__[type_] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, TypeVar): # Generic type_ = type_.__bound__ if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif origin is list: args_ = get_args(type_) if args_: type_ = args_[0] value = [convert_attr_value(i, type_, cls) for i in value] elif origin is Union: types_ = get_args(type_) if len(types_) == 2 and NoneType in types_: # Optional if types_[0] is NoneType: type_ = types_[1] else: type_ = types_[0] value = convert_attr_value(value, type_, cls) return value class Datclass: def __new__(cls, *args, **kwargs): """Modify the `__init__` function to support extended attributes.""" if _ORIGINAL_INIT_NAME not in cls.__dict__: # Each time an object is instantiated, it enters the `__new__` method; # let's add a conditional check here. setattr(cls, _ORIGINAL_INIT_NAME, cls.__init__) cls.__init__ = cls.__datclass_init__ return super().__new__(cls) def __datclass_init__(self, *args, **kwargs): """A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return: """ # All code assumes that "cls" is a dataclass and a subclass of "__dataclass__", # eliminating the need for further checks. cls = self.__class__ if cls is Datclass: # Handling Generic Types and Creating Objects Directly using DataClass. for attr, value in kwargs.items(): if empty_dict_as_none and value == {}: value = None setattr(self, attr, value) return # Map any field name to a valid Python field name. kwargs = {cls.__rename_attrs__.get(k, k): v for k, v in kwargs.items()} # Call the original constructor. original_init = getattr(self, _ORIGINAL_INIT_NAME) init_kwargs = {k: kwargs.pop(k) for k in self.__dataclass_fields__ if k in kwargs} # type: ignore original_init(*args, **init_kwargs) # Extend fields or log missing fields, including undefined fields. if extra or log: frozen = cls.__dataclass_params__.frozen # type: ignore for attr, value in kwargs.items(): ok_attr = identifier_transform(attr) if log: # Log missing fields, including undefined fields. # Facilitate Timely Data Updates log_message = f'{cls.__module__}.{cls.__name__}({ok_attr}: {type(value).__name__} = {value!r})' if ok_attr != attr: log_message += f' # rename from {attr!r}' _log.warning(log_message) if not frozen and extra: setattr(self, ok_attr, value) # Record the renaming of fields. if ok_attr != attr and attr not in self.__rename_attrs__: self.__rename_attrs__[attr] = ok_attr # noinspection PyUnusedLocal def __post_init__(self, *args, **kwargs): """Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ... """ if not nested: return for attr_name, field in self.__dataclass_fields__.items(): # type: ignore value = getattr(self, attr_name) new_value = convert_attr_value(value, field.type, self.__class__) if new_value is not value: setattr(self, attr_name, new_value) # Original field name -> Valid Python field name after renaming __rename_attrs__: ClassVar[Dict[str, str]] = {} @classmethod def from_str(cls, text: str): """Create an instance from a JSON string.""" return cls(**json.loads(text)) @classmethod def from_file(cls, file_path: str, encoding: str = 'utf8'): """Create an instance from a JSON file.""" text = Path(file_path).read_text(encoding=encoding) return cls.from_str(text) def to_dict(self, ignore_none=False, recursive_ignore=True) -> dict: """Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return: """ rename_attrs_inverse = {v: k for k, v in self.__rename_attrs__.items()} result_dict, object_attrs = {}, {} if hasattr(self, '__slots__'): object_attrs.update({k: getattr(self, k) for k in self.__slots__}) object_attrs.update(self.__dict__) for attr_name, attr_value in object_attrs.items(): # Exclude private attributes: # '__orig_class__' if attr_name.startswith('__'): continue if attr_value is None and ignore_none: continue target_attr_name = rename_attrs_inverse.get(attr_name, attr_name) transformed_value = to_item(attr_value, ignore_none=ignore_none and recursive_ignore) result_dict[target_attr_name] = transformed_value return result_dict def to_str( self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True ) -> str: """Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return: """ data_dict = self.to_dict( ignore_none=ignore_none, recursive_ignore=recursive_ignore ) json_str = json.dumps( data_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys ) return json_str def to_file(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False): """Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return: """ Path(file_path).write_text( self.to_str( ensure_ascii=ensure_ascii, indent=indent, ignore_none=ignore_none, sort_keys=sort_keys ), encoding=encoding, ) return Datclass
(cls, *args, **kwargs)
10,489
datclass
__post_init__
Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ...
def get_datclass( extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = get_identifier, empty_dict_as_none=False, nested: bool = True, ): """Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass. """ def to_item(v, ignore_none=False): """Convert v to a dictionary or a list. :param v: :param ignore_none: Ignore values that are None. :return: """ if isinstance(v, Datclass): v = v.to_dict(ignore_none=ignore_none) elif isinstance(v, list): v = [to_item(i, ignore_none=ignore_none) for i in v] return v def convert_attr_value(value, type_, cls): """Convert the value of the attribute. :param value: :param type_: :param cls: :return: """ if value is None: return None if empty_dict_as_none and value == {}: return None origin = get_origin(type_) if origin is None and isinstance(value, dict): if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, ForwardRef): type_ = sys.modules[cls.__module__].__dict__[type_.__forward_arg__] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__[type_] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, TypeVar): # Generic type_ = type_.__bound__ if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif origin is list: args_ = get_args(type_) if args_: type_ = args_[0] value = [convert_attr_value(i, type_, cls) for i in value] elif origin is Union: types_ = get_args(type_) if len(types_) == 2 and NoneType in types_: # Optional if types_[0] is NoneType: type_ = types_[1] else: type_ = types_[0] value = convert_attr_value(value, type_, cls) return value class Datclass: def __new__(cls, *args, **kwargs): """Modify the `__init__` function to support extended attributes.""" if _ORIGINAL_INIT_NAME not in cls.__dict__: # Each time an object is instantiated, it enters the `__new__` method; # let's add a conditional check here. setattr(cls, _ORIGINAL_INIT_NAME, cls.__init__) cls.__init__ = cls.__datclass_init__ return super().__new__(cls) def __datclass_init__(self, *args, **kwargs): """A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return: """ # All code assumes that "cls" is a dataclass and a subclass of "__dataclass__", # eliminating the need for further checks. cls = self.__class__ if cls is Datclass: # Handling Generic Types and Creating Objects Directly using DataClass. for attr, value in kwargs.items(): if empty_dict_as_none and value == {}: value = None setattr(self, attr, value) return # Map any field name to a valid Python field name. kwargs = {cls.__rename_attrs__.get(k, k): v for k, v in kwargs.items()} # Call the original constructor. original_init = getattr(self, _ORIGINAL_INIT_NAME) init_kwargs = {k: kwargs.pop(k) for k in self.__dataclass_fields__ if k in kwargs} # type: ignore original_init(*args, **init_kwargs) # Extend fields or log missing fields, including undefined fields. if extra or log: frozen = cls.__dataclass_params__.frozen # type: ignore for attr, value in kwargs.items(): ok_attr = identifier_transform(attr) if log: # Log missing fields, including undefined fields. # Facilitate Timely Data Updates log_message = f'{cls.__module__}.{cls.__name__}({ok_attr}: {type(value).__name__} = {value!r})' if ok_attr != attr: log_message += f' # rename from {attr!r}' _log.warning(log_message) if not frozen and extra: setattr(self, ok_attr, value) # Record the renaming of fields. if ok_attr != attr and attr not in self.__rename_attrs__: self.__rename_attrs__[attr] = ok_attr # noinspection PyUnusedLocal def __post_init__(self, *args, **kwargs): """Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ... """ if not nested: return for attr_name, field in self.__dataclass_fields__.items(): # type: ignore value = getattr(self, attr_name) new_value = convert_attr_value(value, field.type, self.__class__) if new_value is not value: setattr(self, attr_name, new_value) # Original field name -> Valid Python field name after renaming __rename_attrs__: ClassVar[Dict[str, str]] = {} @classmethod def from_str(cls, text: str): """Create an instance from a JSON string.""" return cls(**json.loads(text)) @classmethod def from_file(cls, file_path: str, encoding: str = 'utf8'): """Create an instance from a JSON file.""" text = Path(file_path).read_text(encoding=encoding) return cls.from_str(text) def to_dict(self, ignore_none=False, recursive_ignore=True) -> dict: """Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return: """ rename_attrs_inverse = {v: k for k, v in self.__rename_attrs__.items()} result_dict, object_attrs = {}, {} if hasattr(self, '__slots__'): object_attrs.update({k: getattr(self, k) for k in self.__slots__}) object_attrs.update(self.__dict__) for attr_name, attr_value in object_attrs.items(): # Exclude private attributes: # '__orig_class__' if attr_name.startswith('__'): continue if attr_value is None and ignore_none: continue target_attr_name = rename_attrs_inverse.get(attr_name, attr_name) transformed_value = to_item(attr_value, ignore_none=ignore_none and recursive_ignore) result_dict[target_attr_name] = transformed_value return result_dict def to_str( self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True ) -> str: """Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return: """ data_dict = self.to_dict( ignore_none=ignore_none, recursive_ignore=recursive_ignore ) json_str = json.dumps( data_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys ) return json_str def to_file(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False): """Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return: """ Path(file_path).write_text( self.to_str( ensure_ascii=ensure_ascii, indent=indent, ignore_none=ignore_none, sort_keys=sort_keys ), encoding=encoding, ) return Datclass
(self, *args, **kwargs)
10,490
datclass
to_dict
Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return:
def get_datclass( extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = get_identifier, empty_dict_as_none=False, nested: bool = True, ): """Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass. """ def to_item(v, ignore_none=False): """Convert v to a dictionary or a list. :param v: :param ignore_none: Ignore values that are None. :return: """ if isinstance(v, Datclass): v = v.to_dict(ignore_none=ignore_none) elif isinstance(v, list): v = [to_item(i, ignore_none=ignore_none) for i in v] return v def convert_attr_value(value, type_, cls): """Convert the value of the attribute. :param value: :param type_: :param cls: :return: """ if value is None: return None if empty_dict_as_none and value == {}: return None origin = get_origin(type_) if origin is None and isinstance(value, dict): if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, ForwardRef): type_ = sys.modules[cls.__module__].__dict__[type_.__forward_arg__] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__[type_] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, TypeVar): # Generic type_ = type_.__bound__ if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif origin is list: args_ = get_args(type_) if args_: type_ = args_[0] value = [convert_attr_value(i, type_, cls) for i in value] elif origin is Union: types_ = get_args(type_) if len(types_) == 2 and NoneType in types_: # Optional if types_[0] is NoneType: type_ = types_[1] else: type_ = types_[0] value = convert_attr_value(value, type_, cls) return value class Datclass: def __new__(cls, *args, **kwargs): """Modify the `__init__` function to support extended attributes.""" if _ORIGINAL_INIT_NAME not in cls.__dict__: # Each time an object is instantiated, it enters the `__new__` method; # let's add a conditional check here. setattr(cls, _ORIGINAL_INIT_NAME, cls.__init__) cls.__init__ = cls.__datclass_init__ return super().__new__(cls) def __datclass_init__(self, *args, **kwargs): """A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return: """ # All code assumes that "cls" is a dataclass and a subclass of "__dataclass__", # eliminating the need for further checks. cls = self.__class__ if cls is Datclass: # Handling Generic Types and Creating Objects Directly using DataClass. for attr, value in kwargs.items(): if empty_dict_as_none and value == {}: value = None setattr(self, attr, value) return # Map any field name to a valid Python field name. kwargs = {cls.__rename_attrs__.get(k, k): v for k, v in kwargs.items()} # Call the original constructor. original_init = getattr(self, _ORIGINAL_INIT_NAME) init_kwargs = {k: kwargs.pop(k) for k in self.__dataclass_fields__ if k in kwargs} # type: ignore original_init(*args, **init_kwargs) # Extend fields or log missing fields, including undefined fields. if extra or log: frozen = cls.__dataclass_params__.frozen # type: ignore for attr, value in kwargs.items(): ok_attr = identifier_transform(attr) if log: # Log missing fields, including undefined fields. # Facilitate Timely Data Updates log_message = f'{cls.__module__}.{cls.__name__}({ok_attr}: {type(value).__name__} = {value!r})' if ok_attr != attr: log_message += f' # rename from {attr!r}' _log.warning(log_message) if not frozen and extra: setattr(self, ok_attr, value) # Record the renaming of fields. if ok_attr != attr and attr not in self.__rename_attrs__: self.__rename_attrs__[attr] = ok_attr # noinspection PyUnusedLocal def __post_init__(self, *args, **kwargs): """Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ... """ if not nested: return for attr_name, field in self.__dataclass_fields__.items(): # type: ignore value = getattr(self, attr_name) new_value = convert_attr_value(value, field.type, self.__class__) if new_value is not value: setattr(self, attr_name, new_value) # Original field name -> Valid Python field name after renaming __rename_attrs__: ClassVar[Dict[str, str]] = {} @classmethod def from_str(cls, text: str): """Create an instance from a JSON string.""" return cls(**json.loads(text)) @classmethod def from_file(cls, file_path: str, encoding: str = 'utf8'): """Create an instance from a JSON file.""" text = Path(file_path).read_text(encoding=encoding) return cls.from_str(text) def to_dict(self, ignore_none=False, recursive_ignore=True) -> dict: """Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return: """ rename_attrs_inverse = {v: k for k, v in self.__rename_attrs__.items()} result_dict, object_attrs = {}, {} if hasattr(self, '__slots__'): object_attrs.update({k: getattr(self, k) for k in self.__slots__}) object_attrs.update(self.__dict__) for attr_name, attr_value in object_attrs.items(): # Exclude private attributes: # '__orig_class__' if attr_name.startswith('__'): continue if attr_value is None and ignore_none: continue target_attr_name = rename_attrs_inverse.get(attr_name, attr_name) transformed_value = to_item(attr_value, ignore_none=ignore_none and recursive_ignore) result_dict[target_attr_name] = transformed_value return result_dict def to_str( self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True ) -> str: """Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return: """ data_dict = self.to_dict( ignore_none=ignore_none, recursive_ignore=recursive_ignore ) json_str = json.dumps( data_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys ) return json_str def to_file(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False): """Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return: """ Path(file_path).write_text( self.to_str( ensure_ascii=ensure_ascii, indent=indent, ignore_none=ignore_none, sort_keys=sort_keys ), encoding=encoding, ) return Datclass
(self, ignore_none=False, recursive_ignore=True) -> dict
10,491
datclass
to_file
Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return:
def get_datclass( extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = get_identifier, empty_dict_as_none=False, nested: bool = True, ): """Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass. """ def to_item(v, ignore_none=False): """Convert v to a dictionary or a list. :param v: :param ignore_none: Ignore values that are None. :return: """ if isinstance(v, Datclass): v = v.to_dict(ignore_none=ignore_none) elif isinstance(v, list): v = [to_item(i, ignore_none=ignore_none) for i in v] return v def convert_attr_value(value, type_, cls): """Convert the value of the attribute. :param value: :param type_: :param cls: :return: """ if value is None: return None if empty_dict_as_none and value == {}: return None origin = get_origin(type_) if origin is None and isinstance(value, dict): if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, ForwardRef): type_ = sys.modules[cls.__module__].__dict__[type_.__forward_arg__] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__[type_] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, TypeVar): # Generic type_ = type_.__bound__ if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif origin is list: args_ = get_args(type_) if args_: type_ = args_[0] value = [convert_attr_value(i, type_, cls) for i in value] elif origin is Union: types_ = get_args(type_) if len(types_) == 2 and NoneType in types_: # Optional if types_[0] is NoneType: type_ = types_[1] else: type_ = types_[0] value = convert_attr_value(value, type_, cls) return value class Datclass: def __new__(cls, *args, **kwargs): """Modify the `__init__` function to support extended attributes.""" if _ORIGINAL_INIT_NAME not in cls.__dict__: # Each time an object is instantiated, it enters the `__new__` method; # let's add a conditional check here. setattr(cls, _ORIGINAL_INIT_NAME, cls.__init__) cls.__init__ = cls.__datclass_init__ return super().__new__(cls) def __datclass_init__(self, *args, **kwargs): """A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return: """ # All code assumes that "cls" is a dataclass and a subclass of "__dataclass__", # eliminating the need for further checks. cls = self.__class__ if cls is Datclass: # Handling Generic Types and Creating Objects Directly using DataClass. for attr, value in kwargs.items(): if empty_dict_as_none and value == {}: value = None setattr(self, attr, value) return # Map any field name to a valid Python field name. kwargs = {cls.__rename_attrs__.get(k, k): v for k, v in kwargs.items()} # Call the original constructor. original_init = getattr(self, _ORIGINAL_INIT_NAME) init_kwargs = {k: kwargs.pop(k) for k in self.__dataclass_fields__ if k in kwargs} # type: ignore original_init(*args, **init_kwargs) # Extend fields or log missing fields, including undefined fields. if extra or log: frozen = cls.__dataclass_params__.frozen # type: ignore for attr, value in kwargs.items(): ok_attr = identifier_transform(attr) if log: # Log missing fields, including undefined fields. # Facilitate Timely Data Updates log_message = f'{cls.__module__}.{cls.__name__}({ok_attr}: {type(value).__name__} = {value!r})' if ok_attr != attr: log_message += f' # rename from {attr!r}' _log.warning(log_message) if not frozen and extra: setattr(self, ok_attr, value) # Record the renaming of fields. if ok_attr != attr and attr not in self.__rename_attrs__: self.__rename_attrs__[attr] = ok_attr # noinspection PyUnusedLocal def __post_init__(self, *args, **kwargs): """Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ... """ if not nested: return for attr_name, field in self.__dataclass_fields__.items(): # type: ignore value = getattr(self, attr_name) new_value = convert_attr_value(value, field.type, self.__class__) if new_value is not value: setattr(self, attr_name, new_value) # Original field name -> Valid Python field name after renaming __rename_attrs__: ClassVar[Dict[str, str]] = {} @classmethod def from_str(cls, text: str): """Create an instance from a JSON string.""" return cls(**json.loads(text)) @classmethod def from_file(cls, file_path: str, encoding: str = 'utf8'): """Create an instance from a JSON file.""" text = Path(file_path).read_text(encoding=encoding) return cls.from_str(text) def to_dict(self, ignore_none=False, recursive_ignore=True) -> dict: """Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return: """ rename_attrs_inverse = {v: k for k, v in self.__rename_attrs__.items()} result_dict, object_attrs = {}, {} if hasattr(self, '__slots__'): object_attrs.update({k: getattr(self, k) for k in self.__slots__}) object_attrs.update(self.__dict__) for attr_name, attr_value in object_attrs.items(): # Exclude private attributes: # '__orig_class__' if attr_name.startswith('__'): continue if attr_value is None and ignore_none: continue target_attr_name = rename_attrs_inverse.get(attr_name, attr_name) transformed_value = to_item(attr_value, ignore_none=ignore_none and recursive_ignore) result_dict[target_attr_name] = transformed_value return result_dict def to_str( self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True ) -> str: """Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return: """ data_dict = self.to_dict( ignore_none=ignore_none, recursive_ignore=recursive_ignore ) json_str = json.dumps( data_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys ) return json_str def to_file(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False): """Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return: """ Path(file_path).write_text( self.to_str( ensure_ascii=ensure_ascii, indent=indent, ignore_none=ignore_none, sort_keys=sort_keys ), encoding=encoding, ) return Datclass
(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False)
10,492
datclass
to_str
Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return:
def get_datclass( extra: bool = True, log: bool = True, identifier_transform: Callable[[str], str] = get_identifier, empty_dict_as_none=False, nested: bool = True, ): """Get a decorator that can be used to convert a dataclass to a datclass. :param extra: Whether to extend fields. :param log: Whether to log missing fields, including undefined fields. :param identifier_transform: A function that maps any field name to a valid Python field name. :param empty_dict_as_none: Convert empty dict to None when converting to a DataClass. :param nested: Whether to recursively convert nested dataclasses. :return: A class that extends a dataclass. """ def to_item(v, ignore_none=False): """Convert v to a dictionary or a list. :param v: :param ignore_none: Ignore values that are None. :return: """ if isinstance(v, Datclass): v = v.to_dict(ignore_none=ignore_none) elif isinstance(v, list): v = [to_item(i, ignore_none=ignore_none) for i in v] return v def convert_attr_value(value, type_, cls): """Convert the value of the attribute. :param value: :param type_: :param cls: :return: """ if value is None: return None if empty_dict_as_none and value == {}: return None origin = get_origin(type_) if origin is None and isinstance(value, dict): if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, ForwardRef): type_ = sys.modules[cls.__module__].__dict__[type_.__forward_arg__] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, str): type_ = sys.modules[cls.__module__].__dict__[type_] if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif isinstance(type_, TypeVar): # Generic type_ = type_.__bound__ if hasattr(type_, DatClass.__datclass_init__.__name__): value = type_(**value) elif origin is list: args_ = get_args(type_) if args_: type_ = args_[0] value = [convert_attr_value(i, type_, cls) for i in value] elif origin is Union: types_ = get_args(type_) if len(types_) == 2 and NoneType in types_: # Optional if types_[0] is NoneType: type_ = types_[1] else: type_ = types_[0] value = convert_attr_value(value, type_, cls) return value class Datclass: def __new__(cls, *args, **kwargs): """Modify the `__init__` function to support extended attributes.""" if _ORIGINAL_INIT_NAME not in cls.__dict__: # Each time an object is instantiated, it enters the `__new__` method; # let's add a conditional check here. setattr(cls, _ORIGINAL_INIT_NAME, cls.__init__) cls.__init__ = cls.__datclass_init__ return super().__new__(cls) def __datclass_init__(self, *args, **kwargs): """A new constructor that extends the original constructor. :param self: Instances of a class that inherits from __dataclass__. :param args: :param kwargs: :return: """ # All code assumes that "cls" is a dataclass and a subclass of "__dataclass__", # eliminating the need for further checks. cls = self.__class__ if cls is Datclass: # Handling Generic Types and Creating Objects Directly using DataClass. for attr, value in kwargs.items(): if empty_dict_as_none and value == {}: value = None setattr(self, attr, value) return # Map any field name to a valid Python field name. kwargs = {cls.__rename_attrs__.get(k, k): v for k, v in kwargs.items()} # Call the original constructor. original_init = getattr(self, _ORIGINAL_INIT_NAME) init_kwargs = {k: kwargs.pop(k) for k in self.__dataclass_fields__ if k in kwargs} # type: ignore original_init(*args, **init_kwargs) # Extend fields or log missing fields, including undefined fields. if extra or log: frozen = cls.__dataclass_params__.frozen # type: ignore for attr, value in kwargs.items(): ok_attr = identifier_transform(attr) if log: # Log missing fields, including undefined fields. # Facilitate Timely Data Updates log_message = f'{cls.__module__}.{cls.__name__}({ok_attr}: {type(value).__name__} = {value!r})' if ok_attr != attr: log_message += f' # rename from {attr!r}' _log.warning(log_message) if not frozen and extra: setattr(self, ok_attr, value) # Record the renaming of fields. if ok_attr != attr and attr not in self.__rename_attrs__: self.__rename_attrs__[attr] = ok_attr # noinspection PyUnusedLocal def __post_init__(self, *args, **kwargs): """Handling nested dataclasses. The `__post_init__` in subclasses must call this method, otherwise nested dataclasses cannot be processed. About `get_origin` and `get_args` -------------------------------- `get_origin` and `get_args` are used to handle generic types. Examples: >>> from typing import get_origin, get_args >>> from typing import List, Dict, Tuple, Union, Optional >>> >>> assert get_origin(List[int]) is list ... assert get_origin(Dict[str, int]) is dict ... assert get_origin(Optional[int]) is Union ... # assert get_origin(<other>) is None ... >>> assert get_args(List[int]) == (int,) ... assert get_args(Union[int, str]) == (int, str) ... # assert get_args(Optional[int]) == (int, NoneType) ... """ if not nested: return for attr_name, field in self.__dataclass_fields__.items(): # type: ignore value = getattr(self, attr_name) new_value = convert_attr_value(value, field.type, self.__class__) if new_value is not value: setattr(self, attr_name, new_value) # Original field name -> Valid Python field name after renaming __rename_attrs__: ClassVar[Dict[str, str]] = {} @classmethod def from_str(cls, text: str): """Create an instance from a JSON string.""" return cls(**json.loads(text)) @classmethod def from_file(cls, file_path: str, encoding: str = 'utf8'): """Create an instance from a JSON file.""" text = Path(file_path).read_text(encoding=encoding) return cls.from_str(text) def to_dict(self, ignore_none=False, recursive_ignore=True) -> dict: """Convert an instance to a dictionary. :param ignore_none: Ignore values that are None. :param recursive_ignore: Ignore values that are None recursively. :return: """ rename_attrs_inverse = {v: k for k, v in self.__rename_attrs__.items()} result_dict, object_attrs = {}, {} if hasattr(self, '__slots__'): object_attrs.update({k: getattr(self, k) for k in self.__slots__}) object_attrs.update(self.__dict__) for attr_name, attr_value in object_attrs.items(): # Exclude private attributes: # '__orig_class__' if attr_name.startswith('__'): continue if attr_value is None and ignore_none: continue target_attr_name = rename_attrs_inverse.get(attr_name, attr_name) transformed_value = to_item(attr_value, ignore_none=ignore_none and recursive_ignore) result_dict[target_attr_name] = transformed_value return result_dict def to_str( self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True ) -> str: """Convert an instance to a JSON string. :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :param recursive_ignore: Ignore values that are None recursively. :return: """ data_dict = self.to_dict( ignore_none=ignore_none, recursive_ignore=recursive_ignore ) json_str = json.dumps( data_dict, ensure_ascii=ensure_ascii, indent=indent, sort_keys=sort_keys ) return json_str def to_file(self, file_path: str, encoding: str = 'utf8', ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False): """Convert an instance to a JSON file. :param file_path: Save file path. :param encoding: same as json dumps :param ensure_ascii: same as json dumps :param indent: same as json dumps :param ignore_none: Ignore values that are None. :param sort_keys: same as json dumps :return: """ Path(file_path).write_text( self.to_str( ensure_ascii=ensure_ascii, indent=indent, ignore_none=ignore_none, sort_keys=sort_keys ), encoding=encoding, ) return Datclass
(self, ensure_ascii=True, indent=None, ignore_none=False, sort_keys=False, recursive_ignore=True) -> str
10,493
typing
ForwardRef
Internal wrapper to hold a forward reference.
class ForwardRef(_Final, _root=True): """Internal wrapper to hold a forward reference.""" __slots__ = ('__forward_arg__', '__forward_code__', '__forward_evaluated__', '__forward_value__', '__forward_is_argument__', '__forward_is_class__', '__forward_module__') def __init__(self, arg, is_argument=True, module=None, *, is_class=False): if not isinstance(arg, str): raise TypeError(f"Forward reference must be a string -- got {arg!r}") try: code = compile(arg, '<string>', 'eval') except SyntaxError: raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}") self.__forward_arg__ = arg self.__forward_code__ = code self.__forward_evaluated__ = False self.__forward_value__ = None self.__forward_is_argument__ = is_argument self.__forward_is_class__ = is_class self.__forward_module__ = module def _evaluate(self, globalns, localns, recursive_guard): if self.__forward_arg__ in recursive_guard: return self if not self.__forward_evaluated__ or localns is not globalns: if globalns is None and localns is None: globalns = localns = {} elif globalns is None: globalns = localns elif localns is None: localns = globalns if self.__forward_module__ is not None: globalns = getattr( sys.modules.get(self.__forward_module__, None), '__dict__', globalns ) type_ = _type_check( eval(self.__forward_code__, globalns, localns), "Forward references must evaluate to types.", is_argument=self.__forward_is_argument__, allow_special_forms=self.__forward_is_class__, ) self.__forward_value__ = _eval_type( type_, globalns, localns, recursive_guard | {self.__forward_arg__} ) self.__forward_evaluated__ = True return self.__forward_value__ def __eq__(self, other): if not isinstance(other, ForwardRef): return NotImplemented if self.__forward_evaluated__ and other.__forward_evaluated__: return (self.__forward_arg__ == other.__forward_arg__ and self.__forward_value__ == other.__forward_value__) return (self.__forward_arg__ == other.__forward_arg__ and self.__forward_module__ == other.__forward_module__) def __hash__(self): return hash((self.__forward_arg__, self.__forward_module__)) def __repr__(self): return f'ForwardRef({self.__forward_arg__!r})'
(arg, is_argument=True, module=None, *, is_class=False)
10,494
typing
__eq__
null
def __eq__(self, other): if not isinstance(other, ForwardRef): return NotImplemented if self.__forward_evaluated__ and other.__forward_evaluated__: return (self.__forward_arg__ == other.__forward_arg__ and self.__forward_value__ == other.__forward_value__) return (self.__forward_arg__ == other.__forward_arg__ and self.__forward_module__ == other.__forward_module__)
(self, other)
10,495
typing
__hash__
null
def __hash__(self): return hash((self.__forward_arg__, self.__forward_module__))
(self)
10,496
typing
__init__
null
def __init__(self, arg, is_argument=True, module=None, *, is_class=False): if not isinstance(arg, str): raise TypeError(f"Forward reference must be a string -- got {arg!r}") try: code = compile(arg, '<string>', 'eval') except SyntaxError: raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}") self.__forward_arg__ = arg self.__forward_code__ = code self.__forward_evaluated__ = False self.__forward_value__ = None self.__forward_is_argument__ = is_argument self.__forward_is_class__ = is_class self.__forward_module__ = module
(self, arg, is_argument=True, module=None, *, is_class=False)