1 Welcome to the Pareto DAB (Dual Active Bridge) Tool
1.1 Installation
Install the Toolbox as a developer
pip install -e .
2 DAB Computational Toolbox (DCT) documentation
Init python files as modules.
- class dct.Any(*args, **kwargs)
Bases:
objectSpecial type indicating an unconstrained type.
Any is compatible with every type.
Any assumed to have all methods.
All values assumed to be instances of Any.
Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks.
- class dct.BoundaryCheck
Bases:
objectBoundary check for parameter.
- static check_dictionary(keyword_dictionary: dict, keyword: str, keyword_list_name: str) tuple[bool, str]
Check the keyword according match in keyword dictionary.
- Parameters:
keyword_dictionary (dict) – Dictionary with keywords
keyword (str) – Keyword to check
keyword_list_name (str) – Name of keyword to mention in inconsistency report, if check fails
- Returns:
tuple: Indication if the verification failed | Error text with description about the deviation
- Return type:
tuple[bool, str]
- static check_float_min_max_values(minimum: float, maximum: float, min_max_value: list[float], parameter_name: str, check_type_minimum: CheckCondition, check_type_maximum: CheckCondition) tuple[bool, str]
Perform a boundary check for the minimum/maximum-pair.
- Parameters:
minimum (float) – Minimum value of the range
maximum (float) – Maximum value of the range
min_max_value (list[tuple[list[float], str]]) – 2 float values for the minimum and maximum boundary check
parameter_name (str) – Name of parameter to mention in inconsistency report, if check fails
check_type_minimum (CheckCondition) – Type of check to perform according the minimum value
check_type_maximum (CheckCondition) – Type of check to perform according the maximum value
- Returns:
tuple: Indication if the verification failed | Error text with description about the deviation
- Return type:
tuple[bool, str]
- static check_float_min_max_values_list(minimum: float, maximum: float, min_max_value_list: list[tuple[list[float], str]], check_type_minimum: CheckCondition, check_type_maximum: CheckCondition) tuple[bool, str]
Perform a boundary check of the minimum/maximum-pair.
- Parameters:
minimum (float) – Minimum value of the range
maximum (float) – Maximum value of the range
min_max_value_list (list[tuple[list[float], str]]) – List of 2 float values according provided minimum and maximum to check and the parameter name
check_type_minimum (CheckCondition) – Type of check to perform according the minimum value
check_type_maximum (CheckCondition) – Type of check to perform according the maximum value
- Returns:
tuple: Indication if the verification failed | Error text with description about the deviation
- Return type:
tuple[bool, str]
- static check_float_value(minimum: float, maximum: float, parameter_value: float, parameter_name: str, check_type_minimum: CheckCondition, check_type_maximum: CheckCondition) tuple[bool, str]
Verify the value according minimum and maximum.
- Parameters:
minimum (float) – Minimum value of the range
maximum (float) – Maximum value of the range
parameter_value (float) – Float values to check and the value name
parameter_name (str) – Name of parameter to mention in inconsistency report, if check fails
check_type_minimum (CheckCondition) – Type of check to perform according the minimum value
check_type_maximum (CheckCondition) – Type of check to perform according the maximum value
- Returns:
tuple: Indication if the verification failed | Error text with description about the deviation
- Return type:
tuple[bool, str]
- static check_float_value_list(minimum: float, maximum: float, value_list: list[tuple[float, str]], check_type_minimum: CheckCondition, check_type_maximum: CheckCondition) tuple[bool, str]
Verify the listed values according minimum and maximum.
- Parameters:
minimum (float) – Minimum value of the range
maximum (float) – Maximum value of the range
value_list (list[tuple[float, str]]) – List of float values to check and the parameter name
check_type_minimum (CheckCondition) – Type of check to perform according the minimum value
check_type_maximum (CheckCondition) – Type of check to perform according the maximum value
- Returns:
tuple: Indication if the verification failed | Error text with description about the deviation
- Return type:
tuple[bool, str]
- static convert_int_list_to_float_list(int_value_list: list[int]) list[float]
Convert a list of integer values in a list of float values.
- Parameters:
int_value_list (list[int]) – List of integer values
- Returns:
List of float values
- Return type:
list[float]
- class dct.Breakpoints(*, circuit_pareto: Literal['no', 'pause', 'stop'], circuit_filtered: Literal['no', 'pause', 'stop'], capacitor: Literal['no', 'pause', 'stop'], inductor: Literal['no', 'pause', 'stop'], transformer: Literal['no', 'pause', 'stop'], heat_sink: Literal['no', 'pause', 'stop'], pre_summary: Literal['no', 'pause', 'stop'], summary: Literal['no', 'pause', 'stop'])
Bases:
BaseModelFlow control breakpoints.
- capacitor: Literal['no', 'pause', 'stop']
- circuit_filtered: Literal['no', 'pause', 'stop']
- circuit_pareto: Literal['no', 'pause', 'stop']
- heat_sink: Literal['no', 'pause', 'stop']
- inductor: Literal['no', 'pause', 'stop']
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- pre_summary: Literal['no', 'pause', 'stop']
- summary: Literal['no', 'pause', 'stop']
- transformer: Literal['no', 'pause', 'stop']
- class dct.CalcModeEnum(*values)
Bases:
EnumEnum for calculation mode.
- continue_mode = 'continue'
- new_mode = 'new'
- skip_mode = 'skip'
- class dct.Capacitor(*, calculation_modes: list[Literal['new', 'skip']], subdirectory: str)
Bases:
BaseModelFlow control for the capacitor 1.
- calculation_modes: list[Literal['new', 'skip']]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- subdirectory: str
- class dct.CapacitorConfiguration(study_data: StudyData, capacitor_toml_data: TomlCapacitorSelection | None = None)
Bases:
objectStudy data and toml-file for capacitor configuration.
- capacitor_toml_data: TomlCapacitorSelection | None = None
- class dct.CapacitorOptimizationDto(circuit_id: str, progress_data: ProgressData, capacitor_optimization_dto: CapacitorRequirements, capacitor_number_in_circuit: int, time_array: ndarray, current_array: ndarray, factor_dc_losses_min_max_list: list[float])
Bases:
objectDTO for the inductor optimization.
- capacitor_number_in_circuit: int
- capacitor_optimization_dto: CapacitorRequirements
- circuit_id: str
- current_array: ndarray
- factor_dc_losses_min_max_list: list[float]
- progress_data: ProgressData
- time_array: ndarray
- class dct.CapacitorRequirements(**kwargs)
Bases:
objectRequirements for a single capacitor design from the circuit results.
- The current waveform needs to be given for a full period:
time_vec (time based)
the current_vec gives the amplitude of the current at given time
- capacitor_number_in_circuit: int
- circuit_id: str
- current_array: ndarray
- current_vec: ndarray
- study_name: str
- time_array: ndarray
- time_vec: ndarray
- v_dc_max: float
- class dct.CapacitorResults(**kwargs)
Bases:
objectDTO contains the inductor losses.
- area_total: float
- capacitor_id: str
- capacitor_number_in_circuit: int
- circuit_id: str
- loss_total_array: ndarray
- n_parallel: int
- n_series: int
- volume_total: float
- class dct.CapacitorSelection
Bases:
objectSelect suitable capacitors.
- c_df: DataFrame
- initialize_capacitor_selection(configuration_data_list: list[CapacitorConfiguration], capacitor_requirements_list: list[CapacitorRequirements]) None
Initialize the capacitor selection.
The initialization initialize the optimization config list, which contains lists separated by number of capacitor component in circuit. After performing this method, the optimization handler can be used to optimize the selected capacitor. The selection capacitor is defined by the number of capacitor component.
- Parameters:
configuration_data_list (list[CapacitorConfiguration]) – List of capacitor configuration data including study data
capacitor_requirements_list (list[CapacitorRequirements]) – list with capacitor requirements
- optimization_handler(filter_data: FilterData, capacitor_in_circuit: int, debug: Debug) None
Control the multi simulation processes.
- Parameters:
filter_data (dct.FilterData) – Information about the filtered designs
capacitor_in_circuit (int) – Number of capacitor within topology
debug (bool) – True to use debug mode which stops earlier
- static verify_optimization_parameter(toml_capacitor: TomlCapacitorSelection) tuple[bool, str]
Verify the parameters from toml file for the capacitor optimization.
Dummy method so far.
- Parameters:
toml_capacitor (TomlCapacitorSelection) – capacitor toml file to check
- Returns:
is_consistent, issue_report
- Return type:
tuple[bool, str]
- class dct.CheckCondition(*values)
Bases:
EnumEnum for type of check.
- check_exclusive = 2
- check_ignore = 0
- check_inclusive = 1
- class dct.Circuit(*, number_of_trials: int, calculation_mode: Literal['new', 'continue', 'skip'], subdirectory: str)
Bases:
BaseModelFlow control for the circuit.
- calculation_mode: Literal['new', 'continue', 'skip']
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- number_of_trials: int
- subdirectory: str
- class dct.CircuitConfigurationDataDto(configuration_name: str, number_of_trials: int, filtered_points_name_list: list[tuple[str, int] | Any], progress_data: ProgressData)
Bases:
objectDTO for queue circuit configuration information transfer.
- configuration_name: str
- number_of_trials: int
- progress_data: ProgressData
- class dct.CircuitOptimizationBase
Bases:
Generic[T_G_D,T_C_D],ABCRepresent the base class for electrical converter optimization depending on the topology.
- abstractmethod add_time_domain_simulations() None
Add time domain simulations to the existing circuit DTOs.
- static filter_df(df: DataFrame, x: str = 'values_0', y: str = 'values_1', factor_min_dc_losses: float = 1.2, factor_max_dc_losses: float = 10, abs_max_losses: float = 100000) DataFrame
Remove designs with too high losses compared to the minimum losses.
- Parameters:
df (pd.DataFrame) – pandas DataFrame with study results
x (str) – x-value name for Pareto plot filtering
y (str) – y-value name for Pareto plot filtering
factor_min_dc_losses (float) – filter factor for the minimum dc losses
factor_max_dc_losses (float) – dc_max_loss = factor_max_dc_losses * min_available_dc_losses_in_pareto_front
abs_max_losses (float) – Absolute maximum losses (clip above this value)
- Returns:
pandas DataFrame with Pareto front near points
- Return type:
pd.DataFrame
- abstractmethod filter_study_results() tuple[bool, str]
Filter the study result and (later to implement->) use ngspice for detailed calculation.
- Returns:
True, if the study results are filtered and empty string or False and report of the issues
- Return type:
tuple[bool, str]
- abstractmethod static generate_circuit_toml(file_path: str) None
Generate the default circuit configuration file.
- Parameters:
file_path (str) – filename including absolute path
- abstractmethod static generate_general_toml(file_path: str) None
Generate the default general configuration file.
- Parameters:
file_path (str) – filename including absolute path
- abstractmethod generate_result_dtos(summary_data: StudyData, capacitor_selection_data_list: list[CapacitorConfiguration], inductor_configuration_list: list[InductorConfiguration], transformer_configuration_list: list[TransformerConfiguration], df: DataFrame, is_pre_summary: bool = True) None
Generate the result dtos from a given (filtered) result dataframe.
- Parameters:
summary_data (StudyData) – Summary Data
capacitor_selection_data_list (list[CapacitorConfiguration]) – List of capacitor selection data
inductor_configuration_list (list[InductorConfiguration]) – List of inductor study data
transformer_configuration_list (list[TransformerConfiguration]) – List of transformer study data
df (pd.DataFrame) – dataframe to take the results from
is_pre_summary (bool) – True for pre-summary, False for summary
- Returns:
None
- Return type:
None
- abstractmethod get_actual_pareto_html() str
Read the current Pareto front from running optimization process.
- Returns:
Pareto front html page
- Return type:
str
- abstractmethod get_capacitor_requirements() list[CapacitorRequirements]
Get the capacitor requirements.
- Returns:
Capacitor requirements
- Return type:
- abstractmethod static get_circuit_plot_data(act_study_data: StudyData) PlotData
Provide the circuit data to plot.
- abstractmethod get_inductor_requirements() list[InductorRequirements]
Get the inductor requirements.
- Returns:
Inductor requirements
- Return type:
- abstractmethod static get_number_of_required_capacitors() int
Get the number of required capacitors.
- Returns:
Number of capacitors required by the actual topology
- Return type:
int
- abstractmethod static get_number_of_required_inductors() int
Get the number of required inductors.
- Returns:
Number of inductors required by the actual topology
- Return type:
int
- abstractmethod static get_number_of_required_transformers() int
Get the number of required transformers.
- Returns:
Number of transformers required by the actual topology
- Return type:
int
- abstractmethod static get_pareto_html(study_name: str, path_name: str) str
Read the current Pareto front from running optimization process.
- Parameters:
study_name (str) – Name of the optuna study
path_name (str) – Path where optuna study is located
- Returns:
Pareto front html page
- Return type:
str
- abstractmethod get_progress_data() ProgressData
Provide the progress data of the optimization.
- Returns:
Progress data: Processing start time, actual processing time, number of filtered operation points and status.
- Return type:
- abstractmethod get_transformer_requirements() list[TransformerRequirements]
Get the transformer requirements.
- Returns:
Transformer requirements
- Return type:
- init_study_information(study_name: str, project_directory: str, sub_directory: str, calculation_mode: CalcModeEnum) None
Initialize the study information.
- Parameters:
study_name (str) – Name of the study
project_directory (Project folder path) – Project directory name
sub_directory (Sub directory path) – Sub directory of the circuit optimization
calculation_mode (CalcModeEnum) – Calculation mode of the circuit optimization
- abstractmethod initialize_circuit_optimization() bool
Initialize the circuit optimization configuration.
- Returns:
True, if the configuration is initialized
- Return type:
bool
- is_circuit_optimization_skippable() tuple[bool, str]
Control procedure of skippable optimization check.
- Returns:
True, if the optimization is skippable and empty string or False and report of the issues
- Return type:
tuple[bool, str]
- static is_pareto_efficient(costs: ndarray, return_mask: bool = True) ndarray
Find the pareto-efficient points.
- Parameters:
costs (np.array) – An (n_points, n_costs) array
return_mask (bool) – True to return a mask
- Returns:
An array of indices of pareto-efficient points. If return_mask is True, this will be an (n_points, ) boolean array Otherwise it will be a (n_efficient_points, ) integer array of indices.
- Return type:
np.array
- abstractmethod load_and_verify_circuit_parameters(toml_dict: dict[str, Any], is_tdb_to_update: bool = False) tuple[bool, str]
Load and verify the circuit input parameter.
- Parameters:
toml_dict (dict[str, Any]) – toml general configuration
is_tdb_to_update (bool) – indicated, if the transistor database is up to date
- Returns:
True, if the configuration was consistent and empty string or False and report of the issues
- Return type:
tuple[bool, str]
- abstractmethod load_and_verify_general_parameters(toml_dict: dict[str, Any]) tuple[bool, str]
Verify the input parameter ranges.
- Parameters:
toml_dict (dict[str, Any]) – toml general configuration
- Returns:
True, if the configuration was consistent and empty string or False and report of the issues
- Return type:
tuple[bool, str]
- misc: float
- static pareto_front_from_df(df: DataFrame, x: str = 'values_0', y: str = 'values_1') DataFrame
Calculate the Pareto front from a Pandas DataFrame. Return a Pandas DataFrame.
- Parameters:
df (pd.DataFrame) – Pandas DataFrame
x (str) – Name of x-parameter from df to show in Pareto plane
y (str) – Name of y-parameter from df to show in Pareto plane
- Returns:
Pandas DataFrame with pareto efficient points
- Return type:
pd.DataFrame
- abstractmethod static plot_compare_waveforms(dto_directory: str) None
Compare calculated waveforms with simulated waveforms (GeckoCIRCUITS).
- Parameters:
dto_directory (str) – Folder of circuit DTOs to read the values from
- r_th_per_unit_area_ind_heat_sink = 0
- r_th_per_unit_area_xfmr_heat_sink = 0
- abstractmethod start_proceed_study(number_trials: int, database_type: str = 'sqlite', sampler: BaseSampler = <optuna.samplers._nsgaiii._sampler.NSGAIIISampler object>) None
Proceed a study which is stored as sqlite database.
- Parameters:
number_trials (int) – Number of trials adding to the existing study
database_type (str) – storage database, e.g. ‘sqlite’ or ‘mysql’
sampler (optuna.sampler-object) – optuna.samplers.NSGAIISampler() or optuna.samplers.NSGAIIISampler(). Note about the brackets () !! Default: NSGAIII
- abstractmethod static visualize_all_lab_data(filepath: str) None
Generate plots or tables for the practical operation in the lab.
- Parameters:
filepath (str) – filepath
- abstractmethod static visualize_single_lab_data(filepath: str, combination_id: str) None
Generate plots or tables for a single operation in the lab.
- Parameters:
filepath (str) – filepath
combination_id (str) – combination ID of object to plot
- class dct.ComponentCooling(tim_thickness: float, tim_conductivity: float)
Bases:
objectFix parameters for the transistor, inductor and transformer cooling.
- tim_conductivity: float
- tim_thickness: float
- class dct.CondBreakpoints(*, circuit: int, inductor: int, transformer: int, heat_sink: int)
Bases:
BaseModelFlow control conditional breakpoints.
- circuit: int
- heat_sink: int
- inductor: int
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- transformer: int
- class dct.ConfigurationDataEntryDto(configuration_name: str, number_of_trials: int, progress_data: ProgressData)
Bases:
objectDTO for queue configuration data information transfer.
- configuration_name: str
- number_of_trials: int
- progress_data: ProgressData
- class dct.ConfigurationDataFiles(*, topology_files: list[str], capacitor_configuration_files: list[str], inductor_configuration_files: list[str], transformer_configuration_files: list[str], heat_sink_configuration_file: str)
Bases:
BaseModelFile paths to the configuration files.
- capacitor_configuration_files: list[str]
- heat_sink_configuration_file: str
- inductor_configuration_files: list[str]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- topology_files: list[str]
- transformer_configuration_files: list[str]
- class dct.DabCircuitOptimization
Bases:
CircuitOptimizationBase[TomlDabGeneral,TomlDabCircuitParetoDesign]Optimize the DAB converter regarding maximum ZVS coverage and minimum conduction losses.
- add_time_domain_simulations() None
Add time domain simulations to the existing circuit DTOs.
- static calculate_fixed_parameters(act_dab_config: CircuitParetoDabDesign) FixedParameters
Calculate time-consuming parameters which are same for every single simulation.
- Parameters:
act_dab_config (circuit_dtos.CircuitParetoDabDesign) – DAB circuit configuration
- Returns:
Fix parameters (transistor DTOs)
- Return type:
d_dtos.FixedParameters
- copper_coin_area_1: float
- copper_coin_area_2: float
- static create_sqlite_database_url(act_study_data: StudyData) str
Create the DAB circuit optimization sqlite URL.
- Parameters:
act_study_data (StudyData) – Information about the circuit study name and study path
- Returns:
SQLite URL
- Return type:
str
- static df_plot_pareto_front(df: DataFrame, figure_size: tuple) None
Plot an interactive Pareto diagram (losses vs. volume) to select the transformers to re-simulate.
- Parameters:
df (pd.DataFrame) – DataFrame, generated from an optuna study (exported by optuna)
figure_size (tuple) – figure size as x,y-tuple in mm, e.g. (160, 80)
- df_to_dab_dto_list(df: DataFrame) list[DabCircuitDTO]
Load a DAB-DTO from an optuna study.
- Parameters:
df (pd.DataFrame) – Pandas DataFrame to convert to the DAB-DTO list
- Returns:
List of DTO
- Return type:
list[d_dtos.DabCircuitDTO]
- filter_study_results() tuple[bool, str]
Filter the study result and use GeckoCIRCUITS for detailed calculation.
- static generate_circuit_toml(file_path: str) None
Generate the default DabCircuitConf.toml file.
- Parameters:
file_path (str) – filename including absolute path
- static generate_general_toml(file_path: str) None
Generate the default DabCircuitConf.toml file.
- Parameters:
file_path (str) – filename including absolute path
- static generate_operating_point_table(combination_dto: DabCircuitDTO, plot_results_path: str, combination_id: str) None
Generate operating point table for lab work.
- Parameters:
combination_dto (DabCircuitDTO) – combination DTO
plot_results_path (str) – Path to store the result table
combination_id (int) – combination ID
- generate_result_dtos(summary_data: StudyData, capacitor_selection_data_list: list[CapacitorConfiguration], inductor_configuration_list: list[InductorConfiguration], transformer_configuration_list: list[TransformerConfiguration], df: DataFrame, is_pre_summary: bool = True) None
Generate the result dtos from a given (filtered) result dataframe.
- Parameters:
summary_data (StudyData) – Summary Data
capacitor_selection_data_list (list[CapacitorConfiguration]) – List of capacitor selection data
inductor_configuration_list (list[InductorConfiguration]) – List of inductor study data
transformer_configuration_list (list[TransformerConfiguration]) – List of transformer study data
df (pd.DataFrame) – dataframe to take the results from
is_pre_summary (bool) – True for pre-summary, False for summary
- get_actual_pareto_html() str
Read the current Pareto front from running optimization process.
- Returns:
Pareto front html page
- Return type:
str
- get_capacitor_requirements() list[CapacitorRequirements]
Get the capacitor requirements.
- Returns:
Capacitor Requirements
- Return type:
- get_config() CircuitParetoDabDesign | None
Return the actual loaded configuration file.
- Returns:
Configuration file as circuit_dtos.DabDesign
- Return type:
circuit_dtos.CircuitParetoDabDesign
- get_inductor_requirements() list[InductorRequirements]
Get the inductor requirements.
- Returns:
Inductor Requirements
- Return type:
- static get_number_of_required_capacitors() int
Get the number of required capacitors.
- Returns:
Number of capacitors required by the actual topology
- Return type:
int
- static get_number_of_required_inductors() int
Get the number of required inductors.
- Returns:
Number of inductors required by the actual topology
- Return type:
int
- static get_number_of_required_transformers() int
Get the number of required transformers.
- Returns:
Number of transformers required by the actual topology
- Return type:
int
- static get_pareto_html(study_name: str, path_name: str) str
Read the current Pareto front from running optimization process.
- Parameters:
study_name (str) – Name of the optuna study
path_name (str) – Path where optuna study is located
- Returns:
Pareto front html page
- Return type:
str
- get_progress_data() ProgressData
Provide the progress data of the optimization.
- Returns:
Progress data: Processing start time, actual processing time, number of filtered operation points and status.
- Return type:
- get_transformer_requirements() list[TransformerRequirements]
Get the transformer requirements.
- Returns:
Transformer Requirements
- Return type:
- initialize_circuit_optimization() bool
Initialize the circuit_dto for circuit optimization.
- Returns:
True, if the configuration was successful initialized
- Return type:
bool
- load_and_verify_circuit_parameters(toml_dict: dict[str, Any], is_tdb_to_update: bool = False) tuple[bool, str]
Load and verify the circuit input parameter.
- Parameters:
toml_dict (dict[str, Any]) – dictionary with circuit configuration
is_tdb_to_update (bool) – True to update the transistor database
- Returns:
True, if the configuration was consistent and empty string or False and report of the issues
- Return type:
tuple[bool, str]
- load_and_verify_general_parameters(toml_dict: dict[str, Any]) tuple[bool, str]
Verify the input parameter ranges.
- Parameters:
toml_dict (dict[str, Any]) – toml general configuration
- Returns:
True, if the configuration was consistent and empty string or False and report of the issues
- Return type:
tuple[bool, str]
- static load_csv_to_df(csv_filepath: str) DataFrame
Load a csv file (previously stored from a Pandas DataFrame) back to a Pandas DataFrame.
- Parameters:
csv_filepath (str) – File path of .csv file
- Returns:
loaded results from the given .csv file
- Return type:
pandas.DataFrame
- static load_dab_dto_from_study(act_study_data: StudyData, dab_config: CircuitParetoDabDesign, trial_number: int | None = None) DabCircuitDTO
Load a DAB-DTO from an optuna study.
- Parameters:
act_study_data (StudyData) – Information about the circuit study name and study path
dab_config (circuit_dtos.CircuitParetoDabDesign) – DAB optimization configuration file
trial_number (int) – trial number to load to the DTO
- Returns:
DTO
- Return type:
d_dtos.DabCircuitDTO
- static load_stored_config(act_circuit_study_data: StudyData) CircuitParetoDabDesign
Load pickle configuration file from disk.
- Parameters:
act_circuit_study_data (StudyData) – Information about the circuit study name and study path
- Returns:
Configuration file as circuit_dtos.DabDesign
- Return type:
circuit_dtos.CircuitParetoDabDesign
- misc: float
- static plot_compare_waveforms(dto_directory: str) None
Compare calculated waveforms with simulated waveforms (GeckoCIRCUITS).
- Parameters:
dto_directory (str) – Folder of circuit DTOs to read the values from
- static plot_single_design_operating_points_from_dto(combination_dto: DabCircuitDTO, plot_results_path: str, combination_id: str, fig: Figure, ax: Axes) None
Generate plot outputs to show the operating points and compare the converters.
- Parameters:
combination_dto (DabCircuitDTO) – combination DTO
plot_results_path (str) – Path to store the result table
combination_id (int) – combination ID
fig (Figure) – matplotlib figure object
ax (Axes) – matplotlib axes object
- run_optimization_mysql(act_storage_url: str, act_number_trials: int) None
Proceed a study which is stored as sqlite database.
- Parameters:
act_storage_url (str) – url-Name of the database path
act_number_trials (int) – Number of trials adding to the existing study
- run_optimization_sqlite(act_number_trials: int) None
Proceed a study which is stored as sqlite database.
- Parameters:
act_number_trials (int) – Number of optimization trials
- save_config() None
Save the actual configuration file as pickle file on the disk.
- save_study_results_pareto(show_results: bool = False) None
Show the results of a study.
A local .html file is generated under config.working_directory to store the interactive plotly plots on disk.
- Parameters:
show_results (bool) – True to directly open the browser to show the study results.
- start_proceed_study(number_trials: int, database_type: str = 'sqlite', sampler: BaseSampler = <optuna.samplers._nsgaiii._sampler.NSGAIIISampler object>) None
Proceed a study which is stored as sqlite database.
- Parameters:
number_trials (int) – Number of trials adding to the existing study
database_type (str) – storage database, e.g. ‘sqlite’ or ‘mysql’
sampler (optuna.sampler-object) – optuna.samplers.NSGAIISampler() or optuna.samplers.NSGAIIISampler(). Note about the brackets () !! Default: NSGAIII
- static study_to_df(act_study_data: StudyData) DataFrame
Create a DataFrame from a study.
- Parameters:
act_study_data (StudyData) – Information about the circuit study name and study path
- Returns:
study result data transferred to Pandas dataframe
- Return type:
pd.DataFrame
- transistor_b1_cooling: ComponentCooling
- transistor_b2_cooling: ComponentCooling
- static visualize_all_lab_data(filepath: str) None
Generate plots or tables for the practical operation in the lab.
- Parameters:
filepath (str) – filepath
- static visualize_single_lab_data(filepath: str, combination_id: str) None
Generate plots or tables for the practical operation in the lab.
- Parameters:
filepath (str) – filepath
combination_id (str) – combination ID of object to plot
- class dct.DataSource(*values)
Bases:
str,EnumSet the setup of the measurement.
- Custom = 'custom'
- Datasheet = 'datasheet'
- LEA_MTB = 'LEA_MTB'
- MagNet = 'MagNet'
- TDK_MDT = 'TDK_MDT'
- class dct.DctMainCtl
Bases:
objectMain class for control dab-optimization.
- check_breakpoint(break_point_key: str, info: str) None
Continue, wait for user input or stop the program according breakpoint configuration.
- Parameters:
break_point_key (str) – Breakpoint configuration keyword
info (str) – Information text displayed at this breakpoint (if program waits or stops).
- static delete_study_content(is_all_invalid: bool, optimization_directory: str, study_directory: str, sub_folder_list: list[str] | None = None) None
Delete the study files and the femmt folders.
If a new study is to generate the old obsolete files and folders needs to be deleted.
- :param is_all_invalidIndicates, if the complete folder content of optimization_directory is to delete
or only those on within the sub folders
:type is_all_invalid : bool :param optimization_directory : Path to optimization folder :type optimization_directory : str :param study_directory : Name of the study folders :type study_directory : str :param sub_folder_list : Path to study directory within the optimization folder :type sub_folder_list : list[str]
- generate_conf_file(path: str) bool
Create and save the configuration file.
Generate following default configuration files within the path: DabCircuitConf.toml, DabInductorConf.toml, DabTransformerConf.toml and DabHeatSinkConf.toml,
:param path : Location of the configuration :type path : str :return: true, if the files are stored successfully :rtype: bool
- static generate_zip_archive(toml_prog_flow: FlowControl) None
Generate a zip archive from the given simulation results to transfer to another computer.
Remove unnecessary file structure before performing the zip operation, e.g. the 00_femmt_simulation results directory.
- Parameters:
toml_prog_flow (tc.FlowControl) – Flow control toml file
- static get_initialization_queue_data(act_toml_prog_flow: FlowControl) tuple[list[ConfigurationDataEntryDto], list[MagneticDataEntryDto], list[ConfigurationDataEntryDto], list[MagneticDataEntryDto], list[ConfigurationDataEntryDto], list[ConfigurationDataEntryDto], list[SummaryDataEntryDto]]
Initialize the lists of configuration data.
- Parameters:
act_toml_prog_flow (tc.FlowControl) – Flow control toml file (reference)
- Returns:
List of configuration data for data transfer: circuit, transformer, inductor, heat sink and summary. Each configuration gets one entry of the list.
- Return type:
list[ConfigurationDataEntryDto], list[srv_ctl_dtos.MagneticDataEntryDto], list[ConfigurationDataEntryDto], list[srv_ctl_dtos.MagneticDataEntryDto], list[ConfigurationDataEntryDto], list[ConfigurationDataEntryDto], list[ConfigurationDataEntryDto], list[SummaryDataEntryDto]
- static get_number_of_pkl_files(filtered_file_path: str) int
Count the number of files with extension ‘pkl’.
If the optimization is skipped the number of filtered points reflected by the number of pkl-files needs to be count for status information.
- Parameters:
filtered_file_path (str) – drive location path to the ‘pkl’-file folder
- Returns:
Number of pkl-files within the folder corresponds to number of filtered operation points
- Return type:
int
- static load_generate_logging_config(logging_config_file: str) None
Read the logging configuration file and configure the logger.
Generate a default logging configuration file in case it does not exist.
- Parameters:
logging_config_file (str) – File name of the logging configuration file
- static load_toml_file(toml_file: str) tuple[bool, dict[str, Any]]
Load the toml configuration data to a dictionary.
:param toml_file : File name of the toml-file :type toml_file : str :return: True, if the data could be loaded successful and the loaded dictionary :rtype: bool, dict
- static log_software_versions(filepath: str) None
Log the software versions of selected packages used to generate the results.
- Parameters:
filepath (str) – file path and file name of the logging file
- run_optimization_from_toml_configurations(workspace_path: str) None
Perform the main program.
This function corresponds to ‘main’, which is called after the instance of the class are created.
- Parameters:
workspace_path (str) – Path to subfolder ‘workspace’ (if empty default path ‘../<path to this file>’ is used)
- static set_up_folder_structure(toml_prog_flow: FlowControl) None
Set up the folder structure for the subprojects.
- Parameters:
toml_prog_flow (tc.FlowControl) – Flow control toml file
- user_input_break_point(break_point_key: str, info: str) None
Continue, wait for user input or stop the program according breakpoint configuration.
- Parameters:
break_point_key (str) – Breakpoint configuration keyword
info (str) – Information text displayed at this breakpoint (if program waits or stops).
- class dct.DctServer
Bases:
objectServer to visualize the actual progress and calculated Pareto-fronts.
- async static admin_page(request: Request, username: str = Depends(dependency=<staticmethod(<function DctServer.get_current_user>)>, use_cache=True, scope=None)) _TemplateResponse | RedirectResponse
Evaluate the permission of user and return the suitable page.
If the form send by ‘@app.get(“/login”’ send back this method is called. It verify the username and password and provide the suitable evaluation result. :param request: Request information of the client request :type request: Request :param username: Name of the user :type username: str :return: html-page :rtype: _TemplateResponse | RedirectResponse
- app = <fastapi.applications.FastAPI object>
- break_status: int = 0
- async static control_page(request: Request, action: str = '', url_back: str = '/html_homepage1') _TemplateResponse | HTMLResponse | RedirectResponse
Provide the html-information based on client request to control_page.
- Parameters:
request (Request) – Request information of the client request
action (str) – Information about the requested action (Keyword driven)
url_back (str) – Uniform resource locator for jump back
- Returns:
html-page
- Return type:
_TemplateResponse
- static dct_server_thread() None
Start the FastAPI-server.
- static get_circuit_table_data(circuit_data: CircuitConfigurationDataDto) dict
Fill the table data for display circuit progress data of one configuration with filtered point name.
- Parameters:
circuit_data (server_ctl_dtos.CircuitConfigurationDataDto) – Configuration data of circuit configuration for progress reporting
- Returns:
Formatted entries of circuit configuration data for progress reporting
- Return type:
dict
- static get_current_user(request: Request) Any
Provide the user of the current session.
User of the current session in case of valid login
- static get_format_time(time_value: float) str
Create the information string based on the input parameters.
The displayed time value is displayed in human understandable way. Depending on thresholds the time is displayed in different way. With the input parameter the information string is generated. :param time_value: time value in second :type time_value: float :return: formatted time value to match the display area :rtype: str
- static get_heat_sink_table_data(act_heat_sink_data_list: list[ConfigurationDataEntryDto]) list[dict]
Fill the table data to display progress based on the configuration progress data.
- Parameters:
act_heat_sink_data_list (list[server_ctl_dtos.ConfigurationDataEntryDto]) – List of configuration data for progress reporting
- Returns:
List of dict with the formatted entries
- Return type:
list[dict]
- static get_magnetic_table_data(magnetic_data_list: list[MagneticDataEntryDto]) list[dict]
Fill the table data for display magnetic progress data of one configuration with filtered point name.
- Parameters:
magnetic_data_list (list[server_ctl_dtos.MagneticDataEntryDto]) – Configuration data of magnetic configuration for progress reporting (inductor or transformer)
- Returns:
List of formatted entries for progress reporting
- Return type:
list[dict]
- static get_pareto_front(request: Request, button_index: int | None, table_index: int | None, url_back: str = '') HTMLResponse
Provide the Pareto-front.
Later to replace by the selected Pareto-front :param request: Request information of the client request :type request: Request :param button_index: Index of selected button, if a button was pressed :type button_index: int :param table_index: Index of selected table in case of a button press :type table_index: int :param url_back: Uniform resource locator for jump back :type url_back: str :return: html-page :rtype: HTMLResponse
- static get_summary_table_data(act_summary_data_list: list[SummaryDataEntryDto]) list[dict]
Fill the table data to display summary progress based on the configuration progress data.
- Parameters:
act_summary_data_list (list[server_ctl_dtos.SummaryDataEntryDto]) – List of configuration data for progress reporting
- Returns:
List of dict with the formatted entries
- Return type:
list[dict]
- static get_table_data(component_data_list: list[ConfigurationDataEntryDto]) list[dict]
Fill the table data to display progress based on the configuration progress data.
- Parameters:
component_data_list (list[server_ctl_dtos.ConfigurationDataEntryDto]) – List of configuration data for progress reporting
- Returns:
List of dict with the formatted entries
- Return type:
list[dict]
- icon = ['StyleSheets/OptIdle.png', 'StyleSheets/OptInProgress.png', 'StyleSheets/OptDone.png', 'StyleSheets/OptSkipped.png']
- static load_optuna_html_file(filepath: str) str
Load the optuna file to string.
!!!Later to replace :param filepath: File name inclusive path :type filepath: str :return: file data as string :rtype: str
- async static login(request: Request, username: str = Form(PydanticUndefined), password: str = Form(PydanticUndefined)) _TemplateResponse | RedirectResponse
Evaluate the login data and create a session.
If the form send by ‘@app.get(“/login”’ send back this method is called. It verify the username and password and provide the suitable evaluation result. :param request: Request information of the client request :type request: Request :param username: Name of the user :type username: str :param password: password :type password: str :return: html-page :rtype: _TemplateResponse | RedirectResponse
- async static login_page(request: Request) _TemplateResponse
Provide the html-information based on client request to login_page.
- Parameters:
request (Request) – Request information of the client request
- Returns:
html-page
- Return type:
_TemplateResponse
- async static main_page1(request: Request, action: str = '', user: str = Depends(dependency=<staticmethod(<function DctServer.get_current_user>)>, use_cache=True, scope=None), button_index: int | None = None, table_index: int | None = None) _TemplateResponse | HTMLResponse
Provide the html-information based on client request to html_homepage1.
- Parameters:
request (Request) – Request information of the client request
action (str) – Information about the requested action (Keyword driven)
user (str) – User, in case of valid user
button_index (int) – Index of selected button, if a button was pressed
table_index (int) – Index of selected table in case of a button press
- Returns:
html-page
- Return type:
_TemplateResponse | HTMLResponse
- async static main_page2(request: Request, action: str = '', c_selected_filtered_point_index: int = -1, user: str | None = Depends(dependency=<staticmethod(<function DctServer.get_current_user>)>, use_cache=True, scope=None), button_index: int | None = None, table_index: int | None = None) _TemplateResponse | HTMLResponse
Provide the html-information based on client request to html_homepage2.
- Parameters:
request (Request) – Request information of the client request
action (str) – Information about the requested action (Keyword driven)
c_selected_filtered_point_index (int) – Index of the selected circuit filtered point
user (str) – User, in case of valid user
button_index (int) – Index of selected button, if a button was pressed
table_index (int) – Index of selected table in case of a button press
- Returns:
html-page
- Return type:
_TemplateResponse | HTMLResponse
- req_stop = <Synchronized wrapper for c_int(0)>
- server_object: Server
- server_request_queue: Queue
- server_response_queue: Queue
- server_thread: Thread
- static start_dct_server(act_server_request_queue: Queue, act_server_response_queue: Queue, program_exit_flag: bool) None
Start the server to control and supervise simulation.
- Parameters:
act_server_request_queue (Queue) – Queue object to request data from main process
act_server_response_queue (Queue) – Queue object to responds to server process
program_exit_flag (boolean) – Flag, which indicates to terminate the program on request
- status_message = 'Wait for button press!'
- static stop_dct_server() None
Stop the server for the control and supervision of the simulation.
- stop_flag = <Synchronized wrapper for c_int(0)>
- templates = <starlette.templating.Jinja2Templates object>
- users = {'Andi': 'hallo'}
- class dct.Debug(*, general: DebugGeneral, circuit: DebugCircuit, capacitor: DebugCapacitor, inductor: DebugInductor, transformer: DebugTransformer)
Bases:
BaseModelGeneral information in debug configuration.
- capacitor: DebugCapacitor
- circuit: DebugCircuit
- general: DebugGeneral
- inductor: DebugInductor
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- transformer: DebugTransformer
- class dct.DebugCapacitor(*, number_working_point_max: int)
Bases:
BaseModelDebug information for the capacitor.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- number_working_point_max: int
- class dct.DebugCircuit(*, is_waveform_validation: bool)
Bases:
BaseModelDebug information for the circuit.
- is_waveform_validation: bool
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class dct.DebugGeneral(*, is_debug: bool)
Bases:
BaseModelDebug mode general information.
- is_debug: bool
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class dct.DebugInductor(*, number_reluctance_working_point_max: int, number_fem_working_point_max: int)
Bases:
BaseModelDebug information for the inductor.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- number_fem_working_point_max: int
- number_reluctance_working_point_max: int
- class dct.DebugTransformer(*, number_reluctance_working_point_max: int, number_fem_working_point_max: int)
Bases:
BaseModelDebug information for the transformer.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- number_fem_working_point_max: int
- number_reluctance_working_point_max: int
- dct.Depends(dependency: Annotated[Callable[[...], Any] | None, Doc('\n A "dependable" callable (like a function).\n\n Don\'t call it directly, FastAPI will call it for you, just pass the object\n directly.\n\n Read more about it in the\n [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/)\n ')] = None, *, use_cache: Annotated[bool, Doc('\n By default, after a dependency is called the first time in a request, if\n the dependency is declared again for the rest of the request (for example\n if the dependency is needed by several dependencies), the value will be\n re-used for the rest of the request.\n\n Set `use_cache` to `False` to disable this behavior and ensure the\n dependency is called again (if declared more than once) in the same request.\n\n Read more about it in the\n [FastAPI docs about sub-dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/sub-dependencies/#using-the-same-dependency-multiple-times)\n ')] = True, scope: Annotated[Literal['function', 'request'] | None, Doc('\n Mainly for dependencies with `yield`, define when the dependency function\n should start (the code before `yield`) and when it should end (the code\n after `yield`).\n\n * `"function"`: start the dependency before the *path operation function*\n that handles the request, end the dependency after the *path operation\n function* ends, but **before** the response is sent back to the client.\n So, the dependency function will be executed **around** the *path operation\n **function***.\n * `"request"`: start the dependency before the *path operation function*\n that handles the request (similar to when using `"function"`), but end\n **after** the response is sent back to the client. So, the dependency\n function will be executed **around** the **request** and response cycle.\n\n Read more about it in the\n [FastAPI docs for FastAPI Dependencies with yield](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#early-exit-and-scope)\n ')] = None) Any
Declare a FastAPI dependency.
It takes a single “dependable” callable (like a function).
Don’t call it directly, FastAPI will call it for you.
Read more about it in the [FastAPI docs for Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/).
Example
```python from typing import Annotated
from fastapi import Depends, FastAPI
app = FastAPI()
- async def common_parameters(q: str | None = None, skip: int = 0, limit: int = 100):
return {“q”: q, “skip”: skip, “limit”: limit}
@app.get(“/items/”) async def read_items(commons: Annotated[dict, Depends(common_parameters)]):
return commons
- class dct.DesscaModel(box_constraints, bandwidth=0.1, reference_pdf=None, render_online=False, pso_options=None, state_names=None, buffer_size=None, disc_resolution=None, epsilon=1e-05)
Bases:
object- downsample(data, target_size)
- plot_heatmap(resolution=100, **kwargs)
- plot_scatter(scatter_kwargs=None)
- render_scatter(online_data=None)
- sample_optimally()
- update_and_sample(data=None)
- update_coverage_pdf(data)
- class dct.Enum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
objectCreate a collection of name/value pairs.
Example enumeration:
>>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3
Access them by:
attribute access:
>>> Color.RED <Color.RED: 1>
value lookup:
>>> Color(1) <Color.RED: 1>
name lookup:
>>> Color['RED'] <Color.RED: 1>
Enumerations can be iterated over, and know how many members they have:
>>> len(Color) 3
>>> list(Color) [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 3>]
Methods can be added to enumerations, and members can have their own attributes – see the documentation for details.
- class dct.FastAPI(*, debug: ~typing.Annotated[bool, Doc('\n Boolean indicating if debug tracebacks should be returned on server\n errors.\n\n Read more in the\n [Starlette docs for Applications](https://www.starlette.dev/applications/#instantiating-the-application).\n ')] = False, routes: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n **Note**: you probably shouldn't use this parameter, it is inherited\n from Starlette and supported for compatibility.\n\n ---\n\n A list of routes to serve incoming HTTP and WebSocket requests.\n "), <typing_extensions.deprecated object at 0x7f4517944f20>] = None, title: ~typing.Annotated[str, Doc('\n The title of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(title="ChimichangApp")\n ```\n ')] = 'FastAPI', summary: ~typing.Annotated[str | None, Doc('\n A short summary of the API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(summary="Deadpond\'s favorite app. Nuff said.")\n ```\n ')] = None, description: ~typing.Annotated[str, Doc('\n A description of the API. Supports Markdown (using\n [CommonMark syntax](https://commonmark.org/)).\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n description="""\n ChimichangApp API helps you do awesome stuff. 🚀\n\n ## Items\n\n You can **read items**.\n\n ## Users\n\n You will be able to:\n\n * **Create users** (_not implemented_).\n * **Read users** (_not implemented_).\n\n """\n )\n ```\n ')] = '', version: ~typing.Annotated[str, Doc('\n The version of the API.\n\n **Note** This is the version of your application, not the version of\n the OpenAPI specification nor the version of FastAPI being used.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(version="0.0.1")\n ```\n ')] = '0.1.0', openapi_url: ~typing.Annotated[str | None, Doc('\n The URL where the OpenAPI schema will be served from.\n\n If you set it to `None`, no OpenAPI schema will be served publicly, and\n the default automatic endpoints `/docs` and `/redoc` will also be\n disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#openapi-url).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(openapi_url="/api/v1/openapi.json")\n ```\n ')] = '/openapi.json', openapi_tags: ~typing.Annotated[list[dict[str, ~typing.Any]] | None, Doc('\n A list of tags used by OpenAPI, these are the same `tags` you can set\n in the *path operations*, like:\n\n * `@app.get("/users/", tags=["users"])`\n * `@app.get("/items/", tags=["items"])`\n\n The order of the tags can be used to specify the order shown in\n tools like Swagger UI, used in the automatic path `/docs`.\n\n It\'s not required to specify all the tags used.\n\n The tags that are not declared MAY be organized randomly or based\n on the tools\' logic. Each tag name in the list MUST be unique.\n\n The value of each item is a `dict` containing:\n\n * `name`: The name of the tag.\n * `description`: A short description of the tag.\n [CommonMark syntax](https://commonmark.org/) MAY be used for rich\n text representation.\n * `externalDocs`: Additional external documentation for this tag. If\n provided, it would contain a `dict` with:\n * `description`: A short description of the target documentation.\n [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `url`: The URL for the target documentation. Value MUST be in\n the form of a URL.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-tags).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n tags_metadata = [\n {\n "name": "users",\n "description": "Operations with users. The **login** logic is also here.",\n },\n {\n "name": "items",\n "description": "Manage items. So _fancy_ they have their own docs.",\n "externalDocs": {\n "description": "Items external docs",\n "url": "https://fastapi.tiangolo.com/",\n },\n },\n ]\n\n app = FastAPI(openapi_tags=tags_metadata)\n ```\n ')] = None, servers: ~typing.Annotated[list[dict[str, str | ~typing.Any]] | None, Doc('\n A `list` of `dict`s with connectivity information to a target server.\n\n You would use it, for example, if your application is served from\n different domains and you want to use the same Swagger UI in the\n browser to interact with each of them (instead of having multiple\n browser tabs open). Or if you want to leave fixed the possible URLs.\n\n If the servers `list` is not provided, or is an empty `list`, the\n `servers` property in the generated OpenAPI will be:\n\n * a `dict` with a `url` value of the application\'s mounting point\n (`root_path`) if it\'s different from `/`.\n * otherwise, the `servers` property will be omitted from the OpenAPI\n schema.\n\n Each item in the `list` is a `dict` containing:\n\n * `url`: A URL to the target host. This URL supports Server Variables\n and MAY be relative, to indicate that the host location is relative\n to the location where the OpenAPI document is being served. Variable\n substitutions will be made when a variable is named in `{`brackets`}`.\n * `description`: An optional string describing the host designated by\n the URL. [CommonMark syntax](https://commonmark.org/) MAY be used for\n rich text representation.\n * `variables`: A `dict` between a variable name and its value. The value\n is used for substitution in the server\'s URL template.\n\n Read more in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#additional-servers).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(\n servers=[\n {"url": "https://stag.example.com", "description": "Staging environment"},\n {"url": "https://prod.example.com", "description": "Production environment"},\n ]\n )\n ```\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of global dependencies, they will be applied to each\n *path operation*, including in sub-routers.\n\n Read more about it in the\n [FastAPI docs for Global Dependencies](https://fastapi.tiangolo.com/tutorial/dependencies/global-dependencies/).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import func_dep_1, func_dep_2\n\n app = FastAPI(dependencies=[Depends(func_dep_1), Depends(func_dep_2)])\n ```\n ')] = None, default_response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n The default response class to be used.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n app = FastAPI(default_response_class=ORJSONResponse)\n ```\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, redirect_slashes: ~typing.Annotated[bool, Doc('\n Whether to detect and redirect slashes in URLs when the client doesn\'t\n use the same format.\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(redirect_slashes=True) # the default\n\n @app.get("/items/")\n async def read_items():\n return [{"item_id": "Foo"}]\n ```\n\n With this app, if a client goes to `/items` (without a trailing slash),\n they will be automatically redirected with an HTTP status code of 307\n to `/items/`.\n ')] = True, docs_url: ~typing.Annotated[str | None, Doc('\n The path to the automatic interactive API documentation.\n It is handled in the browser by Swagger UI.\n\n The default URL is `/docs`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url=None)\n ```\n ')] = '/docs', redoc_url: ~typing.Annotated[str | None, Doc('\n The path to the alternative automatic interactive API documentation\n provided by ReDoc.\n\n The default URL is `/redoc`. You can disable it by setting it to `None`.\n\n If `openapi_url` is set to `None`, this will be automatically disabled.\n\n Read more in the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#docs-urls).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(docs_url="/documentation", redoc_url="redocumentation")\n ```\n ')] = '/redoc', swagger_ui_oauth2_redirect_url: ~typing.Annotated[str | None, Doc('\n The OAuth2 redirect endpoint for the Swagger UI.\n\n By default it is `/docs/oauth2-redirect`.\n\n This is only used if you use OAuth2 (with the "Authorize" button)\n with Swagger UI.\n ')] = '/docs/oauth2-redirect', swagger_ui_init_oauth: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n OAuth2 configuration for the Swagger UI, by default shown at `/docs`.\n\n Read more about the available configuration options in the\n [Swagger UI docs](https://swagger.io/docs/open-source-tools/swagger-ui/usage/oauth2/).\n ')] = None, middleware: ~typing.Annotated[~collections.abc.Sequence[~starlette.middleware.Middleware] | None, Doc('\n List of middleware to be added when creating the application.\n\n In FastAPI you would normally do this with `app.add_middleware()`\n instead.\n\n Read more in the\n [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).\n ')] = None, exception_handlers: ~typing.Annotated[dict[int | type[Exception], ~collections.abc.Callable[[~starlette.requests.Request, ~typing.Any], ~collections.abc.Coroutine[~typing.Any, ~typing.Any, ~starlette.responses.Response]]] | None, Doc('\n A dictionary with handlers for exceptions.\n\n In FastAPI, you would normally use the decorator\n `@app.exception_handler()`.\n\n Read more in the\n [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).\n ')] = None, on_startup: ~typing.Annotated[~collections.abc.Sequence[~collections.abc.Callable[[], ~typing.Any]] | None, Doc('\n A list of startup event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, on_shutdown: ~typing.Annotated[~collections.abc.Sequence[~collections.abc.Callable[[], ~typing.Any]] | None, Doc('\n A list of shutdown event handler functions.\n\n You should instead use the `lifespan` handlers.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, lifespan: ~typing.Annotated[~collections.abc.Callable[[~fastapi.applications.AppType], ~contextlib.AbstractAsyncContextManager[None]] | ~collections.abc.Callable[[~fastapi.applications.AppType], ~contextlib.AbstractAsyncContextManager[~collections.abc.Mapping[str, ~typing.Any]]] | None, Doc('\n A `Lifespan` context manager handler. This replaces `startup` and\n `shutdown` functions with a single context manager.\n\n Read more in the\n [FastAPI docs for `lifespan`](https://fastapi.tiangolo.com/advanced/events/).\n ')] = None, terms_of_service: ~typing.Annotated[str | None, Doc('\n A URL to the Terms of Service for your API.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(terms_of_service="http://example.com/terms/")\n ```\n ')] = None, contact: ~typing.Annotated[dict[str, str | ~typing.Any] | None, Doc('\n A dictionary with the contact information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) The name of the contact person/organization.\n * `url`: (`str`) A URL pointing to the contact information. MUST be in\n the format of a URL.\n * `email`: (`str`) The email address of the contact person/organization.\n MUST be in the format of an email address.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n contact={\n "name": "Deadpoolio the Amazing",\n "url": "http://x-force.example.com/contact/",\n "email": "dp@x-force.example.com",\n }\n )\n ```\n ')] = None, license_info: ~typing.Annotated[dict[str, str | ~typing.Any] | None, Doc('\n A dictionary with the license information for the exposed API.\n\n It can contain several fields.\n\n * `name`: (`str`) **REQUIRED** (if a `license_info` is set). The\n license name used for the API.\n * `identifier`: (`str`) An [SPDX](https://spdx.dev/) license expression\n for the API. The `identifier` field is mutually exclusive of the `url`\n field. Available since OpenAPI 3.1.0, FastAPI 0.99.0.\n * `url`: (`str`) A URL to the license used for the API. This MUST be\n the format of a URL.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more at the\n [FastAPI docs for Metadata and Docs URLs](https://fastapi.tiangolo.com/tutorial/metadata/#metadata-for-api).\n\n **Example**\n\n ```python\n app = FastAPI(\n license_info={\n "name": "Apache 2.0",\n "url": "https://www.apache.org/licenses/LICENSE-2.0.html",\n }\n )\n ```\n ')] = None, openapi_prefix: ~typing.Annotated[str, Doc('\n A URL prefix for the OpenAPI URL.\n '), <typing_extensions.deprecated object at 0x7f45179464b0>] = '', root_path: ~typing.Annotated[str, Doc('\n A path prefix handled by a proxy that is not seen by the application\n but is seen by external clients, which affects things like Swagger UI.\n\n Read more about it at the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path="/api/v1")\n ```\n ')] = '', root_path_in_servers: ~typing.Annotated[bool, Doc('\n To disable automatically generating the URLs in the `servers` field\n in the autogenerated OpenAPI using the `root_path`.\n\n Read more about it in the\n [FastAPI docs for Behind a Proxy](https://fastapi.tiangolo.com/advanced/behind-a-proxy/#disable-automatic-server-from-root-path).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n app = FastAPI(root_path_in_servers=False)\n ```\n ')] = True, responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc('\n OpenAPI callbacks that should apply to all *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ')] = None, webhooks: ~typing.Annotated[~fastapi.routing.APIRouter | None, Doc("\n Add OpenAPI webhooks. This is similar to `callbacks` but it doesn't\n depend on specific *path operations*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Note**: This is available since OpenAPI 3.1.0, FastAPI 0.99.0.\n\n Read more about it in the\n [FastAPI docs for OpenAPI Webhooks](https://fastapi.tiangolo.com/advanced/openapi-webhooks/).\n ")] = None, deprecated: ~typing.Annotated[bool | None, Doc("\n Mark all *path operations* as deprecated. You probably don't need it,\n but it's available.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#deprecate-a-path-operation).\n ")] = None, include_in_schema: ~typing.Annotated[bool, Doc("\n To include (or not) all the *path operations* in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ")] = True, swagger_ui_parameters: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Parameters to configure Swagger UI, the autogenerated interactive API\n documentation (by default at `/docs`).\n\n Read more about it in the\n [FastAPI docs about how to Configure Swagger UI](https://fastapi.tiangolo.com/how-to/configure-swagger-ui/).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, separate_input_output_schemas: ~typing.Annotated[bool, Doc("\n Whether to generate separate OpenAPI schemas for request body and\n response body when the results would be more precise.\n\n This is particularly useful when automatically generating clients.\n\n For example, if you have a model like:\n\n ```python\n from pydantic import BaseModel\n\n class Item(BaseModel):\n name: str\n tags: list[str] = []\n ```\n\n When `Item` is used for input, a request body, `tags` is not required,\n the client doesn't have to provide it.\n\n But when using `Item` for output, for a response body, `tags` is always\n available because it has a default value, even if it's just an empty\n list. So, the client should be able to always expect it.\n\n In this case, there would be two different schemas, one for input and\n another one for output.\n\n Read more about it in the\n [FastAPI docs about how to separate schemas for input and output](https://fastapi.tiangolo.com/how-to/separate-openapi-schemas)\n ")] = True, openapi_external_docs: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n This field allows you to provide additional external documentation links.\n If provided, it must be a dictionary containing:\n\n * `description`: A brief description of the external documentation.\n * `url`: The URL pointing to the external documentation. The value **MUST**\n be a valid URL format.\n\n **Example**:\n\n ```python\n from fastapi import FastAPI\n\n external_docs = {\n "description": "Detailed API Reference",\n "url": "https://example.com/api-docs",\n }\n\n app = FastAPI(openapi_external_docs=external_docs)\n ```\n ')] = None, strict_content_type: ~typing.Annotated[bool, Doc("\n Enable strict checking for request Content-Type headers.\n\n When `True` (the default), requests with a body that do not include\n a `Content-Type` header will **not** be parsed as JSON.\n\n This prevents potential cross-site request forgery (CSRF) attacks\n that exploit the browser's ability to send requests without a\n Content-Type header, bypassing CORS preflight checks. In particular\n applicable for apps that need to be run locally (in localhost).\n\n When `False`, requests without a `Content-Type` header will have\n their body parsed as JSON, which maintains compatibility with\n certain clients that don't send `Content-Type` headers.\n\n Read more about it in the\n [FastAPI docs for Strict Content-Type](https://fastapi.tiangolo.com/advanced/strict-content-type/).\n ")] = True, **extra: ~typing.Annotated[~typing.Any, Doc('\n Extra keyword arguments to be stored in the app, not used by FastAPI\n anywhere.\n ')])
Bases:
StarletteFastAPI app class, the main entrypoint to use FastAPI.
Read more in the [FastAPI docs for First Steps](https://fastapi.tiangolo.com/tutorial/first-steps/).
## Example
```python from fastapi import FastAPI
- add_api_route(path: str, endpoint: ~collections.abc.Callable[[...], ~typing.Any], *, response_model: ~typing.Any = <fastapi.datastructures.DefaultPlaceholder object>, status_code: int | None = None, tags: list[str | ~enum.Enum] | None = None, dependencies: ~collections.abc.Sequence[~fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, ~typing.Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None = None, response_model_exclude: set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None = 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 = <fastapi.datastructures.DefaultPlaceholder object>, name: str | None = None, openapi_extra: dict[str, ~typing.Any] | None = None, generate_unique_id_function: ~collections.abc.Callable[[~fastapi.routing.APIRoute], str] = <fastapi.datastructures.DefaultPlaceholder object>) None
- add_api_websocket_route(path: str, endpoint: Callable[[...], Any], name: str | None = None, *, dependencies: Sequence[Depends] | None = None) None
- api_route(path: str, *, response_model: ~typing.Any = <fastapi.datastructures.DefaultPlaceholder object>, status_code: int | None = None, tags: list[str | ~enum.Enum] | None = None, dependencies: ~collections.abc.Sequence[~fastapi.params.Depends] | None = None, summary: str | None = None, description: str | None = None, response_description: str = 'Successful Response', responses: dict[int | str, dict[str, ~typing.Any]] | None = None, deprecated: bool | None = None, methods: list[str] | None = None, operation_id: str | None = None, response_model_include: set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None = None, response_model_exclude: set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None = 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>, name: str | None = None, openapi_extra: dict[str, ~typing.Any] | None = None, generate_unique_id_function: ~collections.abc.Callable[[~fastapi.routing.APIRoute], str] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
- build_middleware_stack() Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]]
- delete(path: ~typing.Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: ~typing.Annotated[~typing.Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, status_code: ~typing.Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: ~typing.Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: ~typing.Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: ~typing.Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: ~typing.Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, name: ~typing.Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
Add a path operation using an HTTP DELETE operation.
## Example
```python from fastapi import FastAPI
app = FastAPI()
@app.delete(“/items/{item_id}”) def delete_item(item_id: str):
return {“message”: “Item deleted”}
- exception_handler(exc_class_or_status_code: Annotated[int | type[Exception], Doc('\n The Exception class this would handle, or a status code.\n ')]) Callable[[DecoratedCallable], DecoratedCallable]
Add an exception handler to the app.
Read more about it in the [FastAPI docs for Handling Errors](https://fastapi.tiangolo.com/tutorial/handling-errors/).
## Example
```python from fastapi import FastAPI, Request from fastapi.responses import JSONResponse
- class UnicornException(Exception):
- def __init__(self, name: str):
self.name = name
app = FastAPI()
@app.exception_handler(UnicornException) async def unicorn_exception_handler(request: Request, exc: UnicornException):
- return JSONResponse(
status_code=418, content={“message”: f”Oops! {exc.name} did something. There goes a rainbow…”},
)
- get(path: ~typing.Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: ~typing.Annotated[~typing.Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, status_code: ~typing.Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: ~typing.Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: ~typing.Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: ~typing.Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: ~typing.Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, name: ~typing.Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
Add a path operation using an HTTP GET operation.
## Example
```python from fastapi import FastAPI
app = FastAPI()
@app.get(“/items/”) def read_items():
return [{“name”: “Empanada”}, {“name”: “Arepa”}]
- head(path: ~typing.Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: ~typing.Annotated[~typing.Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, status_code: ~typing.Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: ~typing.Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: ~typing.Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: ~typing.Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: ~typing.Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, name: ~typing.Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
Add a path operation using an HTTP HEAD operation.
## Example
```python from fastapi import FastAPI, Response
app = FastAPI()
@app.head(“/items/”, status_code=204) def get_items_headers(response: Response):
response.headers[“X-Cat-Dog”] = “Alone in the world”
- include_router(router: ~typing.Annotated[~fastapi.routing.APIRouter, Doc('The `APIRouter` to include.')], *, prefix: ~typing.Annotated[str, Doc('An optional path prefix for the router.')] = '', tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to all the *path operations* in this\n router.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to all the\n *path operations* in this router.\n\n Read more about it in the\n [FastAPI docs for Bigger Applications - Multiple Files](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n\n **Example**\n\n ```python\n from fastapi import Depends, FastAPI\n\n from .dependencies import get_token_header\n from .internal import admin\n\n app = FastAPI()\n\n app.include_router(\n admin.router,\n dependencies=[Depends(get_token_header)],\n )\n ```\n ')] = None, responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses to be shown in OpenAPI.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Additional Responses in OpenAPI](https://fastapi.tiangolo.com/advanced/additional-responses/).\n\n And in the\n [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/#include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark all the *path operations* in this router as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n deprecated=True,\n )\n ```\n ')] = None, include_in_schema: ~typing.Annotated[bool, Doc('\n Include (or not) all the *path operations* in this router in the\n generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n include_in_schema=False,\n )\n ```\n ')] = True, default_response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Default response class to be used for the *path operations* in this\n router.\n\n Read more in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#default-response-class).\n\n **Example**\n\n ```python\n from fastapi import FastAPI\n from fastapi.responses import ORJSONResponse\n\n from .internal import old_api\n\n app = FastAPI()\n\n app.include_router(\n old_api.router,\n default_response_class=ORJSONResponse,\n )\n ```\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) None
Include an APIRouter in the same app.
Read more about it in the [FastAPI docs for Bigger Applications](https://fastapi.tiangolo.com/tutorial/bigger-applications/).
## Example
```python from fastapi import FastAPI
from .users import users_router
app = FastAPI()
- middleware(middleware_type: Annotated[str, Doc('\n The type of middleware. Currently only supports `http`.\n ')]) Callable[[DecoratedCallable], DecoratedCallable]
Add a middleware to the application.
Read more about it in the [FastAPI docs for Middleware](https://fastapi.tiangolo.com/tutorial/middleware/).
## Example
```python import time from typing import Awaitable, Callable
from fastapi import FastAPI, Request, Response
app = FastAPI()
@app.middleware(“http”) async def add_process_time_header(
request: Request, call_next: Callable[[Request], Awaitable[Response]]
- ) -> Response:
start_time = time.time() response = await call_next(request) process_time = time.time() - start_time response.headers[“X-Process-Time”] = str(process_time) return response
- on_event(event_type: Annotated[str, Doc('\n The type of event. `startup` or `shutdown`.\n ')]) Callable[[DecoratedCallable], DecoratedCallable]
Add an event handler for the application.
on_event is deprecated, use lifespan event handlers instead.
Read more about it in the [FastAPI docs for Lifespan Events](https://fastapi.tiangolo.com/advanced/events/#alternative-events-deprecated).
- openapi() dict[str, Any]
Generate the OpenAPI schema of the application. This is called by FastAPI internally.
The first time it is called it stores the result in the attribute app.openapi_schema, and next times it is called, it just returns that same result. To avoid the cost of generating the schema every time.
If you need to modify the generated OpenAPI schema, you could modify it.
Read more in the [FastAPI docs for OpenAPI](https://fastapi.tiangolo.com/how-to/extending-openapi/).
- options(path: ~typing.Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: ~typing.Annotated[~typing.Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, status_code: ~typing.Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: ~typing.Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: ~typing.Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: ~typing.Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: ~typing.Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, name: ~typing.Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
Add a path operation using an HTTP OPTIONS operation.
## Example
```python from fastapi import FastAPI
app = FastAPI()
@app.options(“/items/”) def get_item_options():
return {“additions”: [“Aji”, “Guacamole”]}
- patch(path: ~typing.Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: ~typing.Annotated[~typing.Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, status_code: ~typing.Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: ~typing.Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: ~typing.Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: ~typing.Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: ~typing.Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, name: ~typing.Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
Add a path operation using an HTTP PATCH operation.
## Example
```python from fastapi import FastAPI from pydantic import BaseModel
- class Item(BaseModel):
name: str description: str | None = None
app = FastAPI()
@app.patch(“/items/”) def update_item(item: Item):
return {“message”: “Item updated in place”}
- post(path: ~typing.Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: ~typing.Annotated[~typing.Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, status_code: ~typing.Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: ~typing.Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: ~typing.Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: ~typing.Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: ~typing.Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, name: ~typing.Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
Add a path operation using an HTTP POST operation.
## Example
```python from fastapi import FastAPI from pydantic import BaseModel
- class Item(BaseModel):
name: str description: str | None = None
app = FastAPI()
@app.post(“/items/”) def create_item(item: Item):
return {“message”: “Item created”}
- put(path: ~typing.Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: ~typing.Annotated[~typing.Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, status_code: ~typing.Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: ~typing.Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: ~typing.Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: ~typing.Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: ~typing.Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, name: ~typing.Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
Add a path operation using an HTTP PUT operation.
## Example
```python from fastapi import FastAPI from pydantic import BaseModel
- class Item(BaseModel):
name: str description: str | None = None
app = FastAPI()
@app.put(“/items/{item_id}”) def replace_item(item_id: str, item: Item):
return {“message”: “Item replaced”, “id”: item_id}
- setup() None
- trace(path: ~typing.Annotated[str, Doc('\n The URL path to be used for this *path operation*.\n\n For example, in `http://example.com/items`, the path is `/items`.\n ')], *, response_model: ~typing.Annotated[~typing.Any, Doc("\n The type to use for the response.\n\n It could be any valid Pydantic *field* type. So, it doesn't have to\n be a Pydantic model, it could be other things, like a `list`, `dict`,\n etc.\n\n It will be used for:\n\n * Documentation: the generated OpenAPI (and the UI at `/docs`) will\n show it as the response (JSON Schema).\n * Serialization: you could return an arbitrary object and the\n `response_model` would be used to serialize that object into the\n corresponding JSON.\n * Filtering: the JSON sent to the client will only contain the data\n (fields) defined in the `response_model`. If you returned an object\n that contains an attribute `password` but the `response_model` does\n not include that field, the JSON sent to the client would not have\n that `password`.\n * Validation: whatever you return will be serialized with the\n `response_model`, converting any data as necessary to generate the\n corresponding JSON. But if the data in the object returned is not\n valid, that would mean a violation of the contract with the client,\n so it's an error from the API developer. So, FastAPI will raise an\n error and return a 500 error code (Internal Server Error).\n\n Read more about it in the\n [FastAPI docs for Response Model](https://fastapi.tiangolo.com/tutorial/response-model/).\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, status_code: ~typing.Annotated[int | None, Doc('\n The default status code to be used for the response.\n\n You could override the status code by returning a response directly.\n\n Read more about it in the\n [FastAPI docs for Response Status Code](https://fastapi.tiangolo.com/tutorial/response-status-code/).\n ')] = None, tags: ~typing.Annotated[list[str | ~enum.Enum] | None, Doc('\n A list of tags to be applied to the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/#tags).\n ')] = None, dependencies: ~typing.Annotated[~collections.abc.Sequence[~fastapi.params.Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be applied to the\n *path operation*.\n\n Read more about it in the\n [FastAPI docs for Dependencies in path operation decorators](https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/).\n ')] = None, summary: ~typing.Annotated[str | None, Doc('\n A summary for the *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n A description for the *path operation*.\n\n If not provided, it will be extracted automatically from the docstring\n of the *path operation function*.\n\n It can contain Markdown.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Path Operation Configuration](https://fastapi.tiangolo.com/tutorial/path-operation-configuration/).\n ')] = None, response_description: ~typing.Annotated[str, Doc('\n The description for the default response.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = 'Successful Response', responses: ~typing.Annotated[dict[int | str, dict[str, ~typing.Any]] | None, Doc('\n Additional responses that could be returned by this *path operation*.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, deprecated: ~typing.Annotated[bool | None, Doc('\n Mark this *path operation* as deprecated.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, operation_id: ~typing.Annotated[str | None, Doc('\n Custom operation ID to be used by this *path operation*.\n\n By default, it is generated automatically.\n\n If you provide a custom operation ID, you need to make sure it is\n unique for the whole API.\n\n You can customize the\n operation ID generation with the parameter\n `generate_unique_id_function` in the `FastAPI` class.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = None, response_model_include: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to include only certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_exclude: ~typing.Annotated[set[int] | set[str] | ~collections.abc.Mapping[int, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | ~collections.abc.Mapping[str, set[int] | set[str] | ~collections.abc.Mapping[int, IncEx | bool] | ~collections.abc.Mapping[str, IncEx | bool] | bool] | None, Doc('\n Configuration passed to Pydantic to exclude certain fields in the\n response data.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = None, response_model_by_alias: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response model\n should be serialized by alias when an alias is used.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_include-and-response_model_exclude).\n ')] = True, response_model_exclude_unset: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that were not set and\n have their default values. This is different from\n `response_model_exclude_defaults` in that if the fields are set,\n they will be included in the response, even if the value is the same\n as the default.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_defaults: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data\n should have all the fields, including the ones that have the same value\n as the default. This is different from `response_model_exclude_unset`\n in that if the fields are set but contain the same default values,\n they will be excluded from the response.\n\n When `True`, default values are omitted from the response.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter).\n ')] = False, response_model_exclude_none: ~typing.Annotated[bool, Doc('\n Configuration passed to Pydantic to define if the response data should\n exclude fields set to `None`.\n\n This is much simpler (less smart) than `response_model_exclude_unset`\n and `response_model_exclude_defaults`. You probably want to use one of\n those two instead of this one, as those allow returning `None` values\n when it makes sense.\n\n Read more about it in the\n [FastAPI docs for Response Model - Return Type](https://fastapi.tiangolo.com/tutorial/response-model/#response_model_exclude_none).\n ')] = False, include_in_schema: ~typing.Annotated[bool, Doc('\n Include this *path operation* in the generated OpenAPI schema.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for Query Parameters and String Validations](https://fastapi.tiangolo.com/tutorial/query-params-str-validations/#exclude-parameters-from-openapi).\n ')] = True, response_class: ~typing.Annotated[type[~starlette.responses.Response], Doc('\n Response class to be used for this *path operation*.\n\n This will not be used if you return a response directly.\n\n Read more about it in the\n [FastAPI docs for Custom Response - HTML, Stream, File, others](https://fastapi.tiangolo.com/advanced/custom-response/#redirectresponse).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, name: ~typing.Annotated[str | None, Doc('\n Name for this *path operation*. Only used internally.\n ')] = None, callbacks: ~typing.Annotated[list[~starlette.routing.BaseRoute] | None, Doc("\n List of *path operations* that will be used as OpenAPI callbacks.\n\n This is only for OpenAPI documentation, the callbacks won't be used\n directly.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Read more about it in the\n [FastAPI docs for OpenAPI Callbacks](https://fastapi.tiangolo.com/advanced/openapi-callbacks/).\n ")] = None, openapi_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Extra metadata to be included in the OpenAPI schema for this *path\n operation*.\n\n Read more about it in the\n [FastAPI docs for Path Operation Advanced Configuration](https://fastapi.tiangolo.com/advanced/path-operation-advanced-configuration/#custom-openapi-path-operation-schema).\n ')] = None, generate_unique_id_function: ~typing.Annotated[~collections.abc.Callable[[~fastapi.routing.APIRoute], str], Doc('\n Customize the function used to generate unique IDs for the *path\n operations* shown in the generated OpenAPI.\n\n This is particularly useful when automatically generating clients or\n SDKs for your API.\n\n Read more about it in the\n [FastAPI docs about how to Generate Clients](https://fastapi.tiangolo.com/advanced/generate-clients/#custom-generate-unique-id-function).\n ')] = <fastapi.datastructures.DefaultPlaceholder object>) Callable[[DecoratedCallable], DecoratedCallable]
Add a path operation using an HTTP TRACE operation.
## Example
```python from fastapi import FastAPI
app = FastAPI()
@app.trace(“/items/{item_id}”) def trace_item(item_id: str):
return None
- websocket(path: Annotated[str, Doc('\n WebSocket path.\n ')], name: Annotated[str | None, Doc('\n A name for the WebSocket. Only used internally.\n ')] = None, *, dependencies: Annotated[Sequence[Depends] | None, Doc('\n A list of dependencies (using `Depends()`) to be used for this\n WebSocket.\n\n Read more about it in the\n [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).\n ')] = None) Callable[[DecoratedCallable], DecoratedCallable]
Decorate a WebSocket function.
Read more about it in the [FastAPI docs for WebSockets](https://fastapi.tiangolo.com/advanced/websockets/).
Example
```python from fastapi import FastAPI, WebSocket
app = FastAPI()
@app.websocket(“/ws”) async def websocket_endpoint(websocket: WebSocket):
await websocket.accept() while True:
data = await websocket.receive_text() await websocket.send_text(f”Message text was: {data}”)
- websocket_route(path: str, name: str | None = None) Callable[[DecoratedCallable], DecoratedCallable]
- class dct.FilterData(filtered_list_pathname: str = '', circuit_study_name: str = '')
Bases:
objectInformation about the filtered circuit designs.
- circuit_study_name: str
- filtered_list_files: list[str]
- filtered_list_pathname: str
- class dct.FlowControl(*, general: General, breakpoints: Breakpoints, conditional_breakpoints: CondBreakpoints, circuit: Circuit, capacitor: Capacitor, inductor: Inductor, transformer: Transformer, heat_sink: HeatSink, pre_summary: PreSummary, summary: Summary, configuration_data_files: ConfigurationDataFiles)
Bases:
BaseModelGeneral flow control class.
- breakpoints: Breakpoints
- conditional_breakpoints: CondBreakpoints
- configuration_data_files: ConfigurationDataFiles
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- pre_summary: PreSummary
- transformer: Transformer
- dct.Form(default: ~typing.Annotated[~typing.Any, Doc('\n Default value if the parameter field is not set.\n ')] = PydanticUndefined, *, default_factory: ~typing.Annotated[~collections.abc.Callable[[], ~typing.Any] | None, Doc("\n A callable to generate the default value.\n\n This doesn't affect `Path` parameters as the value is always required.\n The parameter is available only for compatibility.\n ")] = <fastapi.datastructures.DefaultPlaceholder object>, media_type: ~typing.Annotated[str, Doc("\n The media type of this parameter field. Changing it would affect the\n generated OpenAPI, but currently it doesn't affect the parsing of the data.\n ")] = 'application/x-www-form-urlencoded', alias: ~typing.Annotated[str | None, Doc("\n An alternative name for the parameter field.\n\n This will be used to extract the data and for the generated OpenAPI.\n It is particularly useful when you can't use the name you want because it\n is a Python reserved keyword or similar.\n ")] = None, alias_priority: ~typing.Annotated[int | None, Doc('\n Priority of the alias. This affects whether an alias generator is used.\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, validation_alias: ~typing.Annotated[str | ~pydantic.aliases.AliasPath | ~pydantic.aliases.AliasChoices | None, Doc("\n 'Whitelist' validation step. The parameter field will be the single one\n allowed by the alias or set of aliases defined.\n ")] = None, serialization_alias: ~typing.Annotated[str | None, Doc("\n 'Blacklist' validation step. The vanilla parameter field will be the\n single one of the alias' or set of aliases' fields and all the other\n fields will be ignored at serialization time.\n ")] = None, title: ~typing.Annotated[str | None, Doc('\n Human-readable title.\n ')] = None, description: ~typing.Annotated[str | None, Doc('\n Human-readable description.\n ')] = None, gt: ~typing.Annotated[float | None, Doc('\n Greater than. If set, value must be greater than this. Only applicable to\n numbers.\n ')] = None, ge: ~typing.Annotated[float | None, Doc('\n Greater than or equal. If set, value must be greater than or equal to\n this. Only applicable to numbers.\n ')] = None, lt: ~typing.Annotated[float | None, Doc('\n Less than. If set, value must be less than this. Only applicable to numbers.\n ')] = None, le: ~typing.Annotated[float | None, Doc('\n Less than or equal. If set, value must be less than or equal to this.\n Only applicable to numbers.\n ')] = None, min_length: ~typing.Annotated[int | None, Doc('\n Minimum length for strings.\n ')] = None, max_length: ~typing.Annotated[int | None, Doc('\n Maximum length for strings.\n ')] = None, pattern: ~typing.Annotated[str | None, Doc('\n RegEx pattern for strings.\n ')] = None, regex: ~typing.Annotated[str | None, Doc('\n RegEx pattern for strings.\n '), <typing_extensions.deprecated object at 0x7f4517b19c40>] = None, discriminator: ~typing.Annotated[str | None, Doc('\n Parameter field name for discriminating the type in a tagged union.\n ')] = None, strict: ~typing.Annotated[bool | None, Doc('\n If `True`, strict validation is applied to the field.\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, multiple_of: ~typing.Annotated[float | None, Doc('\n Value must be a multiple of this. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, allow_inf_nan: ~typing.Annotated[bool | None, Doc('\n Allow `inf`, `-inf`, `nan`. Only applicable to numbers.\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, max_digits: ~typing.Annotated[int | None, Doc('\n Maximum number of digits allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, decimal_places: ~typing.Annotated[int | None, Doc('\n Maximum number of decimal places allowed for decimal values.\n ')] = <fastapi.datastructures.DefaultPlaceholder object>, examples: ~typing.Annotated[list[~typing.Any] | None, Doc('\n Example values for this field.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/)\n ')] = None, example: ~typing.Annotated[~typing.Any | None, <typing_extensions.deprecated object at 0x7f4517b19d30>] = <fastapi.datastructures.DefaultPlaceholder object>, openapi_examples: ~typing.Annotated[dict[str, ~fastapi.openapi.models.Example] | None, Doc("\n OpenAPI-specific examples.\n\n It will be added to the generated OpenAPI (e.g. visible at `/docs`).\n\n Swagger UI (that provides the `/docs` interface) has better support for the\n OpenAPI-specific examples than the JSON Schema `examples`, that's the main\n use case for this.\n\n Read more about it in the\n [FastAPI docs for Declare Request Example Data](https://fastapi.tiangolo.com/tutorial/schema-extra-example/#using-the-openapi_examples-parameter).\n ")] = None, deprecated: ~typing.Annotated[~typing_extensions.deprecated | str | bool | None, Doc('\n Mark this parameter field as deprecated.\n\n It will affect the generated OpenAPI (e.g. visible at `/docs`).\n ')] = None, include_in_schema: ~typing.Annotated[bool, Doc("\n To include (or not) this parameter field in the generated OpenAPI.\n You probably don't need it, but it's available.\n\n This affects the generated OpenAPI (e.g. visible at `/docs`).\n ")] = True, json_schema_extra: ~typing.Annotated[dict[str, ~typing.Any] | None, Doc('\n Any additional JSON schema data.\n ')] = None, **extra: ~typing.Annotated[~typing.Any, Doc('\n Include extra fields used by the JSON Schema.\n '), <typing_extensions.deprecated object at 0x7f4517b19e50>]) Any
- class dct.General(*, project_directory: str, topology: Literal['dab', 'sbc'])
Bases:
BaseModelGeneral flow control information.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- project_directory: str
- topology: Literal['dab', 'sbc']
- class dct.HTMLResponse(content: Any = None, status_code: int = 200, headers: Mapping[str, str] | None = None, media_type: str | None = None, background: BackgroundTask | None = None)
Bases:
Response- media_type = 'text/html'
- class dct.HeatSink(*, number_of_trials: int, calculation_mode: Literal['new', 'continue', 'skip'], subdirectory: str)
Bases:
BaseModelFlow control for the heat sink.
- calculation_mode: Literal['new', 'continue', 'skip']
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- number_of_trials: int
- subdirectory: str
- class dct.HeatSinkBoundaryConditions(t_ambient: float, t_hs_max: float)
Bases:
objectFix parameters for the heat sink cooling.
- t_ambient: float
- t_hs_max: float
- class dct.HeatSinkOptimization
Bases:
objectOptimization support class for heat sink optimization.
- get_progress_data() ProgressData
Provide the progress data of the optimization.
- Returns:
Progress data: Processing start time, actual processing time and status. number of filtered heat sink Pareto front points are obsolete
- Return type:
- initialize_heat_sink_optimization(toml_heat_sink: TomlHeatSink, toml_prog_flow: FlowControl) bool
Initialize the configuration.
- Parameters:
toml_heat_sink (dct.TomlHeatSink) – toml heat sink class
toml_prog_flow (dct.FlowControl) – toml program flow class
- Returns:
True, if the configuration was successful initialized
- Return type:
bool
- optimization_handler(target_number_trials: int, debug: bool = False) None
Control the multi simulation processes.
- Parameters:
target_number_trials (int) – Number of trials for the optimization
debug (bool) – Debug mode flag
- static verify_optimization_parameter(toml_heat_sink: TomlHeatSink) tuple[bool, str]
Verify the input parameter ranges.
- Parameters:
toml_heat_sink (dct.TomlInductor) – toml inductor configuration
- Returns:
True, if the configuration was consistent
- Return type:
bool
- class dct.Inductor(*, numbers_of_trials: list[int], calculation_modes: list[Literal['new', 'continue', 'skip']], subdirectory: str)
Bases:
BaseModelFlow control for the inductor.
- calculation_modes: list[Literal['new', 'continue', 'skip']]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- numbers_of_trials: list[int]
- subdirectory: str
- class dct.InductorConfiguration(study_data: StudyData, simulation_calculation_mode: CalcModeEnum, inductor_toml_data: TomlInductor | None = None)
Bases:
objectStudy data and toml-file for inductor configuration.
- inductor_toml_data: TomlInductor | None = None
- simulation_calculation_mode: CalcModeEnum
- class dct.InductorOptimization
Bases:
objectOptimization of the inductor.
- fem_simulation_handler(circuit_study_name: str, inductor_in_circuit: int, debug: Debug) None
Control the multi simulation processes.
- Parameters:
circuit_study_name (str) – Name of the circuit study
inductor_in_circuit (int) – Number of inductor to optimize
debug (bool) – True to use debug mode which stops earlier
- get_number_of_performed_calculations() int
Provide the number of performed calculations.
- Returns:
int: Number of performed calculations
- Return type:
int
- get_progress_data(index: int, filtered_list_id: int) ProgressData
Provide the progress data of the optimization.
- Parameters:
index (int) – Index within the list of component configurations
filtered_list_id (int) – List index of the filtered operation point from circuit
- Returns:
Progress data: Processing start time, actual processing time, number of filtered inductor Pareto front points and status.
- Return type:
- initialize_inductor_optimization_list(configuration_data_list: list[InductorConfiguration], inductor_requirements_list: list[InductorRequirements]) None
Initialize the inductor optimization.
- Parameters:
configuration_data_list (list[InductorConfiguration]) – List of inductor configuration data including study data
inductor_requirements_list (list[InductorRequirements]) – list with inductor requirements
- optimization_handler_reluctance_model(circuit_study_name: str, inductor_in_circuit: int, debug: Debug) None
Control the multi simulation processes.
- Parameters:
circuit_study_name (str) – Name of the circuit study
inductor_in_circuit (int) – Number of inductor to optimize
debug (bool) – True to use debug mode which stops earlier
- static verify_optimization_parameter(toml_inductor: TomlInductor) tuple[bool, str]
Verify the input parameter ranges.
- Parameters:
toml_inductor (dct.TomlInductor) – toml inductor configuration
- Returns:
True, if the configuration was consistent
- Return type:
bool
- class dct.InductorOptimizationDto(trial_directory: str, circuit_id: str, inductor_number_in_circuit: int, progress_data: ProgressData, fmt_inductor_optimization_dto: InductorOptimizationDTO, number_of_trails: int, thermal_data: ComponentCooling, factor_dc_losses_min_max_list: list[float], inductor_requirements: InductorRequirements)
Bases:
objectDTO for the inductor optimization.
- circuit_id: str
- factor_dc_losses_min_max_list: list[float]
- fmt_inductor_optimization_dto: InductorOptimizationDTO
- inductor_number_in_circuit: int
- inductor_requirements: InductorRequirements
- number_of_trails: int
- progress_data: ProgressData
- thermal_data: ComponentCooling
- trial_directory: str
- class dct.InductorRequirements(**kwargs)
Bases:
objectRequirements for a single inductor design from the circuit results.
- The current waveform needs to be given for a full period:
time_vec (time based)
the current_vec gives the amplitude of the current at given time
- circuit_id: str
- current_array: ndarray
- current_vec: ndarray
- inductor_number_in_circuit: int
- study_name: str
- target_inductance: float
- time_array: ndarray
- time_vec: ndarray
- class dct.InductorResults(**kwargs)
Bases:
objectDTO contains the inductor losses.
- area_to_heat_sink: float
- circuit_id: str
- core_loss_array: ndarray
- inductor_id: int
- inductor_number_in_circuit: int
- loss_array: ndarray
- r_th_ind_heat_sink: float
- volume: float
- winding_loss_array: ndarray
- class dct.Jinja2Templates(directory: str | PathLike[str] | Sequence[str | PathLike[str]], *, context_processors: list[Callable[[Request], dict[str, Any]]] | None = None)
- class dct.Jinja2Templates(*, env: Environment, context_processors: list[Callable[[Request], dict[str, Any]]] | None = None)
Bases:
objectJinja2 template renderer.
Example
```python from starlette.templating import Jinja2Templates
templates = Jinja2Templates(directory=”templates”)
- async def homepage(request: Request) -> Response:
return templates.TemplateResponse(request, “index.html”)
- TemplateResponse(request: Request, name: str, context: dict[str, Any] | None = None, status_code: int = 200, headers: Mapping[str, str] | None = None, media_type: str | None = None, background: BackgroundTask | None = None) _TemplateResponse
Render a template and return an HTML response.
- Parameters:
request – The incoming request instance.
name – The template file name to render.
context – Variables to pass to the template.
status_code – HTTP status code for the response.
headers – Additional headers to include in the response.
media_type – Media type for the response.
background – Background task to run after response is sent.
- Returns:
An HTML response with the rendered template content.
- get_template(name: str) Template
- class dct.MagneticDataEntryDto(magnetic_configuration_name: str, number_calculations: int, number_performed_calculations: int, progress_data: ProgressData)
Bases:
objectDTO for queue summary information transfer.
- magnetic_configuration_name: str
- number_calculations: int
- number_performed_calculations: int
- progress_data: ProgressData
- class dct.Material(*values)
Bases:
str,EnumSet the name of the core material as enums.
- DMR96A = 'DMR96A'
- DMR96A2 = 'DMR96A2'
- DMR96A2_test = 'DMR96A2_test'
- ML95S = 'ML95S'
- N27 = 'N27'
- N30 = 'N30'
- N49 = 'N49'
- N87 = 'N87'
- N95 = 'N95'
- PC200 = 'PC200'
- T37 = 'T37'
- TEST = 'TEST'
- custom_material = 'custom_material'
- class dct.ParetoFrontSource(*values)
Bases:
EnumEnum of Pareto front types.
- pareto_circuit = 0
- pareto_heat_sink = 3
- pareto_inductor = 1
- pareto_summary = 4
- pareto_transformer = 2
- class dct.ParetoPlots
Bases:
objectGenerate PDF plots to see the results of single Pareto steps (circuit, inductor, transformer, heat sink).
- static generate_pareto_plot(x_values_list: list, y_values_list: list, color_list: list, alpha_list: list[float], x_label: str, y_label: str, label_list: list[str | None], fig_name_path: str, xlim: list | None = None, ylim: list | None = None) None
Generate multiple Pareto plot in one PDF file.
- Parameters:
x_values_list (list) – list of different Pareto plot x values
y_values_list (list) – list of different Pareto plot y values
color_list
alpha_list (list[float]) – The alpha blending value, between 0 (transparent) and 1 (opaque) for each sequence in a list
x_label (str) – x label of the Pareto plot
y_label (str) – y label of the Pareto plot
label_list (list[str | None]) – list of different Pareto plot labels in a legend
fig_name_path (str) – filename, will be saved as pdf
xlim (list[float]) – x-axis limitation [x_min, x_max]
ylim (list[float]) – y-axis limitation [y_min, y_max]
- static plot_capacitor_results(capacitor_study_data: StudyData, filtered_list_files: list[str], summary_directory: str) None
Plot the results of the transformer optimization in the Pareto plane.
- Parameters:
capacitor_study_data (StudyData) – Information about the capacitor study name and study path
filtered_list_files (list[str]) – List of filtered circuit design names
summary_directory (str) – Path of the summary directory (pre-summary or summary directory)
- static plot_circuit_results(circuit_optimization: CircuitOptimizationBase, summary_directory: str) None
Plot the results of the circuit optimization in the Pareto plane.
- Parameters:
circuit_optimization (CircuitOptimizationBase) – circuit optimization class
summary_directory (str) – Path of the summary directory (pre-summary or summary directory)
- static plot_heat_sink_results(heat_sink_study_data: StudyData, summary_directory: str) None
Plot the results of the heat sink optimization in the Pareto plane.
- Parameters:
heat_sink_study_data (StudyData) – Information about the heat sink study name and study path
summary_directory (str) – Path of the summary directory (pre-summary or summary directory)
- static plot_inductor_results(inductor_study_data: StudyData, filtered_list_files: list[str], summary_directory: str, is_summary: bool = False) None
Plot the results of the inductor optimization in the Pareto plane.
- Parameters:
inductor_study_data (StudyData) – Information about the inductor study name and study path
filtered_list_files (list[str]) – List of filtered circuit design names
summary_directory (str) – Path of the summary directory (pre-summary or summary directory)
is_summary (bool) – Flag to distinguish between pre summary and summary plot
- static plot_summary(summary_study_data: StudyData, circuit_optimization: CircuitOptimizationBase, combination_id: int = 0, is_summary: bool = False) None
Plot the combined results of circuit, inductor, transformer and heat sink in the Pareto plane.
- Parameters:
summary_study_data (StudyData) – Information about the summary study name and study path
circuit_optimization (CircuitOptimizationBase) – circuit optimization class
combination_id (int) – combination ID to highlight in the Pareto plane
is_summary (bool) – Flag to distinguish between pre summary and summary plot
- static plot_transformer_results(transformer_study_data: StudyData, filtered_list_files: list[str], summary_directory: str, is_summary: bool = False) None
Plot the results of the transformer optimization in the Pareto plane.
- Parameters:
transformer_study_data (StudyData) – Information about the transformer study name and study path
filtered_list_files (list[str]) – List of filtered circuit design names
summary_directory (str) – Path of the summary directory (pre-summary or summary directory)
is_summary (bool) – Flag to distinguish between pre summary and summary plot
- class dct.PlotData(x_values_list: list[list[float]], y_values_list: list[list[float]], color_list: list[str], alpha_list: list[float], x_label: str, y_label: str, label_list: list[str | None], fig_name_path: str, xlim: list | None = None, ylim: list | None = None)
Bases:
objectContains data to plot with plot function.
- alpha_list: list[float]
- color_list: list[str]
- fig_name_path: str
- label_list: list[str | None]
- x_label: str
- x_values_list: list[list[float]]
- xlim: list | None = None
- y_label: str
- y_values_list: list[list[float]]
- ylim: list | None = None
- dct.Pool(processes=None, initializer=None, initargs=(), maxtasksperchild=None)
Returns a process pool object
- class dct.PreSummary(*, calculation_mode: Literal['new', 'skip'], subdirectory: str)
Bases:
BaseModelFlow control for the pre-summary.
- calculation_mode: Literal['new', 'skip']
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- subdirectory: str
- class dct.ProgressData(run_time: float, number_of_filtered_points: int, progress_status: ProgressStatus)
Bases:
objectStatistic data of heat sink optimization.
- number_of_filtered_points: int
- progress_status: ProgressStatus
- run_time: float
- class dct.ProgressStatus(*values)
Bases:
EnumEnum of progress status.
- Done = 2
- Idle = 0
- InProgress = 1
- Skipped = 3
- dct.Queue(maxsize=0)
Returns a queue object
- class dct.QueueDetailData(circuit_data: CircuitConfigurationDataDto, inductor_list: list[ConfigurationDataEntryDto], transformer_list: list[ConfigurationDataEntryDto], heat_sink_list: list[ConfigurationDataEntryDto], summary_data: SummaryDataEntryDto, conf_process_time: float, break_point_notification: str)
Bases:
objectDTO for one shared memory data exchange within a queue.
- break_point_notification: str
- circuit_data: CircuitConfigurationDataDto
- conf_process_time: float
- heat_sink_list: list[ConfigurationDataEntryDto]
- inductor_list: list[ConfigurationDataEntryDto]
- summary_data: SummaryDataEntryDto
- transformer_list: list[ConfigurationDataEntryDto]
- class dct.QueueMainData(circuit_list: list[ConfigurationDataEntryDto], inductor_main_list: list[MagneticDataEntryDto], transformer_main_list: list[MagneticDataEntryDto], heat_sink_list: list[ConfigurationDataEntryDto], summary_list: list[SummaryDataEntryDto], total_process_time: float, break_point_notification: str)
Bases:
objectDTO for one shared memory data exchange within a queue.
- break_point_notification: str
- circuit_list: list[ConfigurationDataEntryDto]
- heat_sink_list: list[ConfigurationDataEntryDto]
- inductor_main_list: list[MagneticDataEntryDto]
- summary_list: list[SummaryDataEntryDto]
- total_process_time: float
- transformer_main_list: list[MagneticDataEntryDto]
- class dct.QueueParetoFrontData(pareto_front_optuna: str, evaluation_info: str, validity: bool)
Bases:
objectDTO for one shared memory data exchange within a queue.
- evaluation_info: str
- pareto_front_optuna: str
- validity: bool
- class dct.RedirectResponse(url: str | URL, status_code: int = 307, headers: Mapping[str, str] | None = None, background: BackgroundTask | None = None)
Bases:
Response
- class dct.Request(scope: ~collections.abc.MutableMapping[str, ~typing.Any], receive: ~collections.abc.Callable[[], ~collections.abc.Awaitable[~collections.abc.MutableMapping[str, ~typing.Any]]] = <function empty_receive>, send: ~collections.abc.Callable[[~collections.abc.MutableMapping[str, ~typing.Any]], ~collections.abc.Awaitable[None]] = <function empty_send>)
Bases:
HTTPConnection[StateT]- async body() bytes
- async close() None
- form(*, max_files: int | float = 1000, max_fields: int | float = 1000, max_part_size: int = 1048576) AwaitableOrContextManager[FormData]
- async is_disconnected() bool
- property method: str
- async send_push_promise(path: str) None
- async stream() AsyncGenerator[bytes, None]
- class dct.RequestCmd(*values)
Bases:
EnumEnum of possible commands.
- continue_opt = 3
- page_detail = 1
- page_main = 0
- pareto_front = 2
- dct.RunTime
alias of
RunTimeMeasurement
- class dct.RunTimeMeasure(total_time: float, circuit_time_list: list[float], inductor_time_list: list[float], transformer_time_list: list[float], heat_sink_time_list: list[float], summary_time_list: list[float])
Bases:
objectStatistic data of heat sink optimization.
- circuit_time_list: list[float]
- heat_sink_time_list: list[float]
- inductor_time_list: list[float]
- summary_time_list: list[float]
- total_time: float
- transformer_time_list: list[float]
- class dct.RunTimeMeasurement
Bases:
objectRuntime class for measure processing time.
- continue_trigger() None
Continue the timer without reset.
- get_runtime() float
Provide the current measured time since timer start.
- Returns:
time in seconds
- Return type:
float
- is_timer_active() bool
Provide the timer state.
- Returns:
True, if the time is active
- Return type:
bool
- reset_start_trigger() None
Reset and start the timer.
- stop_trigger() None
Stop the timer.
- class dct.SbcCircuitOptimization
Bases:
CircuitOptimizationBase[TomlSbcGeneral,TomlSbcCircuitParetoDesign]Optimize the SBC converter regarding maximum ZVS coverage and minimum conduction losses.
- add_time_domain_simulations() None
Add time domain simulations to the existing circuit DTOs.
- static calculate_fixed_parameters(act_sbc_config: CircuitParetoSbcDesign) FixedParameters
Calculate time-consuming parameters which are same for every single simulation.
- Parameters:
act_sbc_config (circuit_dtos.CircuitParetoSbcDesign) – Sbc circuit configuration
- Returns:
Fix parameters (transistor DTOs)
- Return type:
s_dtos.FixedParameters
- static calculate_voltage_to_duty_cycle_min_max_list(act_parameter_range: TomlSbcParameterRange) list[float]
Calculate the duty cycle list based on v1 and v2 lists.
- Parameters:
act_parameter_range (sbc_tc.TomlSbcParameterRange) – Parameter range of voltages and current
- Returns:
Duty cycle minimum-maximum list
- Return type:
list[float]
- static create_sqlite_database_url(act_study_data: StudyData) str
Create the SBC circuit optimization sqlite URL.
- Parameters:
act_study_data (StudyData) – Information about the circuit study name and study path
- Returns:
SQLite URL
- Return type:
str
- static df_plot_pareto_front(df: DataFrame, figure_size: tuple) None
Plot an interactive Pareto diagram (losses vs. volume) to select the transformers to re-simulate.
- Parameters:
df (pd.DataFrame) – DataFrame, generated from an optuna study (exported by optuna)
figure_size (tuple) – figure size as x,y-tuple in mm, e.g. (160, 80)
- df_to_sbc_dto_list(df: DataFrame) list[SbcCircuitDTO]
Load a SBC-DTO from an optuna study.
- Parameters:
df (pd.DataFrame) – Pandas DataFrame to convert to the SBC-DTO list
- Returns:
List of DTO
- Return type:
list[s_dtos.SbcCircuitDTO]
- static filter_equidistant_sampling(pareto_matrix: ndarray, n_points: int = 8) ndarray
Filter the study result.
For SBC a Pseudo Pareto front is provided. Each point have similar distance, if function is normalized. Filtering are separated in 2 ranges: The middle is identified by the normalized smallest distance to 0 Based on this middle both branches are taken for filter point 1 Design: normalized middle (NM) 2 Designs: Started from NM 1/3 between NM and max and similar to minimum 3 Designs: Minimum, middle and maximum 4 Designs: Minimum, 1/3 , 2/3 and maximum More than 4 Designs: Max, min and normalized equidistant arc length in between
- Parameters:
pareto_matrix (np.ndarray) – pareto front points with shape (n,2)
n_points (int) – Number of filtered points
- Returns:
filtered points
- Return type:
np.ndarray
- filter_study_results() tuple[bool, str]
Filter the study result.
For SBC a Pseudo Pareto front is provided, which is filtered for requested number of designs.
- static generate_circuit_toml(file_path: str) None
Generate the default SbcCircuitConf.toml file.
- Parameters:
file_path (str) – filename including absolute path
- static generate_general_toml(file_path: str) None
Generate the default SbcCircuitConf.toml file.
- Parameters:
file_path (str) – filename including absolute path
- generate_result_dtos(summary_data: StudyData, capacitor_selection_data_list: list[CapacitorConfiguration], inductor_configuration_list: list[InductorConfiguration], transformer_configuration_list: list[TransformerConfiguration], df: DataFrame, is_pre_summary: bool = True) None
Generate the result dtos from a given (filtered) result dataframe.
- Parameters:
summary_data (StudyData) – Summary Data
capacitor_selection_data_list (list[CapacitorConfiguration]) – List of capacitor selection data
inductor_configuration_list (list[InductorConfiguration]) – List of inductor study data
transformer_configuration_list (list[TransformerConfiguration]) – List of transformer study data
df (pd.DataFrame) – dataframe to take the results from
is_pre_summary (bool) – True for pre-summary, False for summary
- get_actual_pareto_html() str
Read the current Pareto front from running optimization process.
- Returns:
Pareto front html page
- Return type:
str
- get_capacitor_requirements() list[CapacitorRequirements]
Get the capacitor requirements.
- Returns:
Capacitor Requirements
- Return type:
- get_config() CircuitParetoSbcDesign | None
Return the actual loaded configuration file.
- Returns:
Configuration file as circuit_dtos.CircuitParetoSbcDesign
- Return type:
circuit_dtos.CircuitParetoSbcDesign
- get_inductor_requirements() list[InductorRequirements]
Get the inductor requirements.
- Returns:
Inductor Requirements
- Return type:
- static get_number_of_required_capacitors() int
Get the number of required capacitors.
- Returns:
Number of capacitors required by the actual topology
- Return type:
int
- static get_number_of_required_inductors() int
Get the number of required inductors.
- Returns:
Number of inductors required by the actual topology
- Return type:
int
- static get_number_of_required_transformers() int
Get the number of required transformers.
- Returns:
Number of transformers required by the actual topology
- Return type:
int
- static get_pareto_html(study_name: str, path_name: str) str
Read the current Pareto front from running optimization process.
- Parameters:
study_name (str) – Name of the optuna study
path_name (str) – Path where optuna study is located
- Returns:
Pareto front html page
- Return type:
str
- get_progress_data() ProgressData
Provide the progress data of the optimization.
- Returns:
Progress data: Processing start time, actual processing time, number of filtered operation points and status.
- Return type:
- get_transformer_requirements() list[TransformerRequirements]
Get the transformer requirements.
- Returns:
Transformer Requirements
- Return type:
- static hybrid_pareto_sampling(pareto_matrix: ndarray, n_points: int = 8) ndarray
Filter points from pareto front by hybrid-strategy: Extremes + Knees + Density.
This method filters points from a Pareto front using a hybrid strategy that combines three complementary selection criteria: extremes, knees, and density. Extremes: Points that represent the best values in at least one objective, ensuring that the boundary solutions with maximal trade-offs are preserved. Knees: Points located at significant curvature changes along the Pareto front, highlighting well-balanced compromises where small sacrifices in one objective yield large gains in others. Density: Points selected based on the distribution density of solutions to reduce redundancy by representing clusters with fewer, but diverse, representatives. By integrating these strategies, the function provides a compact, representative subset of the Pareto front that balances multiple selection approaches.
- Parameters:
pareto_matrix (np.ndarray) – pareto front points with shape (n,2)
n_points (int) – Number of filtered points
- Returns:
filtered points
- Return type:
np.ndarray
- initialize_circuit_optimization() bool
Initialize the circuit_dto for circuit optimization.
- Returns:
True, if the configuration was successful initialized
- Return type:
bool
- static is_pareto_efficient(costs: ndarray, return_mask: bool = True) ndarray
Find the pareto-efficient points.
- Parameters:
costs (np.array) – An (n_points, n_costs) array
return_mask (bool) – True to return a mask
- Returns:
An array of indices of pareto-efficient points. If return_mask is True, this will be an (n_points, ) boolean array Otherwise it will be a (n_efficient_points, ) integer array of indices.
- Return type:
np.array
- load_and_verify_circuit_parameters(toml_dict: dict[str, Any], is_tdb_to_update: bool = False) tuple[bool, str]
Load and verify the circuit input parameter.
- Parameters:
toml_dict (dict[str, Any]) – dictionary with circuit configuration
is_tdb_to_update (bool) – True to update the transistor database
- Returns:
True, if the configuration was consistent and empty string or False and report of the issues
- Return type:
tuple[bool, str]
- load_and_verify_general_parameters(toml_dict: dict[str, Any]) tuple[bool, str]
Verify the input parameter ranges.
- Parameters:
toml_dict (dict[str, Any]) – toml general configuration
- Returns:
True, if the configuration was consistent and empty string or False and report of the issues
- Return type:
tuple[bool, str]
- static load_csv_to_df(csv_filepath: str) DataFrame
Load a csv file (previously stored from a Pandas DataFrame) back to a Pandas DataFrame.
- Parameters:
csv_filepath (str) – File path of .csv file
- Returns:
loaded results from the given .csv file
- Return type:
pandas.DataFrame
- static load_sbc_dto_from_study(act_study_data: StudyData, sbc_config: CircuitParetoSbcDesign, trial_number: int | None = None) SbcCircuitDTO
Load a SBC-DTO from an optuna study.
- Parameters:
act_study_data (StudyData) – Information about the circuit study name and study path
sbc_config (circuit_dtos.CircuitParetoSbcDesign) – SBC optimization configuration file
trial_number (int) – trial number to load to the DTO
- Returns:
DTO
- Return type:
s_dtos.SbcCircuitDTO
- static load_stored_config(act_circuit_study_data: StudyData) CircuitParetoSbcDesign
Load pickle configuration file from disk.
- Parameters:
act_circuit_study_data (StudyData) – Information about the circuit study name and study path
- Returns:
Configuration file as circuit_dtos.CircuitParetoSbcDesign
- Return type:
circuit_dtos.CircuitParetoSbcDesign
- static pareto_front_from_df(df: DataFrame, x: str = 'values_0', y: str = 'values_1') DataFrame
Calculate the Pareto front from a Pandas DataFrame. Return a Pandas DataFrame.
- Parameters:
df (pd.DataFrame) – Pandas DataFrame
x (str) – Name of x-parameter from df to show in Pareto plane
y (str) – Name of y-parameter from df to show in Pareto plane
- Returns:
Pandas DataFrame with pareto efficient points
- Return type:
pd.DataFrame
- static plot_compare_waveforms(dto_directory: str) None
Compare calculated waveforms with simulated waveforms (GeckoCIRCUITS).
- Parameters:
dto_directory (str) – Folder of circuit DTOs to read the values from
- run_optimization(act_number_trials: int) DataFrame
Proceed a study which bases on functional data.
- Parameters:
act_number_trials (int) – Number of optimization trials
- save_config() None
Save the actual configuration file as pickle file on the disk.
- save_study_results_pareto(show_results: bool = False) None
Show the results of a study.
A local .html file is generated under config.working_directory to store the interactive plotly plots on disk.
- Parameters:
show_results (bool) – True to directly open the browser to show the study results.
- start_proceed_study(number_trials: int, database_type: str = 'sqlite', sampler: BaseSampler = <optuna.samplers._nsgaiii._sampler.NSGAIIISampler object>) None
Proceed a study which is stored as sqlite database.
- Parameters:
number_trials (int) – Number of trials adding to the existing study
database_type (str) – storage database, e.g. ‘sqlite’ or ‘mysql’
sampler (optuna.sampler-object) – optuna.samplers.NSGAIISampler() or optuna.samplers.NSGAIIISampler(). Note about the brackets () !! Default: NSGAIII
- static study_to_df(act_study_data: StudyData) DataFrame
Create a DataFrame from a study.
- Parameters:
act_study_data (StudyData) – Information about the circuit study name and study path
- Returns:
study result data transferred to Pandas dataframe
- Return type:
pd.DataFrame
- static visualize_all_lab_data(filepath: str) None
Generate plots or tables for the practical operation in the lab.
- Parameters:
filepath (str) – filepath
- static visualize_single_lab_data(filepath: str, combination_id: str) None
Generate plots or tables for the practical operation in the lab.
- Parameters:
filepath (str) – filepath
combination_id (str) – combination ID of object to plot
- class dct.ServerRequestData
Bases:
objectRequest command structure.
- c_configuration_index: int
- c_filtered_point_index: int
- item_configuration_index: int
- pareto_source: ParetoFrontSource
- request_cmd: RequestCmd
- class dct.SessionMiddleware(app: Callable[[MutableMapping[str, Any], Callable[[], Awaitable[MutableMapping[str, Any]]], Callable[[MutableMapping[str, Any]], Awaitable[None]]], Awaitable[None]], secret_key: str | Secret, session_cookie: str = 'session', max_age: int | None = 1209600, path: str = '/', same_site: Literal['lax', 'strict', 'none'] = 'lax', https_only: bool = False, domain: str | None = None)
Bases:
object
- class dct.StackedTransformerResults(**kwargs)
Bases:
objectDTO contains the stacked transformer losses.
- area_to_heat_sink: float
- circuit_id: str
- core_loss_array: ndarray
- loss_array: ndarray
- r_th_xfmr_heat_sink: float
- transformer_id: int
- transformer_number_in_circuit: int
- volume: float
- winding_1_loss_array: ndarray
- winding_2_loss_array: ndarray
- class dct.StaticFiles(*, directory: str | PathLike[str] | None = None, packages: list[str | tuple[str, str]] | None = None, html: bool = False, check_dir: bool = True, follow_symlink: bool = False)
Bases:
object- async check_config() None
Perform a one-off configuration check that StaticFiles is actually pointed at a directory, so that we can raise loud errors rather than just returning 404 responses.
- file_response(full_path: str | PathLike[str], stat_result: stat_result, scope: MutableMapping[str, Any], status_code: int = 200) Response
- get_directories(directory: str | PathLike[str] | None = None, packages: list[str | tuple[str, str]] | None = None) list[str | PathLike[str]]
Given directory and packages arguments, return a list of all the directories that should be used for serving static files from.
- get_path(scope: MutableMapping[str, Any]) str
Given the ASGI scope, return the path string to serve up, with OS specific path separators, and any ‘..’, ‘.’ components removed.
- async get_response(path: str, scope: MutableMapping[str, Any]) Response
Returns an HTTP response, given the incoming path, method and request headers.
- is_not_modified(response_headers: Headers, request_headers: Headers) bool
Given the request and response headers, return True if an HTTP “Not Modified” response could be returned instead.
- lookup_path(path: str) tuple[str, stat_result | None]
- class dct.StudyData(study_name: str, optimization_directory: str, calculation_mode: CalcModeEnum = CalcModeEnum.new_mode, number_of_trials: int = 0)
Bases:
objectData class containing all general information to perform a study.
- static check_study_data(study_path: str, study_name: str) bool
Verify if the study path and sqlite3-database file exists.
Works for all types of studies (circuit, inductor, transformer, heat sink). :param study_path: drive location folder to the study :type study_path: str :param study_name: Name of the study :type study_name: str :return: True, if the optimization could be performed successful :rtype: bool
- class dct.Summary(*, subdirectory: str)
Bases:
BaseModelFlow control for the summary.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- subdirectory: str
- class dct.SummaryDataEntryDto(configuration_name: str, number_of_combinations: int, progress_data: ProgressData)
Bases:
objectDTO for queue summary information transfer.
- configuration_name: str
- number_of_combinations: int
- progress_data: ProgressData
- class dct.ThermalCalcSupport
Bases:
objectProvides functions to calculate the thermal resistance.
- static calculate_r_th_copper_coin(cooling_area: float, height_pcb: float = 0.00155, height_pcb_heat_sink: float = 0.003) tuple[float, float]
Calculate the thermal resistance of the copper coin.
Assumptions are made with some geometry factors from a real copper coin for TO263 housing. :param cooling_area: cooling area in m² :type cooling_area: float :param height_pcb: PCB thickness, e.g. 1.55 mm :type height_pcb: float :param height_pcb_heat_sink: Distance from PCB to heat sink in m :type height_pcb_heat_sink: float :return: r_th_copper_coin, effective_copper_coin_cooling_area :rtype: tuple[float, float]
- static calculate_r_th_tim(copper_coin_bot_area: float, component_cooling: ComponentCooling) float
Calculate the thermal resistance of the thermal interface material (TIM).
- Parameters:
copper_coin_bot_area (float) – bottom area in m²
component_cooling (ComponentCooling) – Thermal material data: Specific thermal conductance and thickness
- Returns:
r_th of TIM material
- Return type:
float
- class dct.TomlCapacitorSelection(*, maximum_peak_to_peak_voltage_ripple: float, temperature_ambient: float, voltage_safety_margin_percentage: float, maximum_number_series_capacitors: int, lifetime_h: float, filter_distance: TomlFilterDistance)
Bases:
BaseModelCapacitor selection details.
- filter_distance: TomlFilterDistance
- lifetime_h: float
- maximum_number_series_capacitors: int
- maximum_peak_to_peak_voltage_ripple: float
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- temperature_ambient: float
- voltage_safety_margin_percentage: float
- class dct.TomlFilterDistance(*, factor_dc_losses_min_max_list: list[float])
Bases:
BaseModelToml checker class for FilterDistance.
- factor_dc_losses_min_max_list: list[float]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class dct.TomlHeatSink(*, design_space: TomlHeatSinkDesignSpace, settings: TomlHeatSinkSettings, boundary_conditions: TomlHeatSinkBoundaryConditions)
Bases:
BaseModelToml checker for HeatSink.
- boundary_conditions: TomlHeatSinkBoundaryConditions
- design_space: TomlHeatSinkDesignSpace
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- settings: TomlHeatSinkSettings
- class dct.TomlHeatSinkBoundaryConditions(*, t_ambient: float, t_hs_max: float, area_min: float)
Bases:
BaseModelToml checker for HeatSinkBoundaryConditions.
- area_min: float
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- t_ambient: float
- t_hs_max: float
- class dct.TomlHeatSinkDesignSpace(*, height_c_min_max_list: list[float], width_b_min_max_list: list[float], length_l_min_max_list: list[float], height_d_min_max_list: list[float], number_cooling_channels_n_min_max_list: list[int], thickness_fin_t_min_max_list: list[float])
Bases:
BaseModelToml checker for HeatSinkDesignSpace.
- height_c_min_max_list: list[float]
- height_d_min_max_list: list[float]
- length_l_min_max_list: list[float]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- number_cooling_channels_n_min_max_list: list[int]
- thickness_fin_t_min_max_list: list[float]
- width_b_min_max_list: list[float]
- class dct.TomlHeatSinkSettings(*, number_directions: int, factor_pcb_area_copper_coin: float, factor_bottom_area_copper_coin: float, thermal_conductivity_copper: float)
Bases:
BaseModelToml checker for HeatSinkSettings.
- factor_bottom_area_copper_coin: float
- factor_pcb_area_copper_coin: float
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- number_directions: int
- thermal_conductivity_copper: float
- class dct.TomlInductor(*, design_space: TomlInductorDesignSpace, insulations: TomlInductorInsulation, boundary_conditions: TomlInductorBoundaryConditions, thermal_data: TomlThermalData, filter_distance: TomlFilterDistance, material_data_sources: TomlMaterialDataSources)
Bases:
BaseModelToml checker class for Inductor.
- boundary_conditions: TomlInductorBoundaryConditions
- design_space: TomlInductorDesignSpace
- filter_distance: TomlFilterDistance
- insulations: TomlInductorInsulation
- material_data_sources: TomlMaterialDataSources
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- thermal_data: TomlThermalData
- class dct.TomlInductorBoundaryConditions(*, temperature: float)
Bases:
BaseModelToml checker class for InductorBoundaryConditions.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- temperature: float
- class dct.TomlInductorDesignSpace(*, core_name_list: list[str], material_name_list: list[Material], litz_wire_name_list: list[str], core_inner_diameter_min_max_list: list[float], window_h_min_max_list: list[float], window_w_min_max_list: list[float])
Bases:
BaseModelToml checker class for InductorDesignSpace.
- core_inner_diameter_min_max_list: list[float]
- core_name_list: list[str]
- litz_wire_name_list: list[str]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- window_h_min_max_list: list[float]
- window_w_min_max_list: list[float]
- class dct.TomlInductorInsulation(*, primary_to_primary: float, core_bot: float, core_top: float, core_right: float, core_left: float)
Bases:
BaseModelToml checker class for InductorInsulation.
- core_bot: float
- core_left: float
- core_right: float
- core_top: float
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- primary_to_primary: float
- class dct.TomlMaterialDataSources(*, permeability_datasource: DataSource, permittivity_datasource: DataSource)
Bases:
BaseModelToml checker class for MaterialDataSources.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- permeability_datasource: DataSource
- permittivity_datasource: DataSource
- class dct.TomlMisc(*, min_efficiency_percent: float, control_board_volume: float, control_board_loss: float)
Bases:
BaseModelData structure for Misc data.
- control_board_loss: float
- control_board_volume: float
- min_efficiency_percent: float
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class dct.TomlThermalData(*, thermal_cooling: list[float])
Bases:
BaseModelToml checker for HeatSinkThermalResistanceData.
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- thermal_cooling: list[float]
- class dct.TomlTransformer(*, design_space: TomlTransformerDesignSpace, insulation: TomlTransformerInsulation, boundary_conditions: TomlTransformerBoundaryConditions, thermal_data: TomlThermalData, filter_distance: TomlTransformerFilterDistance, settings: TomlTransformerSettings, material_data_sources: TomlMaterialDataSources)
Bases:
BaseModelToml checker class for Transformer.
- boundary_conditions: TomlTransformerBoundaryConditions
- design_space: TomlTransformerDesignSpace
- filter_distance: TomlTransformerFilterDistance
- insulation: TomlTransformerInsulation
- material_data_sources: TomlMaterialDataSources
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- settings: TomlTransformerSettings
- thermal_data: TomlThermalData
- class dct.TomlTransformerBoundaryConditions(*, max_transformer_total_height: float, max_core_volume: float, temperature: float)
Bases:
BaseModelToml checker class for TransformerBoundaryConditions.
- max_core_volume: float
- max_transformer_total_height: float
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- temperature: float
- class dct.TomlTransformerDesignSpace(*, material_name_list: list[Material], core_name_list: list[str], core_inner_diameter_min_max_list: list[float], window_w_min_max_list: list[float], window_h_bot_min_max_list: list[float], primary_litz_wire_list: list[str], secondary_litz_wire_list: list[str], n_p_top_min_max_list: list[int], n_p_bot_min_max_list: list[int])
Bases:
BaseModelToml checker class for TransformerDesignSpace.
- core_inner_diameter_min_max_list: list[float]
- core_name_list: list[str]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- n_p_bot_min_max_list: list[int]
- n_p_top_min_max_list: list[int]
- primary_litz_wire_list: list[str]
- secondary_litz_wire_list: list[str]
- window_h_bot_min_max_list: list[float]
- window_w_min_max_list: list[float]
- class dct.TomlTransformerFilterDistance(*, factor_dc_losses_min_max_list: list[float])
Bases:
BaseModelToml checker class for TransformerFilterDistance.
- factor_dc_losses_min_max_list: list[float]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class dct.TomlTransformerInsulation(*, iso_window_top_core_top: float, iso_window_top_core_bot: float, iso_window_top_core_left: float, iso_window_top_core_right: float, iso_window_bot_core_top: float, iso_window_bot_core_bot: float, iso_window_bot_core_left: float, iso_window_bot_core_right: float, iso_primary_to_primary: float, iso_secondary_to_secondary: float, iso_primary_to_secondary: float)
Bases:
BaseModelToml checker class for TransformerInsulation.
- iso_primary_to_primary: float
- iso_primary_to_secondary: float
- iso_secondary_to_secondary: float
- iso_window_bot_core_bot: float
- iso_window_bot_core_left: float
- iso_window_bot_core_right: float
- iso_window_bot_core_top: float
- iso_window_top_core_bot: float
- iso_window_top_core_left: float
- iso_window_top_core_right: float
- iso_window_top_core_top: float
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class dct.TomlTransformerSettings(*, fft_filter_value_factor: float, mesh_accuracy: float)
Bases:
BaseModelToml checker class for TransformerSettings.
- fft_filter_value_factor: float
- mesh_accuracy: float
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class dct.TopologyEnum(*values)
Bases:
EnumEnum for available topologies.
- dab = 'dab'
- sbc = 'sbc'
- class dct.Transformer(*, numbers_of_trials: list[int], calculation_modes: list[Literal['new', 'continue', 'skip']], subdirectory: str)
Bases:
BaseModelFlow control for the transformer.
- calculation_modes: list[Literal['new', 'continue', 'skip']]
- model_config = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- numbers_of_trials: list[int]
- subdirectory: str
- class dct.TransformerConfiguration(study_data: StudyData, simulation_calculation_mode: CalcModeEnum, transformer_toml_data: TomlTransformer | None = None)
Bases:
objectStudy data and toml-file for transformer configuration.
- simulation_calculation_mode: CalcModeEnum
- transformer_toml_data: TomlTransformer | None = None
- class dct.TransformerOptimization
Bases:
objectOptimization of the transformer.
- fem_simulation_handler(circuit_study_name: str, transformer_in_circuit: int, debug: Debug) None
Control the multi simulation processes.
- Parameters:
circuit_study_name (str) – Name of the circuit study
transformer_in_circuit (int) – Number of transformer component in circuit
debug (dct.Debug) – Debug DTO
- get_number_of_performed_calculations() int
Provide the number of performed calculations.
- Returns:
int: Number of performed calculations
- Return type:
int
- get_progress_data(index: int, filtered_list_id: int) ProgressData
Provide the progress data of the optimization.
- Parameters:
index (int) – Index within the list of component configurations
filtered_list_id (int) – List index of the filtered operation point from circuit
- Returns:
Progress data: Processing start time, actual processing time, number of filtered transformer Pareto front points and status.
- Return type:
- initialize_transformer_optimization_list(configuration_data_list: list[TransformerConfiguration], transformer_requirements_list: list[TransformerRequirements]) None
Initialize the transformer optimization.
- Parameters:
configuration_data_list (list[TransformerConfiguration]) – List of transformer configuration data including study data
transformer_requirements_list (list[TransformerRequirements]) – list with transformer requirements
- optimization_handler_reluctance_model(circuit_study_name: str, transformer_in_circuit: int, debug: Debug) None
Control the multi simulation processes.
- Parameters:
circuit_study_name (str) – Name of the circuit study
transformer_in_circuit (int) – Number of transformer component in circuit
debug (bool) – True to use debug mode which stops earlier
- static verify_optimization_parameter(toml_transformer: TomlTransformer) tuple[bool, str]
Verify the input parameter ranges.
- Parameters:
toml_transformer (dct.TomlTransformer) – toml transformer configuration
- Returns:
True, if the configuration was consistent
- Return type:
bool
- class dct.TransformerOptimizationDto(trial_directory: str, circuit_id: str, transformer_number_in_circuit: int, progress_data: ProgressData, fmt_transformer_optimization_dto: StoSingleInputConfig, number_of_trails: int, thermal_data: ComponentCooling, factor_dc_losses_min_max_list: list[float], transformer_requirements: TransformerRequirements)
Bases:
objectDTO for the transformer optimization.
- circuit_id: str
- factor_dc_losses_min_max_list: list[float]
- fmt_transformer_optimization_dto: StoSingleInputConfig
- number_of_trails: int
- progress_data: ProgressData
- thermal_data: ComponentCooling
- transformer_number_in_circuit: int
- transformer_requirements: TransformerRequirements
- trial_directory: str
- class dct.TransformerRequirements(**kwargs)
Bases:
objectRequirements for a single transformer design from the circuit results.
- The current waveform needs to be given for a full period:
time_vec (time based)
the current_vec gives the amplitude of the current at given time
- circuit_id: str
- current_1_array: ndarray
- current_1_vec: ndarray
- current_2_array: ndarray
- current_2_vec: ndarray
- l_h_target: float
- l_s12_target: float
- n_target: float
- study_name: str
- temperature: float
- time_array: ndarray
- time_vec: ndarray
- transformer_number_in_circuit: int
- dct.abspath(path)
Return an absolute path.
- dct.c_flag
alias of
CheckCondition
- dct.check_user_points_in_min_max_region(dim_min_max_list: list[float], dim_points_list: list[float]) None
Check if given operating point is within the limits of the operating area.
- Parameters:
dim_min_max_list (list[float]) – e.g. [175, 295]
dim_points_list (list[float]) – list of user-given operating points, e.g. [200, 230]
- Raises:
ValueError – in case of list is out of min/max limits
- dct.colors() dict
Colors according to the GNOME color scheme (Color 4).
- dct.cpu_count()
Returns the number of CPUs in the system
- dct.current_process()
Return process object representing the current process
- dct.dessca(dim_1_min: float, dim_1_max: float, dim_2_min: float, dim_2_max: float, dim_3_min: float, dim_3_max: float, total_number_points: int, dim_1_user_given_points_list: list[float], dim_2_user_given_points_list: list[float], dim_3_user_given_points_list: list[float]) tuple[ndarray, ndarray, ndarray]
Latin hypercube sampling for a given 3-dimensional user input.
- Parameters:
dim_1_min – dimension 1 minimum, e.g. 690
dim_1_max – dimension 1 maximum, e.g. 710
dim_2_min – dimension 2 minimum, e.g. 175
dim_2_max – dimension 2 maximum, e.g. 295
dim_3_min – dimension 3 minimum, e.g. -2000
dim_3_max – dimension 3 maximum, e.g. 2000
total_number_points – point to sample by the sampler
dim_1_user_given_points_list – user-given points for dimension 1, e.g. [695, 705]
dim_2_user_given_points_list – user-given points for dimension 2, e.g. [289, 299]
dim_3_user_given_points_list – user-given points for dimension 3, e.g. [-1300, 1530]
- Returns:
dim_1_all_points, dim_2_all_points, dim_3_all_points
- Return type:
tuple[np.ndarray, np.ndarray, np.ndarray]
- dct.generate_default_capacitor_toml(file_path: str) None
Generate the default capacitor selection toml file.
- Parameters:
file_path (str) – filename including absolute path
- dct.generate_default_flow_control_toml(working_directory: str) None
Generate the default progFlow.toml file.
- Parameters:
working_directory (str) – working directory
- dct.generate_default_heat_sink_toml(file_path: str) None
Generate the default heat sink configuration toml file.
- Parameters:
file_path (str) – filename including absolute path
- dct.generate_default_inductor_toml(file_path: str) None
Generate the default inductor configuration toml file.
- Parameters:
file_path (str) – working directory
- dct.generate_default_transformer_toml(file_path: str) None
Generate the default transformer configuration toml file.
- Parameters:
file_path (str) – filename including absolute path
- dct.generate_logging_config(working_directory: str) None
Generate the default logging configuration file.
- Parameters:
working_directory (str) – working directory
- dct.generate_missing_toml_files(working_directory: str) None
Check for missing toml default files. Generate them, if missing.
- Parameters:
working_directory (str) – working directory
- dct.global_plot_settings_font_latex() None
Set the plot fonts to LaTeX-font.
- dct.global_plot_settings_font_sansserif() None
Set the plot fonts to Sans-Serif-Font.
- dct.latin_hypercube(dim_1_min: float, dim_1_max: float, dim_2_min: float, dim_2_max: float, dim_3_min: float, dim_3_max: float, total_number_points: int, dim_1_user_given_points_list: list[float], dim_2_user_given_points_list: list[float], dim_3_user_given_points_list: list[float], sampling_random_seed: int | None) tuple[ndarray, ndarray, ndarray]
Latin hypercube sampling for a given 3-dimensional user input.
- Parameters:
dim_1_min – dimension 1 minimum, e.g. 690
dim_1_max – dimension 1 maximum, e.g. 710
dim_2_min – dimension 2 minimum, e.g. 175
dim_2_max – dimension 2 maximum, e.g. 295
dim_3_min – dimension 3 minimum, e.g. -2000
dim_3_max – dimension 3 maximum, e.g. 2000
total_number_points – point to sample by the sampler
dim_1_user_given_points_list – user-given points for dimension 1, e.g. [695, 705]
dim_2_user_given_points_list – user-given points for dimension 2, e.g. [289, 299]
dim_3_user_given_points_list – user-given points for dimension 3, e.g. [-1300, 1530]
sampling_random_seed (int) – random seed for the hypercube sampling (reproducible)
- Returns:
dim_1_all_points, dim_2_all_points, dim_3_all_points
- Return type:
tuple[np.ndarray, np.ndarray, np.ndarray]
- dct.plot_samples(dim_1_min_max_list: list[float], dim_2_min_max_list: list[float], dim_3_min_max_list: list[float], number_user_points: int, dim_1_points_list: list[float], dim_2_points_list: list[float], dim_3_points_list: list[float]) None
Plot sampling in a 3D-room.
- Parameters:
dim_1_min_max_list (list[float]) – dimension 1 as min-max-list, e.g. [690, 710]
dim_2_min_max_list (list[float]) – dimension 2 as min-max-list, e.g. [175, 295]
dim_3_min_max_list (list[float]) – dimension 3 as min-max-list, e.g. [-2000, 2000]
number_user_points (int) – Number of user given points (color change)#
dim_1_points_list (list[float]) – sampled points in dimension 1 (e.g. by latin hypercube)
dim_2_points_list (list[float]) – sampled points in dimension 2 (e.g. by latin hypercube)
dim_3_points_list (list[float]) – sampled points in dimension 3 (e.g. by latin hypercube)
- dct.visualize_waveform_verification(working_directory: str) None
Verify the simulated vs. calculated waveform by visual plots.
- Parameters:
working_directory (str) – working directory